CoolFace
Apppublic

sanket3280/code-execution

sourceHugging Faceupdated 10mo agoView on Hugging Face
0likes
javaHarness.js143 linesDownload Raw Back to testHarness
1const { extractFunctionName } = require('./baseHarness');2 3const createJavaTestHarness = (sourceCode, testCases) => {4  const functionName = extractFunctionName.java(sourceCode);5  6  let cleanCode = sourceCode7    .replace(/\bpublic\s+class\s+Main\s*\{[\s\S]*?\}/g, '')8    .replace(/\bpublic\s+static\s+void\s+main\s*\([^)]*\)\s*\{[\s\S]*?\}/g, '')9    .replace(/\bclass\s+Main\s*\{[\s\S]*?\}/g, '');10  11  // Check if this is a LinkedList problem - if so, skip batch execution entirely12  const hasLinkedListInput = testCases.some(tc => {13    try {14      const input = JSON.parse(tc.input);15      return Object.keys(input).some(key => key.includes('list'));16    } catch (e) {17      return false;18    }19  });20  21  // For LinkedList problems, throw error to force individual execution (avoids timeouts)22  if (hasLinkedListInput) {23    throw new Error('LinkedList problems should use individual execution to avoid timeouts');24  }25  26  let harness = '';27  28  // Add common imports if not present29  if (!sourceCode.includes('import java.util')) {30    harness += 'import java.util.*;\n\n';31  }32  33  // Add ListNode class if not already present34  if (!cleanCode.includes('class ListNode')) {35    harness += 'class ListNode {\n';36    harness += '    int val;\n';37    harness += '    ListNode next;\n';38    harness += '    ListNode(int val) { this.val = val; }\n';39    harness += '}\n\n';40  }41  42  harness += cleanCode + '\n\n';43  harness += 'public class Main {\n';44  45  harness += '    static ListNode createLinkedList(int[] arr) {\n';46  harness += '        if (arr == null || arr.length == 0) return null;\n';47  harness += '        ListNode head = new ListNode(arr[0]);\n';48  harness += '        ListNode current = head;\n';49  harness += '        for (int i = 1; i < arr.length; i++) {\n';50  harness += '            current.next = new ListNode(arr[i]);\n';51  harness += '            current = current.next;\n';52  harness += '        }\n';53  harness += '        return head;\n';54  harness += '    }\n\n';55  56  harness += '    static String linkedListToString(ListNode head) {\n';57  harness += '        if (head == null) return "[]";\n';58  harness += '        StringBuilder sb = new StringBuilder("[");\n';59  harness += '        while (head != null) {\n';60  harness += '            sb.append(head.val);\n';61  harness += '            if (head.next != null) sb.append(",");\n';62  harness += '            head = head.next;\n';63  harness += '        }\n';64  harness += '        sb.append("]");\n';65  harness += '        return sb.toString();\n';66  harness += '    }\n\n';67  68  harness += '    public static void main(String[] args) {\n';69  harness += '        Solution solution = new Solution();\n';70  harness += '        System.out.println("TEST_RESULTS_START");\n';71  72  testCases.forEach((tc, i) => {73    const input = JSON.parse(tc.input);74    const expected = tc.expected;75    76    harness += `        try {\n`;77    78    // Handle different input types79    const inputKeys = Object.keys(input);80    if (inputKeys.includes('lists') && Array.isArray(input.lists)) {81      // Handle array of arrays for mergeKLists82      harness += `            ListNode[] lists = new ListNode[${input.lists.length}];\n`;83      input.lists.forEach((list, idx) => {84        if (list && list.length > 0) {85          harness += `            lists[${idx}] = createLinkedList(new int[]{${list.join(',')}});\n`;86        } else {87          harness += `            lists[${idx}] = null;\n`;88        }89      });90      harness += `            ListNode result = solution.${functionName}(lists);\n`;91      harness += `            String output = linkedListToString(result);\n`;92    } else {93      // Regular input handling - detect parameter types from source code94      const inputValues = Object.values(input);95      const args = inputValues.map(v => {96        if (Array.isArray(v)) {97          return `new int[]{${v.join(',')}}`;98        } else if (typeof v === 'string') {99          return `"${v}"`;100        } else {101          return v;102        }103      }).join(', ');104      105      // Detect return type from source code106      const returnTypeMatch = sourceCode.match(new RegExp(`public\\s+(\\w+(?:<[^>]+>)?(?:\\[\\])?(?:\\s*\\[\\])?(?:\\s*<[^>]+>)?)\\s+${functionName}\\s*\\(`));107      const returnType = returnTypeMatch ? returnTypeMatch[1].trim() : 'Object';108      109      // Handle different return types110      if (returnType.includes('int[]') || returnType.includes('Integer[]')) {111        harness += `            int[] result = solution.${functionName}(${args});\n`;112        harness += `            String output = java.util.Arrays.toString(result);\n`;113      } else if (returnType === 'int' || returnType === 'Integer') {114        harness += `            int result = solution.${functionName}(${args});\n`;115        harness += `            String output = String.valueOf(result);\n`;116      } else if (returnType === 'boolean' || returnType === 'Boolean') {117        harness += `            boolean result = solution.${functionName}(${args});\n`;118        harness += `            String output = String.valueOf(result);\n`;119      } else if (returnType === 'String') {120        harness += `            String result = solution.${functionName}(${args});\n`;121        harness += `            String output = result;\n`;122      } else {123        harness += `            Object result = solution.${functionName}(${args});\n`;124        harness += `            String output = result instanceof int[] ? java.util.Arrays.toString((int[])result) : String.valueOf(result);\n`;125      }126    }127    128    harness += `            boolean passed = output.equals("${expected}");\n`;129    harness += `            System.out.println("TEST_${i+1}:" + (passed ? "PASS" : "FAIL") + ":" + output + ":${expected}");\n`;130    harness += `        } catch (Exception e) {\n`;131    harness += `            System.out.println("TEST_${i+1}:ERROR:" + e.getMessage());\n`;132    harness += `        }\n`;133  });134  135  harness += '        System.out.println("TEST_RESULTS_END");\n';136  harness += '    }\n';137  harness += '}';138  139  return harness;140};141 142module.exports = { createJavaTestHarness };143