lbaf23 commited on
Commit
9b5db35
·
verified ·
1 Parent(s): f31a389

Upload 4 files

Browse files
Files changed (4) hide show
  1. evaluate.py +209 -0
  2. install.py +41 -0
  3. py500.jsonl +0 -0
  4. run.py +116 -0
evaluate.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple
2
+ import ast
3
+
4
+
5
+ class AssertNormalizerPython:
6
+ def normalize_assert(self, stmt: str, mask_str: bool = False) -> str:
7
+ try:
8
+ tree = ast.parse(stmt)
9
+ except SyntaxError:
10
+ return stmt
11
+
12
+ if not tree.body or not isinstance(tree.body[0], (ast.Assert, ast.Expr)):
13
+ return stmt
14
+
15
+ node = tree.body[0]
16
+
17
+ cps = []
18
+ # assert ... ===
19
+ if isinstance(node, ast.Assert):
20
+ if isinstance(node.test, ast.Compare):
21
+ left = self._expr_to_str(node.test.left, mask_str)
22
+ comps = [self._expr_to_str(comp, mask_str) for comp in node.test.comparators]
23
+ ops = node.test.ops
24
+ length = min(len(comps), len(ops))
25
+ for i in range(length):
26
+ cps.append({'left': left, 'op': ops[i], 'right': comps[i]})
27
+ left = comps[i]
28
+
29
+ elif type(node.test) == ast.UnaryOp:
30
+ if type(node.test.op) == ast.Not:
31
+ test_str = self._expr_to_str(node.test.operand, mask_str)
32
+ cps.append({'left': test_str, 'op': ast.Not(), 'right': ''})
33
+ else:
34
+ test_str = self._expr_to_str(node.test, mask_str)
35
+ cps.append({'left': test_str, 'op': '', 'right': ''})
36
+ elif type(node.test) == ast.BoolOp:
37
+ left = self._expr_to_str(node.test.values[0], mask_str)
38
+ right = self._expr_to_str(node.test.values[1], mask_str)
39
+ cps.append({'left': left, 'op': node.test.op, 'right': right})
40
+ else:
41
+ test_str = self._expr_to_str(node.test, mask_str)
42
+ cps.append({'left': test_str, 'op': '', 'right': ''})
43
+
44
+ # unittest
45
+ if isinstance(node, ast.Expr) and isinstance(node.value, ast.Call):
46
+ call = node.value
47
+ method = self._get_method_name(call.func)
48
+ if not method:
49
+ return stmt
50
+
51
+ args = [self._expr_to_str(a, mask_str) for a in call.args]
52
+
53
+ # === assertTrue / assertFalse / assertIsNone / assertIsNotNone ===
54
+ if method in ["assertTrue", "assertFalse", "assertIsNone", "assertIsNotNone"]:
55
+ target = args[-1] if len(args) > 0 else "?"
56
+ if method == "assertTrue":
57
+ cps.append({'left': target, 'op': ast.Is(), 'right': 'True'})
58
+ elif method == "assertFalse":
59
+ cps.append({'left': target, 'op': ast.IsNot(), 'right': 'True'})
60
+ elif method == "assertIsNone":
61
+ cps.append({'left': target, 'op': ast.Is(), 'right': 'None'})
62
+ elif method == "assertIsNotNone":
63
+ cps.append({'left': target, 'op': ast.IsNot(), 'right': 'None'})
64
+
65
+ # === assertEqual / assertNotEqual ===
66
+ elif method == 'assertEqual':
67
+ cps.append({'left': args[0], 'op': ast.Eq(), 'right': args[1]})
68
+ elif method == 'assertNotEqual':
69
+ cps.append({'left': args[0], 'op': ast.NotEq(), 'right': args[1]})
70
+
71
+ # === assertIs / assertIsNot ===
72
+ elif method == 'assertIs':
73
+ cps.append({'left': args[0], 'op': ast.Is(), 'right': args[1]})
74
+
75
+ elif method == 'assertIsNot':
76
+ cps.append({'left': args[0], 'op': ast.IsNot(), 'right': args[1]})
77
+
78
+ # === assertIn / assertNotIn ===
79
+ elif method == 'assertIn':
80
+ cps.append({'left': args[0], 'op': ast.In(), 'right': args[1]})
81
+
82
+ elif method == 'assertNotIn':
83
+ cps.append({'left': args[0], 'op': ast.In(), 'right': args[1]})
84
+
85
+ # === assertAlmostEqual ===
86
+ elif method == 'assertAlmostEqual':
87
+ cps.append({'left': args[0], 'op': ast.Eq(), 'right': args[1]})
88
+
89
+
90
+ # Final result
91
+ str_cps = []
92
+ for cp in cps:
93
+ left, op, right = cp['left'], cp['op'], cp['right']
94
+ if left == 'False':
95
+ left = 'True'
96
+ op = self._not_op(op)
97
+
98
+ if right == 'False':
99
+ right = 'True'
100
+ op = self._not_op(op)
101
+
102
+ if left > right:
103
+ rv, rvop = self._reverse_op(op)
104
+ if rv:
105
+ str_cps.append(f'{right} {rvop} {left}')
106
+ else:
107
+ str_cps.append(f"{left} {self._op_to_str(op)} {right}")
108
+ else:
109
+ str_cps.append(f"{left} {self._op_to_str(op)} {right}")
110
+
111
+ str_cps = sorted(str_cps)
112
+ return ' && '.join(str_cps)
113
+
114
+ def _get_method_name(self, func):
115
+ if isinstance(func, ast.Attribute):
116
+ return func.attr
117
+ elif isinstance(func, ast.Name):
118
+ return func.id
119
+ else:
120
+ return None
121
+
122
+ def _expr_to_str(self, expr, mask_str: bool):
123
+ if isinstance(expr, ast.Constant):
124
+ if isinstance(expr.value, str):
125
+ return '"STR"' if mask_str else repr(expr.value)
126
+ return repr(expr.value)
127
+ elif isinstance(expr, ast.Name):
128
+ return expr.id
129
+ elif isinstance(expr, ast.Attribute):
130
+ return f"{self._expr_to_str(expr.value, mask_str)}.{expr.attr}"
131
+ elif isinstance(expr, ast.Call):
132
+ func_str = self._expr_to_str(expr.func, mask_str)
133
+ args_str = ",".join(self._expr_to_str(a, mask_str) for a in expr.args)
134
+ return f"{func_str}({args_str})"
135
+ elif isinstance(expr, ast.Compare):
136
+ left = self._expr_to_str(expr.left, mask_str)
137
+ ops = " ".join(self._op_to_str(op) for op in expr.ops)
138
+ rights = " ".join(self._expr_to_str(c, mask_str) for c in expr.comparators)
139
+ return f"{left} {ops} {rights}"
140
+ elif isinstance(expr, ast.BinOp):
141
+ left = self._expr_to_str(expr.left, mask_str)
142
+ right = self._expr_to_str(expr.right, mask_str)
143
+ op = self._op_to_str(expr.op)
144
+ return f"{left} {op} {right}"
145
+ elif isinstance(expr, ast.UnaryOp):
146
+ op = self._op_to_str(expr.op)
147
+ operand = self._expr_to_str(expr.operand, mask_str)
148
+ return f"{op}{operand}"
149
+ else:
150
+ return ast.unparse(expr) if hasattr(ast, "unparse") else str(expr)
151
+
152
+ def _op_to_str(self, op):
153
+ return {
154
+ ast.Add: "+", ast.Sub: "-", ast.Mult: "*", ast.Div: "/", ast.Mod: "%",
155
+ ast.Eq: "==", ast.NotEq: "!=", ast.Gt: ">", ast.GtE: ">=", ast.Lt: "<", ast.LtE: "<=",
156
+ ast.Is: "is", ast.IsNot: "is not", ast.In: "in", ast.NotIn: "not in",
157
+ ast.And: "and", ast.Or: "or", ast.Not: "not ", ast.USub: "-", ast.UAdd: "+",
158
+ }.get(type(op), str(op))
159
+
160
+ def _not_op(self, op):
161
+ if type(op) is ast.NotEq:
162
+ return ast.Eq()
163
+ elif type(op) is ast.Eq:
164
+ return ast.NotEq()
165
+ elif type(op) is ast.Is:
166
+ return ast.IsNot()
167
+ elif type(op) is ast.IsNot:
168
+ return ast.Is()
169
+ else:
170
+ return op
171
+
172
+ def _reverse_op(self, op) -> Tuple:
173
+ if type(op) in {ast.Eq, ast.NotEq, ast.Gt, ast.GtE, ast.Lt, ast.LtE, ast.Is, ast.IsNot, ast.And, ast.Or}:
174
+ return True, {
175
+ ast.Eq: "==", ast.NotEq: "!=", ast.Gt: "<", ast.GtE: "<=", ast.Lt: ">", ast.LtE: ">=",
176
+ ast.Is: "is", ast.IsNot: "is not",
177
+ ast.And: "and", ast.Or: "or"
178
+ }.get(type(op), "?")
179
+ return False, self._op_to_str(op)
180
+
181
+ def _normalize_symmetric(self, a, b, op):
182
+ terms = sorted([a.strip(), b.strip()])
183
+ return f"{terms[0]} {op} {terms[1]}"
184
+
185
+ def _is_logical_expr(self, expr):
186
+ return isinstance(expr, (ast.Compare, ast.BoolOp, ast.UnaryOp, ast.BinOp, ast.Call))
187
+
188
+
189
+ def is_python_assert_same(assert_stmt1: str, assert_stmt2: str, mask_str: bool = False) -> bool:
190
+ try:
191
+ norm_a = AssertNormalizerPython().normalize_assert(assert_stmt1, mask_str)
192
+ norm_b = AssertNormalizerPython().normalize_assert(assert_stmt2, mask_str)
193
+ except Exception:
194
+ return False
195
+ return norm_a == norm_b
196
+
197
+
198
+ if __name__ == '__main__':
199
+ # Same
200
+ assert is_python_assert_same("assert a == b", "assert b == a # Comment")
201
+ assert is_python_assert_same("assert True is x", "assert x is True")
202
+ assert is_python_assert_same("self.assertEquals(a, b)", "self.assertEquals(b, a)")
203
+ assert is_python_assert_same("self.assertTrue(x)", "assert x is True")
204
+ assert is_python_assert_same("self.assertFalse(x)", "assert x is False")
205
+ assert is_python_assert_same("assert a > 0", "assert 0 < a")
206
+
207
+ # Not Same
208
+ assert not is_python_assert_same("assert a > 0", "assert a == 0")
209
+ assert not is_python_assert_same("assert a == b", "assert a is b")
install.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from utils import read_jsonl
2
+ import os
3
+ import argparse
4
+ import subprocess
5
+
6
+
7
+ def download_py_dependencies(repo_path: str, install_cmd: str) -> bool:
8
+ result = subprocess.run(
9
+ install_cmd,
10
+ shell=True,
11
+ text=True,
12
+ executable='/bin/bash',
13
+ cwd=repo_path,
14
+ stdout=subprocess.PIPE,
15
+ stderr=subprocess.PIPE,
16
+ )
17
+ return result.returncode == 0
18
+
19
+
20
+ if __name__ == '__main__':
21
+ parser = argparse.ArgumentParser()
22
+ parser.add_argument('--repo_cache_dir', type=str, default='/tmp/pywork1/py500')
23
+ args = parser.parse_args()
24
+ py500 = read_jsonl('data/py500.jsonl')
25
+ repos = set()
26
+ for i, data in enumerate(py500):
27
+ print(f'=== {i} ===')
28
+ if repos.__contains__(data['repo_name']):
29
+ print(f'Skip {i}')
30
+ continue
31
+ repo_path = str(os.path.join(
32
+ args.repo_cache_dir,
33
+ data['repo_name']
34
+ ))
35
+ res = download_py_dependencies(
36
+ repo_path=repo_path,
37
+ install_cmd=data['install_cmd'],
38
+ )
39
+ print(res)
40
+ repos.add(data['repo_name'])
41
+ assert res
py500.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
run.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from utils import read_jsonl
2
+ import argparse
3
+ from typing import Tuple, Dict
4
+ import subprocess
5
+ import os
6
+ import xml.etree.ElementTree as ET
7
+
8
+
9
+ def run_py_repo_test(
10
+ repo_path: str,
11
+ test_target: str,
12
+ timeout: float = 10.0
13
+ ) -> Tuple[Dict, str]:
14
+ test_cmd = f'''\
15
+ source .venv/bin/activate
16
+ pytest {test_target} --junitxml=results.xml
17
+ '''
18
+ print(f'>>> {repo_path}')
19
+ print(test_cmd)
20
+ score = 0.0
21
+ total = 0
22
+ passed = 0
23
+ test_output = ''
24
+ test_output_file = os.path.join(repo_path, 'results.xml')
25
+ try:
26
+ if os.path.exists(test_output_file):
27
+ os.remove(test_output_file)
28
+ result = subprocess.run(
29
+ test_cmd,
30
+ shell=True,
31
+ executable='/bin/bash',
32
+ text=True,
33
+ cwd=os.path.abspath(repo_path),
34
+ stdout=subprocess.PIPE,
35
+ stderr=subprocess.PIPE,
36
+ timeout=timeout,
37
+ )
38
+ except Exception as e:
39
+ print(e)
40
+ pass
41
+ if os.path.exists(test_output_file):
42
+ try:
43
+ tree = ET.parse(test_output_file)
44
+ root = tree.getroot()
45
+ suite = root.find('testsuite')
46
+
47
+ if suite is None:
48
+ raise ValueError("Invalid XML: No <testsuite> element found")
49
+
50
+ total = int(suite.attrib.get('tests', 0))
51
+ failures = int(suite.attrib.get('failures', 0))
52
+ errors = int(suite.attrib.get('errors', 0))
53
+ skipped = int(suite.attrib.get('skipped', 0))
54
+ passed = total - failures - errors - skipped
55
+ score = passed / total if total > 0 else 0.0
56
+
57
+ error_messages = []
58
+ for case in suite.findall('testcase'):
59
+ failure = case.find('failure')
60
+ error = case.find('error')
61
+ if failure is not None:
62
+ error_messages.append(
63
+ f"Failure:\n" + \
64
+ '\n'.join(['...\n'] + failure.text.splitlines()[-4:])
65
+ )
66
+ elif error is not None:
67
+ error_messages.append(
68
+ f"Failure:\n" + \
69
+ '\n'.join(['...\n'] + error.text.splitlines()[-4:])
70
+ )
71
+ test_output = (
72
+ f"Total {total}, Passed: {passed}, Failures: {failures}, Errors: {errors}, Skipped: {skipped}\n"
73
+ f"Pass Rate: {score}"
74
+ )
75
+ if error_messages:
76
+ test_output += "\n\nError Message:\n" + "\n".join(error_messages)
77
+ except Exception:
78
+ pass
79
+ else:
80
+ try:
81
+ max_lines = 20
82
+ test_output = result.stdout.strip()
83
+ test_output = '\n'.join(test_output.splitlines()[- max_lines : ]).strip()
84
+ except Exception:
85
+ test_output = 'The "pytest" command run failed.'
86
+ return {
87
+ 'score': score,
88
+ 'passed': passed,
89
+ 'total': total,
90
+ }, test_output
91
+
92
+
93
+ if __name__ == '__main__':
94
+ parser = argparse.ArgumentParser()
95
+ parser.add_argument('--repo_cache_dir', type=str, default='/tmp/pywork1/py500')
96
+ parser.add_argument('--start_index', type=int, default=0)
97
+ parser.add_argument('--end_index', type=int, default=500)
98
+ args = parser.parse_args()
99
+
100
+ py500 = read_jsonl('data/py500.jsonl')
101
+
102
+ failed = []
103
+ for i in range(args.start_index, args.end_index):
104
+ data = py500[i]
105
+ print(f'=== {i} ===')
106
+ repo_path = str(os.path.join(args.repo_cache_dir, data['repo_name']))
107
+ res, output = run_py_repo_test(repo_path=repo_path, test_target=data['test_target'])
108
+ print(output)
109
+ try:
110
+ assert res['score'] == 1.0
111
+ except Exception as e:
112
+ print(e)
113
+ failed.append(i)
114
+
115
+ print('=== Failed ===')
116
+ print(failed)