Elffuss BraidHub

kikocis/auto-code-rover public

6ea11b99288f · 24.6 KiBRawPermalink
1"""
2Modified from pinpoint:
3https://github.com/Generalized-SBFL/pytest-pinpoint/blob/master/pytest_pinpoint.py
4
5For the purpose of SWE-bench, since each task instance has its own conda env, the test
6execution (with coverage run) should be done in the task instance's conda env.
7Afterwards, the analysis of coverage data should be done in this project's conda env.
8
9This file mainly analyzes the coverage data for SBFL analysis.
10"""
11
12import ast
13import math
14import os
15import re
16from collections.abc import Mapping
17from configparser import ConfigParser
18from functools import cache
19from os import PathLike
20from os.path import join as pjoin
21from pathlib import Path
22from pprint import pformat
23from subprocess import PIPE, STDOUT, TimeoutExpired
24from tempfile import mkstemp
25
26from coverage.sqldata import CoverageData
27
28import app.utils as apputils
29from app import globals, log
30from app.data_structures import MethodId
31from app.task import SweTask, Task
32
33
34class NoCoverageData(RuntimeError):
35 def __init__(self, testing_log_file: str):
36 self.testing_log_file = testing_log_file
37
38
39def canonicalize_testname_sympy_bin_test(testname: str) -> tuple[str, str]:
40 """
41 The sympy version, who excutes tests with bin/test
42
43 All tests in sympy are just function names, like `test_is_superset`
44 """
45 return "", testname
46
47
48def canonicalize_testname_django_runner(testname: str) -> tuple[str, str]:
49 """
50 Same as canonicalize_testname_pytest, but for django test runner.
51 Need to deal with them separately because the test name formats are diff.
52 """
53 identifier_pattern = r"[a-zA-Z_][a-zA-Z0-9_]*"
54 pattern = r"^{0} \({0}(.{0})*\)".format(identifier_pattern)
55 if not re.search(pattern, testname):
56 # special case like: A reference in a local scope can't be serialized.
57 return "", ""
58
59 func, path = testname.split(" (")
60 path = path[:-1] # remove the trailing )
61 full_name = path + "." + func
62 # path can contain both module or class name
63 # module are snake case, class are camel case
64 # we only want module name to form the file name
65 path_parts = path.split(".")
66 modules = []
67 for part in path_parts:
68 if part.islower():
69 modules.append(part)
70 file_name = "/".join(modules) + ".py"
71 return file_name, full_name
72
73
74def canonicalize_testname_pytest(testname: str) -> tuple[str, str]:
75 """
76 Unify the test names in tasks_map.json and pytest-cov.
77
78 pytest-cov format is FILE::METHOD[PARAMETRIZATION]|PHASE, where PHASE is "setup", "run", or "teardown"
79 see https://pytest-cov.readthedocs.io/en/latest/contexts.html#
80 example:
81 astropy/coordinates/tests/test_angles.py::test_latitude_limits[value2-expected_value2-None-float32-1]|run
82
83 tasks_map.json format does not have the "|PHASE" suffix
84
85 Returns:
86 - (file_name, full name of the test)
87 """
88 file_name = testname.split("::")[0]
89 return file_name, testname
90
91
92def canonicalize_testname(task_id: str, testname: str) -> tuple[str, str]:
93 if "django" in task_id:
94 return canonicalize_testname_django_runner(testname)
95 elif "sympy" in task_id:
96 return canonicalize_testname_sympy_bin_test(testname)
97 else:
98 return canonicalize_testname_pytest(testname)
99
100
101class FileExecStats:
102 def __init__(self, filename: str):
103 self.filename = filename
104 # line number -> (pass_count, fail_count)
105 self.line_stats: dict[int, tuple[int, int]] = dict()
106
107 def incre_pass_count(self, line_no: int):
108 if line_no in self.line_stats:
109 old_pass, old_fail = self.line_stats[line_no]
110 self.line_stats[line_no] = (old_pass + 1, old_fail)
111 else:
112 self.line_stats[line_no] = (1, 0)
113
114 def incre_fail_count(self, line_no: int):
115 if line_no in self.line_stats:
116 old_pass, old_fail = self.line_stats[line_no]
117 self.line_stats[line_no] = (old_pass, old_fail + 1)
118 else:
119 self.line_stats[line_no] = (0, 1)
120
121 def __str__(self):
122 res = self.filename + "\n"
123 res += pformat(self.line_stats)
124 return res
125
126 def __repr__(self) -> str:
127 return self.__str__()
128
129
130class ExecStats:
131 def __init__(self):
132 # file name -> FileExecStats
133 self.file_stats: dict[str, FileExecStats] = dict()
134
135 def add_file(self, file_exec_stats: FileExecStats):
136 self.file_stats[file_exec_stats.filename] = file_exec_stats
137
138 def __str__(self) -> str:
139 return pformat(self.file_stats)
140
141 """
142 Formula from:
143 https://homes.cs.washington.edu/~rjust/publ/fault_localization_effectiveness_icse_2017.pdf
144 """
145
146 @staticmethod
147 def ochiai(failed, passed, total_fail, total_pass):
148 top = failed
149 bottom = math.sqrt(total_fail * (failed + passed))
150 if bottom == 0:
151 return 0
152 return top / bottom
153
154 @staticmethod
155 def tarantula(failed, passed, total_fail, total_pass):
156 top = failed / total_fail
157 bottom = failed / total_fail + passed / total_pass
158 if bottom == 0:
159 return 0
160 return top / bottom
161
162 @staticmethod
163 def op2(failed, passed, total_fail, total_pass):
164 top = passed
165 bottom = total_pass + 1
166 if bottom == 0:
167 return failed
168 return failed - top / bottom
169
170 @staticmethod
171 def barinel(failed, passed, total_fail, total_pass):
172 top = passed
173 bottom = passed + failed
174 if bottom == 0:
175 return 0
176 return 1 - top / bottom
177
178 @staticmethod
179 def dstar(failed, passed, total_fail, total_pass):
180 top = failed**2
181 bottom = passed + (total_fail - failed)
182 if bottom == 0:
183 return 0
184 return top / bottom
185
186 def rank_lines(
187 self, fl_algo, total_fail, total_pass
188 ) -> list[tuple[str, int, float]]:
189 lines_with_scores = [] # filename, line_no, score
190 for file, file_exec_stats in self.file_stats.items():
191 for line_no, (passed, failed) in file_exec_stats.line_stats.items():
192 # invoke the fl algorithm to compute score
193 score = fl_algo(failed, passed, total_fail, total_pass)
194 lines_with_scores.append((file, line_no, score))
195 # sort by score (descending), then by file name, then by line number
196 lines_with_scores.sort(key=lambda x: (-x[2], x[0], x[1]))
197 return lines_with_scores
198
199
200def helper_remove_dup_and_empty(lst: list[str]) -> list[str]:
201 """
202 Remove duplicates and empty strings from the list.
203 """
204 return list(filter(lambda x: x != "", list(set(lst))))
205
206
207def helper_two_tests_match(test_one: str, test_two: str) -> bool:
208 """
209 Check if two tests are referring to the same test function.
210 For example:
211 - matplotlib.tests.test_figure.test_savefig_pixel_ratio
212 - lib.matplotlib.tests.test_figure.test_savefig_pixel_ratio
213 Should be the same.
214 """
215 # make sure suffix are the same, since the actual function name
216 # appears the last
217 return test_one.endswith(test_two) or test_two.endswith(test_one)
218
219
220def helper_test_match_any(test: str, candidates: list[str]) -> bool:
221 """
222 Check if the test matches any of the candidates.
223 """
224 return any([helper_two_tests_match(test, c) for c in candidates])
225
226
227"""
228Main entry to the SBFL analysis.
229"""
230
231
232def run(task: Task) -> tuple[list[str], list[tuple[str, int, float]], str]:
233 """
234 Run SBFL analysis on the given coverage data file.
235 At the same time, collect the test file names.
236
237 Args:
238 - pass_tests: list of test names that passed
239 - fail_tests: list of test names that failed
240 - cov_file: path to the coverage data file, generated by python coverage.py
241 - task_id: task id to identify which project we are on.
242
243 Returns:
244 - list of test file names
245 - list of ranked lines (file, line_no, score)
246 - path of testing log
247 """
248 if isinstance(task, SweTask):
249 return PythonSbfl.run(task)
250
251 raise NotImplementedError(f"SBFL does not support {type(task).__name__}")
252
253
254class PythonSbfl:
255 @classmethod
256 def run(cls, task: SweTask) -> tuple[list[str], list[tuple[str, int, float]], str]:
257 cov_file, log_file = cls._run_python_developer_test_suite(task)
258
259 pass_tests_names = []
260 fail_tests_names = []
261 test_file_names = []
262 for test in task.testcases_passing:
263 file_name, test_name = canonicalize_testname(task.task_id, test)
264 pass_tests_names.append(test_name)
265 test_file_names.append(file_name)
266 for test in task.testcases_failing:
267 file_name, test_name = canonicalize_testname(task.task_id, test)
268 fail_tests_names.append(test_name)
269 test_file_names.append(file_name)
270
271 # compute total before removing wierd test names
272 total_fail = len(fail_tests_names)
273 total_pass = len(pass_tests_names)
274
275 pass_tests_names = helper_remove_dup_and_empty(pass_tests_names)
276 fail_tests_names = helper_remove_dup_and_empty(fail_tests_names)
277 test_file_names = helper_remove_dup_and_empty(test_file_names)
278
279 if not os.path.isfile(cov_file):
280 raise NoCoverageData(log_file)
281
282 covdb = CoverageData(basename=cov_file)
283 covdb.read()
284
285 exec_stats = ExecStats()
286
287 # Collect measured_files
288 measured_files = covdb.measured_files()
289 for measured_f in measured_files:
290 file_exec_stats = FileExecStats(measured_f)
291 current_context = covdb.contexts_by_lineno(measured_f)
292 # not consider files which are not tested
293 if current_context is [] or current_context is None:
294 measured_files.remove(measured_f)
295 continue
296 # store pass/fail stats associated with context and line number
297 for line_no, context_names in current_context.items():
298 for test_name in context_names:
299 if not test_name: # ''
300 continue
301
302 # remove pytest-cov phase name
303 # see https://pytest-cov.readthedocs.io/en/latest/contexts.html#
304 test_name = re.sub(r"\|((setup)|(run)|(teardown))$", "", test_name)
305
306 if helper_test_match_any(test_name, pass_tests_names):
307 file_exec_stats.incre_pass_count(line_no)
308 elif helper_test_match_any(test_name, fail_tests_names):
309 file_exec_stats.incre_fail_count(line_no)
310 exec_stats.add_file(file_exec_stats)
311
312 # NOTE: swap algorithm here
313 ranked_lines = exec_stats.rank_lines(ExecStats.ochiai, total_fail, total_pass)
314 return test_file_names, ranked_lines, log_file
315
316 @classmethod
317 def _run_python_developer_test_suite(cls, task: SweTask) -> tuple[str, str]:
318 """
319 Run the relevant parts of developer test suite.
320 Record coverage information for each test while running them.
321
322 Returns:
323 - The produced coverage file for the test suite.
324 Empty string if no coverage file is produced.
325 - Log file.
326 """
327 if "django" in task.task_id:
328 return cls._run_developer_test_suite_django(task)
329 else:
330 return cls._run_developer_test_suite_others(task)
331
332 @classmethod
333 def _run_developer_test_suite_django(cls, task: SweTask) -> tuple[str, str]:
334 """
335 Since django does not use pytest as the testing framework, we use another procedure.
336
337 Returns:
338 - The produced coverage file for the test suite. Empty string if the file is not produced.
339 """
340
341 tests_dir = pjoin(task.project_path, "tests")
342 assert os.path.isdir(tests_dir)
343
344 execution_dir = tests_dir
345 with apputils.cd(execution_dir):
346 # (1) since we want to use coverage.py with dynamic context, create config first
347 cov_config = pjoin(execution_dir, ".coveragerc")
348 cls._specify_dynamic_context(cov_config)
349
350 # (2) actually run the tests to produce coverage output
351 orig_cmd_parts = task.test_cmd.split(" ")
352 assert (
353 orig_cmd_parts[0] == "./tests/runtests.py"
354 ), f"Test command does not start with ./tests/runtests.py: {task.test_cmd}"
355 test_cmd = (
356 "python -m coverage run "
357 + os.path.basename(orig_cmd_parts[0])
358 + " --parallel 1 "
359 + " ".join(orig_cmd_parts[1:])
360 )
361
362 _, log_file = mkstemp(suffix=".log", prefix="run_developer_tests")
363
364 try:
365 cp = apputils.run_string_cmd_in_conda(
366 test_cmd,
367 task.env_name,
368 stdout=PIPE,
369 stderr=STDOUT,
370 text=True,
371 timeout=globals.test_exec_timeout,
372 )
373 Path(log_file).write_text(cp.stdout)
374 except TimeoutExpired:
375 log.log_and_print(
376 "Timeout expired while running the test suite.",
377 )
378 return "", log_file
379
380 # (3) check whether the coverage file is there
381 cov_file = pjoin(execution_dir, ".coverage")
382 if not os.path.exists(cov_file):
383 log.log_and_print(
384 "Coverage file is not produced after running the test suite.",
385 )
386 return "", log_file
387 return cov_file, log_file
388
389 @classmethod
390 def _run_developer_test_suite_others(cls, task: SweTask) -> tuple[str, str]:
391 """
392 Run the relevant parts of developer test suite.
393 Record coverage information for each test while running them.
394
395 Returns:
396 - The produced coverage file for the test suite. Empty string if no coverage file is produced.
397 - Log file.
398 """
399
400 with apputils.cd(task.project_path):
401 # (1) run the tests to produce coverage output
402 if task.test_cmd.startswith("pytest"):
403 # Use pytest-cov to properly get parametrized test names
404 args = task.test_cmd.removeprefix("pytest")
405 test_cmd = f"python -m pytest --cov --cov-context=test {args}"
406 elif "bin/test" in task.test_cmd:
407 assert task.task_id.startswith("sympy__")
408
409 # Sympy tests are compatible with PyTest. Only issue is that more tests
410 # can berun by PyTest than if Sympy testing is used. However, we match
411 # context names with PASS_TO_PASS and FAIL_TO_PASS later, so it's fine.
412
413 test_files = [x for x in task.test_cmd.split() if x.endswith(".py")]
414 assert (
415 test_files
416 ), f"Failed to find test files in command: {task.test_cmd}"
417
418 cov_config = pjoin(task.project_path, ".coveragerc")
419
420 cls._omit_coverage_in_file(cov_config, test_files)
421
422 test_cmd = (
423 "python -m pytest --cov --cov-context=test --no-header"
424 f" -rA --tb=no -p no:cacheprovider {' '.join(test_files)}"
425 )
426 elif task.test_cmd.startswith("tox "):
427 tox_ini = pjoin(task.project_path, "tox.ini")
428 assert os.path.exists(
429 tox_ini
430 ), f"tox.ini not found in {task.project_path}"
431
432 cls._add_pytest_cov_to_tox(tox_ini)
433
434 test_cmd = f"python -m {task.test_cmd}"
435 else:
436 cov_config = pjoin(task.project_path, ".coveragerc")
437 cls._specify_dynamic_context(cov_config)
438 test_cmd = f"python -m coverage run {task.test_cmd}"
439
440 _, log_file = mkstemp(suffix=".log", prefix="run_developer_tests")
441 try:
442 cp = apputils.run_string_cmd_in_conda(
443 test_cmd,
444 task.env_name,
445 stdout=PIPE,
446 stderr=STDOUT,
447 text=True,
448 timeout=globals.test_exec_timeout,
449 )
450 Path(log_file).write_text(cp.stdout)
451 # Path(self.output_dir, "run_developer_tests.log").write_text(cp.stdout)
452 except TimeoutExpired:
453 log.log_and_print(
454 "Timeout expired while running the test suite.",
455 )
456 return "", log_file
457
458 # (2) check whether the coverage file is there
459 cov_file = pjoin(task.project_path, ".coverage")
460 if not os.path.exists(cov_file):
461 # sometimes cov_file can have extensions such as:
462 # .coverage.TSS.852665.XmCvBpdx
463 # we need to find the correct file
464 all_files = os.listdir(task.project_path)
465 for f in all_files:
466 if f.startswith(".coverage.TSS"):
467 cov_file = pjoin(task.project_path, f)
468 break
469 # now check again
470 if not os.path.exists(cov_file):
471 log.log_and_print(
472 "Coverage file is not produced after running the test suite.",
473 )
474 return "", log_file
475 return cov_file, log_file
476
477 @classmethod
478 def _specify_dynamic_context(cls, coveragerc: str | PathLike) -> None:
479 # check whether there is already a .coveragerc file
480 if not os.path.exists(coveragerc):
481 with open(coveragerc, "w") as f:
482 f.write("[run]\ndynamic_context = test_function")
483 else:
484 # add the dynamic context setting to it
485 with open(coveragerc) as f:
486 lines = f.readlines()
487 updated_lines = []
488 added_context_line = False
489 for line in lines:
490 updated_lines.append(line)
491 if line.startswith("[run]"):
492 added_context_line = True
493 updated_lines.append("dynamic_context = test_function\n")
494 # if there is no [run] section in old file, our line
495 # has not been added yet
496 if not added_context_line:
497 updated_lines.append("[run]\n")
498 updated_lines.append("dynamic_context = test_function\n")
499 with open(coveragerc, "w") as f:
500 f.writelines(updated_lines)
501
502 @classmethod
503 def _omit_coverage_in_file(
504 cls, coveragerc: str | PathLike, omitted: list[str]
505 ) -> None:
506 value = "".join(f"\n{file}" for file in omitted)
507 value = "\n# added by auto-code-rover" + value
508
509 config = ConfigParser()
510
511 if os.path.exists(coveragerc):
512 config.read(coveragerc)
513
514 if not config.has_section("run"):
515 config.add_section("run")
516
517 config["run"]["omit"] = value + config["run"].get("omit", "")
518
519 with open(coveragerc, "w") as f:
520 config.write(f)
521
522 @classmethod
523 def _add_pytest_cov_to_tox(cls, tox_ini: str | PathLike):
524 assert os.path.exists(tox_ini)
525
526 config = ConfigParser()
527 config.read(tox_ini)
528
529 assert config.has_section("testenv")
530 config["testenv"]["deps"] = (
531 config["testenv"].get("deps", "") + "\npytest\npytest-cov"
532 )
533
534 assert config.has_option("testenv", "commands")
535 config["testenv"]["commands"] = config["testenv"]["commands"].replace(
536 "pytest", "pytest --cov --cov-context=test"
537 )
538
539 with open(tox_ini, "w") as f:
540 config.write(f)
541
542
543def collate_results(
544 ranked_lines: list[tuple[str, int, float]], test_file_names: list[str]
545) -> list[tuple[str, int, int, float]]:
546 """
547 From the ranked lines, perform filtering (for lines that are likely to be in the test files),
548 as well as merging (since multiple ranked lines can be adjacent to each other).
549
550 Returns:
551 - list of (file, start_line_no, end_line_no, score), sorted
552 """
553 # (1) remove lines with non positive score
554 positive_lines = [line for line in ranked_lines if line[2] > 0]
555 # (2) remove lines that are in test files
556 survived_lines = []
557 for file, line_no, score in positive_lines:
558 # file is full path, and test_files_names are relative path
559 file_is_test = any([file.endswith(test_file) for test_file in test_file_names])
560 if not file_is_test:
561 survived_lines.append((file, line_no, score))
562
563 # (3) convert survived lines into dict, key is filename, value is list of (line_no, score)
564 file_line_score: Mapping[str, list[tuple[int, float]]] = dict()
565 for file, line_no, score in survived_lines:
566 if file not in file_line_score:
567 file_line_score[file] = []
568 file_line_score[file].append((line_no, score))
569 # sort the dict value list by line_no
570 for file, line_score in file_line_score.items():
571 new_line_score = sorted(line_score, key=lambda x: x[0])
572 file_line_score[file] = new_line_score
573
574 # (4) merge adjacent lines, the new dict value list is a list of (start_line_no, end_line_no, score)
575 # note that end_line_no is inclusive
576 merged_file_line_score: Mapping[str, list[tuple[int, int, float]]] = dict()
577 for file, line_score in file_line_score.items():
578 merged_line_score = []
579 # indexes into the line_score
580 start_index = 0
581 end_index = 0
582 while end_index < len(line_score):
583 while (
584 end_index < len(line_score)
585 and line_score[end_index][0]
586 == line_score[start_index][0] + end_index - start_index
587 ):
588 end_index += 1
589 # now we know line_scores between start_index and end_index - 1 are consecutive
590 # find the highest score in this consecutive range
591 scores = [score for _, score in line_score[start_index:end_index]]
592 highest_score = max(scores)
593 merged_line_score.append(
594 (
595 line_score[start_index][0],
596 line_score[end_index - 1][0],
597 highest_score,
598 )
599 )
600 start_index = end_index
601 merged_file_line_score[file] = merged_line_score
602
603 # convert dict back to list of (file, start_line_no, end_line_no, score), and sort by score
604 res = []
605 for file, line_score in merged_file_line_score.items():
606 for start_line, end_line, score in line_score:
607 res.append((file, start_line, end_line, score))
608 # sort by score (descending), then by file name, then by start line number
609 res = sorted(res, key=lambda x: (-x[3], x[0], x[1]))
610 return res
611
612
613@cache
614def method_ranges_in_file(file: str) -> dict[MethodId, tuple[int, int]]:
615 """
616 Find the ranges of all methods in a python file.
617
618 Result key is method name, value is (start_line, end_line), inclusive.
619 """
620
621 class MethodRangeFinder(ast.NodeVisitor):
622 def __init__(self):
623 self.range_map: dict[MethodId, tuple[int, int]] = {}
624 self.class_name = ""
625
626 def calc_method_id(self, method_name: str) -> MethodId:
627 return MethodId(self.class_name, method_name)
628
629 def visit_ClassDef(self, node: ast.ClassDef) -> None:
630 self.class_name = node.name
631 super().generic_visit(node)
632 self.class_name = ""
633
634 def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
635 method_id = self.calc_method_id(node.name)
636 assert node.end_lineno
637 self.range_map[method_id] = (node.lineno, node.end_lineno)
638
639 def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
640 method_id = self.calc_method_id(node.name)
641 assert node.end_lineno
642 self.range_map[method_id] = (node.lineno, node.end_lineno)
643
644 finder = MethodRangeFinder()
645
646 source = Path(file).read_text()
647
648 try:
649 tree = ast.parse(source, file)
650 except SyntaxError:
651 return {}
652
653 finder.visit(tree)
654
655 return finder.range_map
656
657
658def map_collated_results_to_methods(ranked_ranges) -> list[tuple[str, str, str, float]]:
659 """
660 Map suspicious lines to methods.
661
662 Return list of (filename, methodname, suspicousness).
663 A method is added at most once, when it is first seen in the line list.
664 """
665 seen = set()
666
667 result = []
668 for x in ranked_ranges:
669 filename, start, end, suspiciousness = x
670 range_map = method_ranges_in_file(filename)
671
672 for method_id, r in range_map.items():
673 if r[0] > end or r[1] < start:
674 continue
675
676 key = (filename, method_id)
677 if key in seen:
678 continue
679
680 result.append(
681 (filename, method_id.class_name, method_id.method_name, suspiciousness)
682 )
683 seen.add(key)
684 return result