Team Ai
Apppublic

sanket3280/code-execution

sourceHugging Faceupdated 11mo agoView on Hugging Face
0likes
pythonHarness.js147 linesDownload Raw Back to testHarness
1/**2 * Python Test Harness Generator3 * Creates optimized test harness for Python code execution4 */5 6const { getHelpers, extractFunctionName } = require('./baseHarness');7 8/**9 * Create Python test harness for batch execution10 */11const createPythonTestHarness = (sourceCode, testCases) => {12  let harness = '';13  14  // Add detected helpers15  const helpers = getHelpers(sourceCode, 'python');16  if (helpers) {17    harness += helpers + '\n\n';18  }19  20  // Add user's source code21  harness += sourceCode + '\n\n';22  23  // Add test cases data24  harness += '# Test cases\n';25  harness += 'test_cases = [\n';26  27  testCases.forEach((testCase, index) => {28    const input = JSON.parse(testCase.input);29    const expected = testCase.expected;30    harness += `    {"input": ${JSON.stringify(input)}, "expected": ${JSON.stringify(expected)}, "index": ${index}},\n`;31  });32  33  harness += ']\n\n';34  35  // Add test execution logic36  harness += createTestExecutionLogic(sourceCode);37  38  return harness;39};40 41/**42 * Create test execution logic43 */44const createTestExecutionLogic = (sourceCode) => {45  const functionName = extractFunctionName.python(sourceCode);46  47  return `48import json49 50class ListNode:51    def __init__(self, val=0, next=None):52        self.val = val53        self.next = next54 55def create_linked_list(arr):56    if not arr:57        return None58    head = ListNode(arr[0])59    current = head60    for i in range(1, len(arr)):61        current.next = ListNode(arr[i])62        current = current.next63    return head64 65def linked_list_to_array(head):66    result = []67    while head:68        result.append(head.val)69        head = head.next70    return result71 72# Test execution73print('TEST_RESULTS_START')74 75for i, test_case in enumerate(test_cases):76    try:77        # Process input (handle special types)78        processed_input = {}79        for key, value in test_case['input'].items():80            if key == 'root' and isinstance(value, list):81                processed_input[key] = build_binary_tree(value)82            elif key == 'lists' and isinstance(value, list) and len(value) > 0 and isinstance(value[0], list):83                # Handle array of arrays (like mergeKLists)84                processed_input[key] = [create_linked_list(arr) for arr in value]85            elif 'list' in key and isinstance(value, list) and (not value or not isinstance(value[0], list)):86                # Handle single linked list87                processed_input[key] = create_linked_list(value)88            else:89                processed_input[key] = value90        91        # Execute function - with case-insensitive fallback92        target_function = None93        try:94            target_function = ${functionName}95        except NameError:96            # Try case-insensitive search97            expected_name = '${functionName}'98            expected_lower = expected_name.lower()99            100            for name in dir():101                if not name.startswith('_') and name.lower() == expected_lower:102                    obj = eval(name)103                    if callable(obj):104                        target_function = obj105                        if i == 0:106                            print(f'WARNING: Function name case mismatch. Expected "{expected_name}" but found "{name}". Please use exact function name.', flush=True)107                        break108            109            if not target_function:110                raise NameError(f'Function "${functionName}" not found. Please check function name spelling and capitalization.')111        112        result = target_function(**processed_input)113        114        # Format output115        if hasattr(result, 'val'):116            # It's a ListNode117            output = '[' + ','.join(map(str, linked_list_to_array(result))) + ']'118        elif isinstance(result, list):119            output = '[' + ','.join(map(str, result)) + ']'120        elif isinstance(result, str):121            output = json.dumps(result)122        else:123            output = str(result)124        125        # Format expected126        expected = test_case['expected']127        if isinstance(expected, str) and expected.startswith('"'):128            expected_str = expected129        else:130            expected_str = json.dumps(expected) if isinstance(expected, str) else str(expected)131        132        # Compare133        passed = output == expected_str134        135        print(f'TEST_{i+1}:{"PASS" if passed else "FAIL"}:{output}:{expected_str}')136        137    except Exception as e:138        print(f'TEST_{i+1}:ERROR:{str(e)}')139 140print('TEST_RESULTS_END')141`;142};143 144module.exports = {145  createPythonTestHarness146};147