Elffuss BraidHub

kikocis/auto-code-rover public

main · 10.8 KiBRawPermalink
1"""
2Directly taken from SWE-bench. Main content are from metrics/log_parsers.py
3"""
4
5import re
6from enum import Enum
7
8
9class TestStatus(Enum):
10 FAILED = "FAILED"
11 PASSED = "PASSED"
12 SKIPPED = "SKIPPED"
13 ERROR = "ERROR"
14
15
16def parse_log_pytest(log: str) -> dict:
17 """
18 Parser for test logs generated with PyTest framework
19
20 Args:
21 log (str): log content
22 Returns:
23 dict: test case to test status mapping
24 """
25 test_status_map = {}
26 for line in log.split("\n"):
27 if any([line.startswith(x.value) for x in TestStatus]):
28 # Additional parsing for FAILED status
29 if line.startswith(TestStatus.FAILED.value):
30 line = line.replace(" - ", " ")
31 test_case = line.split()
32 if len(test_case) <= 1:
33 continue
34 test_status_map[test_case[1]] = test_case[0]
35 return test_status_map
36
37
38def parse_log_django(log: str) -> dict:
39 """
40 Parser for test logs generated with Django tester framework
41
42 Args:
43 log (str): log content
44 Returns:
45 dict: test case to test status mapping
46 """
47 test_status_map = {}
48 lines = log.split("\n")
49 for line in lines:
50 line = line.strip()
51 if line.endswith(" ... ok"):
52 test = line.split(" ... ok")[0]
53 test_status_map[test] = TestStatus.PASSED.value
54 if " ... skipped" in line:
55 test = line.split(" ... skipped")[0]
56 test_status_map[test] = TestStatus.SKIPPED.value
57 if line.endswith(" ... FAIL"):
58 test = line.split(" ... FAIL")[0]
59 test_status_map[test] = TestStatus.FAILED.value
60 if line.startswith("FAIL:"):
61 test = line.split()[1].strip()
62 test_status_map[test] = TestStatus.FAILED.value
63 if line.endswith(" ... ERROR"):
64 test = line.split(" ... ERROR")[0]
65 test_status_map[test] = TestStatus.ERROR.value
66 if line.startswith("ERROR:"):
67 test = line.split()[1].strip()
68 test_status_map[test] = TestStatus.ERROR.value
69 return test_status_map
70
71
72def parse_log_pytest_v2(log):
73 """
74 Parser for test logs generated with PyTest framework (Later Version)
75
76 Args:
77 log (str): log content
78 Returns:
79 dict: test case to test status mapping
80 """
81 test_status_map = {}
82 escapes = "".join([chr(char) for char in range(1, 32)])
83 for line in log.split("\n"):
84 line = re.sub(r"\[(\d+)m", "", line)
85 translator = str.maketrans("", "", escapes)
86 line = line.translate(translator)
87 if any([line.startswith(x.value) for x in TestStatus]):
88 if line.startswith(TestStatus.FAILED.value):
89 line = line.replace(" - ", " ")
90 test_case = line.split()
91 test_status_map[test_case[1]] = test_case[0]
92 return test_status_map
93
94
95def parse_log_seaborn(log):
96 """
97 Parser for test logs generated with seaborn testing framework
98
99 Args:
100 log (str): log content
101 Returns:
102 dict: test case to test status mapping
103 """
104 test_status_map = {}
105 for line in log.split("\n"):
106 if line.startswith(TestStatus.FAILED.value):
107 test_case = line.split()[1]
108 test_status_map[test_case] = TestStatus.FAILED.value
109 elif f" {TestStatus.PASSED.value} " in line:
110 parts = line.split()
111 if parts[1] == TestStatus.PASSED.value:
112 test_case = parts[0]
113 test_status_map[test_case] = TestStatus.PASSED.value
114 return test_status_map
115
116
117def parse_log_sympy(log):
118 """
119 Parser for test logs generated with Sympy framework
120
121 Args:
122 log (str): log content
123 Returns:
124 dict: test case to test status mapping
125 """
126 test_status_map = {}
127 pattern = r"(_*) (.*)\.py:(.*) (_*)"
128 matches = re.findall(pattern, log)
129 for match in matches:
130 test_case = f"{match[1]}.py:{match[2]}"
131 test_status_map[test_case] = TestStatus.FAILED.value
132 for line in log.split("\n"):
133 line = line.strip()
134 if line.startswith("test_"):
135 if line.endswith(" E"):
136 test = line.split()[0]
137 test_status_map[test] = TestStatus.ERROR.value
138 if line.endswith(" F"):
139 test = line.split()[0]
140 test_status_map[test] = TestStatus.FAILED.value
141 if line.endswith(" ok"):
142 test = line.split()[0]
143 test_status_map[test] = TestStatus.PASSED.value
144 return test_status_map
145
146
147parse_log_astroid = parse_log_pytest
148parse_log_flask = parse_log_pytest
149parse_log_marshmallow = parse_log_pytest
150parse_log_matplotlib = parse_log_pytest
151parse_log_pydicom = parse_log_pytest
152parse_log_pvlib = parse_log_pytest
153parse_log_pylint = parse_log_pytest
154parse_log_pyvista = parse_log_pytest
155parse_log_requests = parse_log_pytest
156parse_log_sqlfluff = parse_log_pytest
157parse_log_xarray = parse_log_pytest
158
159parse_log_astropy = parse_log_pytest_v2
160parse_log_scikit = parse_log_pytest_v2
161parse_log_sphinx = parse_log_pytest_v2
162
163
164MAP_REPO_TO_PARSER = {
165 "astropy/astropy": parse_log_astropy,
166 "django/django": parse_log_django,
167 "marshmallow-code/marshmallow": parse_log_marshmallow,
168 "matplotlib/matplotlib": parse_log_matplotlib,
169 "mwaskom/seaborn": parse_log_seaborn,
170 "pallets/flask": parse_log_flask,
171 "psf/requests": parse_log_requests,
172 "pvlib/pvlib-python": parse_log_pvlib,
173 "pydata/xarray": parse_log_xarray,
174 "pydicom/pydicom": parse_log_pydicom,
175 "pylint-dev/astroid": parse_log_astroid,
176 "pylint-dev/pylint": parse_log_pylint,
177 "pytest-dev/pytest": parse_log_pytest,
178 "pyvista/pyvista": parse_log_pyvista,
179 "scikit-learn/scikit-learn": parse_log_scikit,
180 "sqlfluff/sqlfluff": parse_log_sqlfluff,
181 "sphinx-doc/sphinx": parse_log_sphinx,
182 "sympy/sympy": parse_log_sympy,
183}
184
185
186# TODO: this is duplicated from execution.py
187TESTS_ERROR = ">>>>> Tests Errored"
188TESTS_TIMEOUT = ">>>>> Tests Timed Out"
189
190
191# not from metrics/log_parsers.py
192def get_logs_eval(repo_name: str, log_file_path: str):
193 """
194 Parse a log file to get test status for each test case.
195 """
196 log_parser = MAP_REPO_TO_PARSER[repo_name]
197 with open(log_file_path) as f:
198 content = f.read()
199 if TESTS_ERROR in content or TESTS_TIMEOUT in content:
200 # something went wrong and there is not test status to parse
201 return {}, False
202
203 return log_parser(content), True
204
205
206def test_passed(case, sm):
207 return case in sm and sm[case] == TestStatus.PASSED.value
208
209
210def test_failed(case, sm):
211 return case not in sm or any(
212 [
213 sm[case] == status
214 for status in [TestStatus.FAILED.value, TestStatus.ERROR.value]
215 ]
216 )
217
218
219# Result Categories
220FAIL_TO_PASS = "FAIL_TO_PASS"
221FAIL_TO_FAIL = "FAIL_TO_FAIL"
222PASS_TO_PASS = "PASS_TO_PASS"
223PASS_TO_FAIL = "PASS_TO_FAIL"
224
225
226# not from metrics/log_parsers.py
227def get_eval_report(
228 eval_sm: dict, gold_results: dict, calculate_to_fail: bool = False
229) -> dict:
230 """
231 Create a report based on failure/pass change from gold results to eval results.
232
233 Args:
234 eval_sm (dict): evaluation status map
235 gold_results (dict): gold results
236 calculate_to_fail (bool): whether to calculate metrics for "x to fail" tests
237 Returns:
238 report (dict): report of metrics
239
240 Metric Definitions (Gold Result Pair + Eval Result):
241 - Fail-Pass (F2P) + P: Success (Resolution)
242 - Pass-Pass (P2P) + P: Success (Maintenance)
243 - Fail-Pass (F2P) + F: Failure
244 - Pass-Pass (P2P) + F: Failure
245
246 Miscellaneous Definitions
247 - Fail-Fail (F2F) + F: Failure Maintenance
248 - Pass-Fail (P2F) + F: Not considered
249 - Fail-Fail (F2F) + P: Success (Extra Credit)
250 - Pass-Fail (P2F) + P: Not considered
251 """
252 # Calculate resolution metrics
253 f2p_success = []
254 f2p_failure = []
255 for test_case in gold_results[FAIL_TO_PASS]:
256 if test_passed(test_case, eval_sm):
257 # Assume silent success for now (test case not in eval_sm)
258 f2p_success.append(test_case)
259 elif test_failed(test_case, eval_sm):
260 f2p_failure.append(test_case)
261
262 # Calculate maintenance metrics
263 p2p_success = []
264 p2p_failure = []
265 for test_case in gold_results[PASS_TO_PASS]:
266 if test_passed(test_case, eval_sm):
267 p2p_success.append(test_case)
268 elif test_failed(test_case, eval_sm):
269 p2p_failure.append(test_case)
270
271 results = {
272 FAIL_TO_PASS: {"success": f2p_success, "failure": f2p_failure},
273 PASS_TO_PASS: {"success": p2p_success, "failure": p2p_failure},
274 }
275
276 f2f_success = []
277 f2f_failure = []
278 p2f_success = []
279 p2f_failure = []
280 if calculate_to_fail:
281 # Calculate "extra credit" metrics
282 for test_case in gold_results[FAIL_TO_FAIL]:
283 if test_passed(test_case, eval_sm):
284 f2f_success.append(test_case)
285 elif test_failed(test_case, eval_sm):
286 f2f_failure.append(test_case)
287
288 # Calculate not considered metrics
289 for test_case in gold_results[PASS_TO_FAIL]:
290 if test_passed(test_case, eval_sm):
291 p2f_success.append(test_case)
292 elif test_failed(test_case, eval_sm):
293 p2f_failure.append(test_case)
294
295 results.update(
296 {
297 FAIL_TO_FAIL: {"success": f2f_success, "failure": f2f_failure},
298 PASS_TO_FAIL: {"success": p2f_success, "failure": p2f_failure},
299 }
300 )
301 return results
302
303
304class ResolvedStatus(Enum):
305 NO = "RESOLVED_NO"
306 PARTIAL = "RESOLVED_PARTIAL"
307 FULL = "RESOLVED_FULL"
308
309
310def compute_fail_to_pass(report: dict) -> float:
311 """
312 Compute fail-to-pass metric. Accepts single report as argument.
313 """
314 total = len(report[FAIL_TO_PASS]["success"]) + len(report[FAIL_TO_PASS]["failure"])
315 if total == 0:
316 return 1
317 return len(report[FAIL_TO_PASS]["success"]) / total
318
319
320def compute_pass_to_pass(report: dict) -> float:
321 """
322 Compute pass-to-pass metric. Accepts single report as argument.
323 """
324 total = len(report[PASS_TO_PASS]["success"]) + len(report[PASS_TO_PASS]["failure"])
325 if total == 0:
326 # TODO: Don't factor in p2p metrics
327 return 1
328 return len(report[PASS_TO_PASS]["success"]) / total
329
330
331def get_resolution_status(report: dict) -> ResolvedStatus:
332 """
333 Determine resolved status of an evaluation instance
334
335 Criteria:
336 - If fail-to-pass (Resolution) = 1 and pass-to-pass (Maintenance) = 1 -> FULL
337 - If (fail-to-pass (Resolution) < 1 and > 0) and pass-to-pass (Maintenance) = 1 -> PARTIAL
338 - Otherwise -> NO
339 """
340 f2p = compute_fail_to_pass(report)
341 p2p = compute_pass_to_pass(report)
342
343 if f2p == 1 and p2p == 1:
344 return ResolvedStatus.FULL
345 elif f2p < 1 and f2p > 0 and p2p == 1:
346 return ResolvedStatus.PARTIAL
347 else:
348 return ResolvedStatus.NO