File size: 3,817 Bytes
9b5db35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
from utils import read_jsonl
import argparse
from typing import Tuple, Dict
import subprocess
import os
import xml.etree.ElementTree as ET


def run_py_repo_test(
        repo_path: str,
        test_target: str,
        timeout: float = 10.0
) -> Tuple[Dict, str]:
    test_cmd = f'''\
source .venv/bin/activate
pytest {test_target} --junitxml=results.xml
'''
    print(f'>>> {repo_path}')
    print(test_cmd)
    score = 0.0
    total = 0
    passed = 0
    test_output = ''
    test_output_file = os.path.join(repo_path, 'results.xml')
    try:
        if os.path.exists(test_output_file):
            os.remove(test_output_file)
        result = subprocess.run(
            test_cmd,
            shell=True,
            executable='/bin/bash',
            text=True,
            cwd=os.path.abspath(repo_path),
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            timeout=timeout,
        )
    except Exception as e:
        print(e)
        pass
    if os.path.exists(test_output_file):
        try:
            tree = ET.parse(test_output_file)
            root = tree.getroot()
            suite = root.find('testsuite')

            if suite is None:
                raise ValueError("Invalid XML: No <testsuite> element found")

            total = int(suite.attrib.get('tests', 0))
            failures = int(suite.attrib.get('failures', 0))
            errors = int(suite.attrib.get('errors', 0))
            skipped = int(suite.attrib.get('skipped', 0))
            passed = total - failures - errors - skipped
            score = passed / total if total > 0 else 0.0

            error_messages = []
            for case in suite.findall('testcase'):
                failure = case.find('failure')
                error = case.find('error')
                if failure is not None:
                    error_messages.append(
                        f"Failure:\n" + \
                        '\n'.join(['...\n'] + failure.text.splitlines()[-4:])
                    )
                elif error is not None:
                    error_messages.append(
                        f"Failure:\n" + \
                        '\n'.join(['...\n'] + error.text.splitlines()[-4:])
                    )
            test_output = (
                f"Total {total}, Passed: {passed}, Failures: {failures}, Errors: {errors}, Skipped: {skipped}\n"
                f"Pass Rate: {score}"
            )
            if error_messages:
                test_output += "\n\nError Message:\n" + "\n".join(error_messages)
        except Exception:
            pass
    else:
        try:
            max_lines = 20
            test_output = result.stdout.strip()
            test_output = '\n'.join(test_output.splitlines()[- max_lines : ]).strip()
        except Exception:
            test_output = 'The "pytest" command run failed.'
    return {
        'score': score,
        'passed': passed,
        'total': total,
    }, test_output


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--repo_cache_dir', type=str, default='/tmp/pywork1/py500')
    parser.add_argument('--start_index', type=int, default=0)
    parser.add_argument('--end_index', type=int, default=500)
    args = parser.parse_args()

    py500 = read_jsonl('data/py500.jsonl')

    failed = []
    for i in range(args.start_index, args.end_index):
        data = py500[i]
        print(f'=== {i} ===')
        repo_path = str(os.path.join(args.repo_cache_dir, data['repo_name']))
        res, output = run_py_repo_test(repo_path=repo_path, test_target=data['test_target'])
        print(output)
        try:
            assert res['score'] == 1.0
        except Exception as e:
            print(e)
            failed.append(i)

        print('=== Failed ===')
        print(failed)