| 1 | """ |
| 2 | Modified from pinpoint: |
| 3 | https://github.com/Generalized-SBFL/pytest-pinpoint/blob/master/pytest_pinpoint.py |
| 4 | |
| 5 | For the purpose of SWE-bench, since each task instance has its own conda env, the test |
| 6 | execution (with coverage run) should be done in the task instance's conda env. |
| 7 | Afterwards, the analysis of coverage data should be done in this project's conda env. |
| 8 | |
| 9 | This file mainly analyzes the coverage data for SBFL analysis. |
| 10 | """ |
| 11 | |
| 12 | import ast |
| 13 | import math |
| 14 | import os |
| 15 | import re |
| 16 | from collections.abc import Mapping |
| 17 | from configparser import ConfigParser |
| 18 | from functools import cache |
| 19 | from os import PathLike |
| 20 | from os.path import join as pjoin |
| 21 | from pathlib import Path |
| 22 | from pprint import pformat |
| 23 | from subprocess import PIPE, STDOUT, TimeoutExpired |
| 24 | from tempfile import mkstemp |
| 25 | |
| 26 | from coverage.sqldata import CoverageData |
| 27 | |
| 28 | import app.utils as apputils |
| 29 | from app import globals, log |
| 30 | from app.data_structures import MethodId |
| 31 | from app.task import SweTask, Task |
| 32 | |
| 33 | |
| 34 | class NoCoverageData(RuntimeError): |
| 35 | def __init__(self, testing_log_file: str): |
| 36 | self.testing_log_file = testing_log_file |
| 37 | |
| 38 | |
| 39 | def 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 | |
| 48 | def 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 | |
| 74 | def 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 | |
| 92 | def 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 | |
| 101 | class 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 | |
| 130 | class 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 | |
| 200 | def 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 | |
| 207 | def 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 | |
| 220 | def 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 | """ |
| 228 | Main entry to the SBFL analysis. |
| 229 | """ |
| 230 | |
| 231 | |
| 232 | def 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 | |
| 254 | class 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("Timeout expired while running the test suite.") |
| 376 | return "", log_file |
| 377 | |
| 378 | # (3) check whether the coverage file is there |
| 379 | cov_file = pjoin(execution_dir, ".coverage") |
| 380 | if not os.path.exists(cov_file): |
| 381 | log.log_and_print( |
| 382 | "Coverage file is not produced after running the test suite." |
| 383 | ) |
| 384 | return "", log_file |
| 385 | return cov_file, log_file |
| 386 | |
| 387 | @classmethod |
| 388 | def _run_developer_test_suite_others(cls, task: SweTask) -> tuple[str, str]: |
| 389 | """ |
| 390 | Run the relevant parts of developer test suite. |
| 391 | Record coverage information for each test while running them. |
| 392 | |
| 393 | Returns: |
| 394 | - The produced coverage file for the test suite. Empty string if no coverage file is produced. |
| 395 | - Log file. |
| 396 | """ |
| 397 | |
| 398 | with apputils.cd(task.project_path): |
| 399 | # (1) run the tests to produce coverage output |
| 400 | if task.test_cmd.startswith("pytest"): |
| 401 | # Use pytest-cov to properly get parametrized test names |
| 402 | args = task.test_cmd.removeprefix("pytest") |
| 403 | test_cmd = f"python -m pytest --cov --cov-context=test {args}" |
| 404 | elif "bin/test" in task.test_cmd: |
| 405 | assert task.task_id.startswith("sympy__") |
| 406 | |
| 407 | # Sympy tests are compatible with PyTest. Only issue is that more tests |
| 408 | # can berun by PyTest than if Sympy testing is used. However, we match |
| 409 | # context names with PASS_TO_PASS and FAIL_TO_PASS later, so it's fine. |
| 410 | |
| 411 | test_files = [x for x in task.test_cmd.split() if x.endswith(".py")] |
| 412 | assert ( |
| 413 | test_files |
| 414 | ), f"Failed to find test files in command: {task.test_cmd}" |
| 415 | |
| 416 | cov_config = pjoin(task.project_path, ".coveragerc") |
| 417 | |
| 418 | cls._omit_coverage_in_file(cov_config, test_files) |
| 419 | |
| 420 | test_cmd = ( |
| 421 | "python -m pytest --cov --cov-context=test --no-header" |
| 422 | f" -rA --tb=no -p no:cacheprovider {' '.join(test_files)}" |
| 423 | ) |
| 424 | elif task.test_cmd.startswith("tox "): |
| 425 | tox_ini = pjoin(task.project_path, "tox.ini") |
| 426 | assert os.path.exists( |
| 427 | tox_ini |
| 428 | ), f"tox.ini not found in {task.project_path}" |
| 429 | |
| 430 | cls._add_pytest_cov_to_tox(tox_ini) |
| 431 | |
| 432 | test_cmd = f"python -m {task.test_cmd}" |
| 433 | else: |
| 434 | cov_config = pjoin(task.project_path, ".coveragerc") |
| 435 | cls._specify_dynamic_context(cov_config) |
| 436 | test_cmd = f"python -m coverage run {task.test_cmd}" |
| 437 | |
| 438 | _, log_file = mkstemp(suffix=".log", prefix="run_developer_tests") |
| 439 | try: |
| 440 | cp = apputils.run_string_cmd_in_conda( |
| 441 | test_cmd, |
| 442 | task.env_name, |
| 443 | stdout=PIPE, |
| 444 | stderr=STDOUT, |
| 445 | text=True, |
| 446 | timeout=globals.test_exec_timeout, |
| 447 | ) |
| 448 | Path(log_file).write_text(cp.stdout) |
| 449 | # Path(self.output_dir, "run_developer_tests.log").write_text(cp.stdout) |
| 450 | except TimeoutExpired: |
| 451 | log.log_and_print("Timeout expired while running the test suite.") |
| 452 | return "", log_file |
| 453 | |
| 454 | # (2) check whether the coverage file is there |
| 455 | cov_file = pjoin(task.project_path, ".coverage") |
| 456 | if not os.path.exists(cov_file): |
| 457 | # sometimes cov_file can have extensions such as: |
| 458 | # .coverage.TSS.852665.XmCvBpdx |
| 459 | # we need to find the correct file |
| 460 | all_files = os.listdir(task.project_path) |
| 461 | for f in all_files: |
| 462 | if f.startswith(".coverage.TSS"): |
| 463 | cov_file = pjoin(task.project_path, f) |
| 464 | break |
| 465 | # now check again |
| 466 | if not os.path.exists(cov_file): |
| 467 | log.log_and_print( |
| 468 | "Coverage file is not produced after running the test suite." |
| 469 | ) |
| 470 | return "", log_file |
| 471 | return cov_file, log_file |
| 472 | |
| 473 | @classmethod |
| 474 | def _specify_dynamic_context(cls, coveragerc: str | PathLike) -> None: |
| 475 | # check whether there is already a .coveragerc file |
| 476 | if not os.path.exists(coveragerc): |
| 477 | with open(coveragerc, "w") as f: |
| 478 | f.write("[run]\ndynamic_context = test_function") |
| 479 | else: |
| 480 | # add the dynamic context setting to it |
| 481 | with open(coveragerc) as f: |
| 482 | lines = f.readlines() |
| 483 | updated_lines = [] |
| 484 | added_context_line = False |
| 485 | for line in lines: |
| 486 | updated_lines.append(line) |
| 487 | if line.startswith("[run]"): |
| 488 | added_context_line = True |
| 489 | updated_lines.append("dynamic_context = test_function\n") |
| 490 | # if there is no [run] section in old file, our line |
| 491 | # has not been added yet |
| 492 | if not added_context_line: |
| 493 | updated_lines.append("[run]\n") |
| 494 | updated_lines.append("dynamic_context = test_function\n") |
| 495 | with open(coveragerc, "w") as f: |
| 496 | f.writelines(updated_lines) |
| 497 | |
| 498 | @classmethod |
| 499 | def _omit_coverage_in_file( |
| 500 | cls, coveragerc: str | PathLike, omitted: list[str] |
| 501 | ) -> None: |
| 502 | value = "".join(f"\n{file}" for file in omitted) |
| 503 | value = "\n# added by auto-code-rover" + value |
| 504 | |
| 505 | config = ConfigParser() |
| 506 | |
| 507 | if os.path.exists(coveragerc): |
| 508 | config.read(coveragerc) |
| 509 | |
| 510 | if not config.has_section("run"): |
| 511 | config.add_section("run") |
| 512 | |
| 513 | config["run"]["omit"] = value + config["run"].get("omit", "") |
| 514 | |
| 515 | with open(coveragerc, "w") as f: |
| 516 | config.write(f) |
| 517 | |
| 518 | @classmethod |
| 519 | def _add_pytest_cov_to_tox(cls, tox_ini: str | PathLike): |
| 520 | assert os.path.exists(tox_ini) |
| 521 | |
| 522 | config = ConfigParser() |
| 523 | config.read(tox_ini) |
| 524 | |
| 525 | assert config.has_section("testenv") |
| 526 | config["testenv"]["deps"] = ( |
| 527 | config["testenv"].get("deps", "") + "\npytest\npytest-cov" |
| 528 | ) |
| 529 | |
| 530 | assert config.has_option("testenv", "commands") |
| 531 | config["testenv"]["commands"] = config["testenv"]["commands"].replace( |
| 532 | "pytest", "pytest --cov --cov-context=test" |
| 533 | ) |
| 534 | |
| 535 | with open(tox_ini, "w") as f: |
| 536 | config.write(f) |
| 537 | |
| 538 | |
| 539 | def collate_results( |
| 540 | ranked_lines: list[tuple[str, int, float]], test_file_names: list[str] |
| 541 | ) -> list[tuple[str, int, int, float]]: |
| 542 | """ |
| 543 | From the ranked lines, perform filtering (for lines that are likely to be in the test files), |
| 544 | as well as merging (since multiple ranked lines can be adjacent to each other). |
| 545 | |
| 546 | Returns: |
| 547 | - list of (file, start_line_no, end_line_no, score), sorted |
| 548 | """ |
| 549 | # (1) remove lines with non positive score |
| 550 | positive_lines = [line for line in ranked_lines if line[2] > 0] |
| 551 | # (2) remove lines that are in test files |
| 552 | survived_lines = [] |
| 553 | for file, line_no, score in positive_lines: |
| 554 | # file is full path, and test_files_names are relative path |
| 555 | file_is_test = any([file.endswith(test_file) for test_file in test_file_names]) |
| 556 | if not file_is_test: |
| 557 | survived_lines.append((file, line_no, score)) |
| 558 | |
| 559 | # (3) convert survived lines into dict, key is filename, value is list of (line_no, score) |
| 560 | file_line_score: Mapping[str, list[tuple[int, float]]] = dict() |
| 561 | for file, line_no, score in survived_lines: |
| 562 | if file not in file_line_score: |
| 563 | file_line_score[file] = [] |
| 564 | file_line_score[file].append((line_no, score)) |
| 565 | # sort the dict value list by line_no |
| 566 | for file, line_score in file_line_score.items(): |
| 567 | new_line_score = sorted(line_score, key=lambda x: x[0]) |
| 568 | file_line_score[file] = new_line_score |
| 569 | |
| 570 | # (4) merge adjacent lines, the new dict value list is a list of (start_line_no, end_line_no, score) |
| 571 | # note that end_line_no is inclusive |
| 572 | merged_file_line_score: Mapping[str, list[tuple[int, int, float]]] = dict() |
| 573 | for file, line_score in file_line_score.items(): |
| 574 | merged_line_score = [] |
| 575 | # indexes into the line_score |
| 576 | start_index = 0 |
| 577 | end_index = 0 |
| 578 | while end_index < len(line_score): |
| 579 | while ( |
| 580 | end_index < len(line_score) |
| 581 | and line_score[end_index][0] |
| 582 | == line_score[start_index][0] + end_index - start_index |
| 583 | ): |
| 584 | end_index += 1 |
| 585 | # now we know line_scores between start_index and end_index - 1 are consecutive |
| 586 | # find the highest score in this consecutive range |
| 587 | scores = [score for _, score in line_score[start_index:end_index]] |
| 588 | highest_score = max(scores) |
| 589 | merged_line_score.append( |
| 590 | ( |
| 591 | line_score[start_index][0], |
| 592 | line_score[end_index - 1][0], |
| 593 | highest_score, |
| 594 | ) |
| 595 | ) |
| 596 | start_index = end_index |
| 597 | merged_file_line_score[file] = merged_line_score |
| 598 | |
| 599 | # convert dict back to list of (file, start_line_no, end_line_no, score), and sort by score |
| 600 | res = [] |
| 601 | for file, line_score in merged_file_line_score.items(): |
| 602 | for start_line, end_line, score in line_score: |
| 603 | res.append((file, start_line, end_line, score)) |
| 604 | # sort by score (descending), then by file name, then by start line number |
| 605 | res = sorted(res, key=lambda x: (-x[3], x[0], x[1])) |
| 606 | return res |
| 607 | |
| 608 | |
| 609 | @cache |
| 610 | def method_ranges_in_file(file: str) -> dict[MethodId, tuple[int, int]]: |
| 611 | """ |
| 612 | Find the ranges of all methods in a python file. |
| 613 | |
| 614 | Result key is method name, value is (start_line, end_line), inclusive. |
| 615 | """ |
| 616 | |
| 617 | class MethodRangeFinder(ast.NodeVisitor): |
| 618 | def __init__(self): |
| 619 | self.range_map: dict[MethodId, tuple[int, int]] = {} |
| 620 | self.class_name = "" |
| 621 | |
| 622 | def calc_method_id(self, method_name: str) -> MethodId: |
| 623 | return MethodId(self.class_name, method_name) |
| 624 | |
| 625 | def visit_ClassDef(self, node: ast.ClassDef) -> None: |
| 626 | self.class_name = node.name |
| 627 | super().generic_visit(node) |
| 628 | self.class_name = "" |
| 629 | |
| 630 | def visit_FunctionDef(self, node: ast.FunctionDef) -> None: |
| 631 | method_id = self.calc_method_id(node.name) |
| 632 | assert node.end_lineno |
| 633 | self.range_map[method_id] = (node.lineno, node.end_lineno) |
| 634 | |
| 635 | def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None: |
| 636 | method_id = self.calc_method_id(node.name) |
| 637 | assert node.end_lineno |
| 638 | self.range_map[method_id] = (node.lineno, node.end_lineno) |
| 639 | |
| 640 | finder = MethodRangeFinder() |
| 641 | |
| 642 | source = Path(file).read_text() |
| 643 | |
| 644 | try: |
| 645 | tree = ast.parse(source, file) |
| 646 | except SyntaxError: |
| 647 | return {} |
| 648 | |
| 649 | finder.visit(tree) |
| 650 | |
| 651 | return finder.range_map |
| 652 | |
| 653 | |
| 654 | def map_collated_results_to_methods(ranked_ranges) -> list[tuple[str, str, str, float]]: |
| 655 | """ |
| 656 | Map suspicious lines to methods. |
| 657 | |
| 658 | Return list of (filename, methodname, suspicousness). |
| 659 | A method is added at most once, when it is first seen in the line list. |
| 660 | """ |
| 661 | seen = set() |
| 662 | |
| 663 | result = [] |
| 664 | for x in ranked_ranges: |
| 665 | filename, start, end, suspiciousness = x |
| 666 | range_map = method_ranges_in_file(filename) |
| 667 | |
| 668 | for method_id, r in range_map.items(): |
| 669 | if r[0] > end or r[1] < start: |
| 670 | continue |
| 671 | |
| 672 | key = (filename, method_id) |
| 673 | if key in seen: |
| 674 | continue |
| 675 | |
| 676 | result.append( |
| 677 | (filename, method_id.class_name, method_id.method_name, suspiciousness) |
| 678 | ) |
| 679 | seen.add(key) |
| 680 | return result |