Parse each mutants/ copy once when reporting mutmut's mutants, and kill more survivors with tests of by_folder, the in-diff tools' folder and their start failures
This commit is contained in:
@@ -2,6 +2,9 @@
|
||||
|
||||
mutmut names a mutant `<module>.<key>__mutmut_<number>`. The key is x_<function> for a function at a module's top, and xǁ<class>ǁ<method> for a method of a class there; mutmut mutates no other code. Its mutants/ copy of a file holds the original of each function it mutates, as `<key>__mutmut_orig`, and each mutant as a copy of it."""
|
||||
import ast
|
||||
import functools
|
||||
from typing import NamedTuple
|
||||
from collections.abc import Sequence
|
||||
|
||||
|
||||
def function_keys(source: str, lines: frozenset[int]) -> list[str]:
|
||||
@@ -46,22 +49,40 @@ def mutated_line(source: str, copy: str, key: str, number: int) -> tuple[int, st
|
||||
"""The source line a mutant changes, with that line as the mutant has it; None where the mutants/ copy lacks the mutant, or holds an original unlike the source.
|
||||
|
||||
A mutant keeps the original's lines, so the first line where they differ sits at the same offset from the source function's def."""
|
||||
try:
|
||||
function = defined(ast.parse(source), key)
|
||||
copied = {node.name: node for node in ast.walk(ast.parse(copy)) if isinstance(node, (ast.AsyncFunctionDef, ast.FunctionDef))}
|
||||
except SyntaxError:
|
||||
module, copied = parsed(source), parsed(copy)
|
||||
if module is None or copied is None:
|
||||
return None
|
||||
original, mutant = copied.get(f"{key}__mutmut_orig"), copied.get(f"{key}__mutmut_{number}")
|
||||
function = defined(module.tree, key)
|
||||
original, mutant = copied.functions.get(f"{key}__mutmut_orig"), copied.functions.get(f"{key}__mutmut_{number}")
|
||||
if function is None or original is None or mutant is None:
|
||||
return None
|
||||
expected = as_named(source.splitlines(), function, function.name)
|
||||
kept, changed = (as_named(copy.splitlines(), node, function.name) for node in (original, mutant))
|
||||
expected = as_named(module.lines, function, function.name)
|
||||
kept, changed = (as_named(copied.lines, node, function.name) for node in (original, mutant))
|
||||
if kept != expected:
|
||||
return None
|
||||
offset = next((index for index, (was, now) in enumerate(zip(kept, changed)) if was != now), None)
|
||||
return None if offset is None else (function.lineno + offset, changed[offset].strip())
|
||||
|
||||
|
||||
class Parsed(NamedTuple):
|
||||
tree: ast.Module
|
||||
functions: dict[str, ast.AsyncFunctionDef | ast.FunctionDef]
|
||||
lines: tuple[str, ...]
|
||||
|
||||
|
||||
# mutated_line reads the same source and mutants/ copy for each of a file's mutants, and a copy holds every mutant, so parsing it
|
||||
# anew for each one made the report take minutes.
|
||||
@functools.lru_cache(maxsize=4)
|
||||
def parsed(text: str) -> Parsed | None:
|
||||
"""A module's tree, each function or method in it by name, and its lines; None where it isn't valid Python."""
|
||||
try:
|
||||
tree = ast.parse(text)
|
||||
except SyntaxError:
|
||||
return None
|
||||
functions = {node.name: node for node in ast.walk(tree) if isinstance(node, (ast.AsyncFunctionDef, ast.FunctionDef))}
|
||||
return Parsed(tree, functions, tuple(text.splitlines()))
|
||||
|
||||
|
||||
def defined(tree: ast.Module, key: str) -> ast.AsyncFunctionDef | ast.FunctionDef | None:
|
||||
"""The function or method mutmut's key names, from a module's top or a class there."""
|
||||
if key.startswith("x_"):
|
||||
@@ -75,7 +96,7 @@ def defined(tree: ast.Module, key: str) -> ast.AsyncFunctionDef | ast.FunctionDe
|
||||
return next((node for node in scope if isinstance(node, (ast.AsyncFunctionDef, ast.FunctionDef)) and node.name == name), None)
|
||||
|
||||
|
||||
def as_named(lines: list[str], function: ast.AsyncFunctionDef | ast.FunctionDef, name: str) -> list[str]:
|
||||
def as_named(lines: Sequence[str], function: ast.AsyncFunctionDef | ast.FunctionDef, name: str) -> list[str]:
|
||||
"""A function's lines from its def, decorators left out, with the def naming it name."""
|
||||
spanned = lines[function.lineno - 1:function.end_lineno]
|
||||
return [spanned[0].replace(function.name, name), *spanned[1:]]
|
||||
|
||||
@@ -176,7 +176,8 @@ def not_killed(folder: Folder, found: dict[str, str], copy: str) -> tuple[list[s
|
||||
copies: dict[str, str] = {}
|
||||
shown: list[tuple[str, int, str]] = []
|
||||
counted = 0
|
||||
for name, status in found.items():
|
||||
# Sorted by name, a file's mutants come one after another, so mutated_line parses its copy once.
|
||||
for name, status in sorted(found.items()):
|
||||
hit = named(name, list(folder.files))
|
||||
if hit is None or hit[1] not in folder.keys[hit[0]]:
|
||||
continue
|
||||
|
||||
@@ -9,7 +9,7 @@ import unittest
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from mutate_changes.changed_lines import added_lines, runs, tool_for
|
||||
from mutate_changes.mutmut_tool import copy_files
|
||||
from mutate_changes.mutmut_tool import by_folder, copy_files
|
||||
from failure import Failure
|
||||
from mutate_changes.mutmut_mutants import function_keys, mutant_globs, mutated_line, named, statuses
|
||||
from mutate_changes.mutmut_setup import left_out, mutmut_config
|
||||
@@ -162,6 +162,15 @@ class MutmutMutants(unittest.TestCase):
|
||||
|
||||
|
||||
class MutmutTool(unittest.TestCase):
|
||||
def test_each_file_goes_to_the_nearest_folder_above_it_that_sets_python_up(self):
|
||||
with tempfile.TemporaryDirectory() as top:
|
||||
for config in ("pkg/setup.cfg", "pkg/inner/lib/pyproject.toml"):
|
||||
pathlib.Path(top, config).parent.mkdir(parents=True)
|
||||
pathlib.Path(top, config).write_text("")
|
||||
lines = frozenset({1})
|
||||
grouped = by_folder(top, {"pkg/inner/deep.py": lines, "pkg/inner/lib/x.py": lines, "top.py": lines})
|
||||
self.assertEqual(grouped, {"pkg": {"inner/deep.py": lines}, "pkg/inner/lib": {"x.py": lines}, ".": {"top.py": lines}})
|
||||
|
||||
def test_copy_files_copies_what_is_listed_but_mutmuts_own_folders_and_names_the_entries_at_the_top(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
root, copy = pathlib.Path(temp, "root"), pathlib.Path(temp, "copy")
|
||||
|
||||
@@ -43,17 +43,18 @@ else:
|
||||
print("Stopping early, because we could not find any test case for any mutant.")
|
||||
sys.exit(1)
|
||||
"""
|
||||
# cargo-mutants, Infection and Stryker, which log how they were called and exit with the code the test gives. cargo-mutants also
|
||||
# logs the diff it is given and writes its outcome files, all but unviable.txt, as a run without an unviable mutant does.
|
||||
FAKE_TOOLS = r"""import pathlib, sys
|
||||
# cargo-mutants, Infection and Stryker, which log the folder they run in and how they were called, and exit with the code the test
|
||||
# gives. cargo-mutants also logs the diff it is given and writes its outcome files, all but unviable.txt, as a run without an
|
||||
# unviable mutant does.
|
||||
FAKE_TOOLS = r"""import os, pathlib, sys
|
||||
log, code, args = pathlib.Path(sys.argv[1]), int(sys.argv[2]), sys.argv[3:]
|
||||
with log.open("a") as written:
|
||||
written.write(" ".join(args) + "\n")
|
||||
written.write(f"{os.getcwd()}\n{' '.join(args)}\n")
|
||||
if args[0] == "cargo":
|
||||
written.write(pathlib.Path(args[args.index("--in-diff") + 1]).read_text())
|
||||
outcomes = pathlib.Path(args[args.index("--output") + 1], "mutants.out")
|
||||
outcomes.mkdir()
|
||||
(outcomes / "caught.txt").write_text("src/lib.rs:2:7: replace + with - in add\n")
|
||||
(outcomes / "caught.txt").write_bytes(b"src/lib.rs:2:7: replace + with - in add, \xff not being UTF-8\n")
|
||||
(outcomes / "missed.txt").write_text("src/lib.rs:2:5: replace add -> i32 with 0\n")
|
||||
(outcomes / "timeout.txt").write_text("src/lib.rs:2:7: replace + with * in add\n")
|
||||
print(f"{args[0]} reports")
|
||||
@@ -129,15 +130,24 @@ class MutateChangesRuns(unittest.TestCase):
|
||||
return ["--prefix", f"python3 {self.temp / 'fake_mutmut.py'} {self.log} {mode}"]
|
||||
|
||||
def change_rust_php_and_typescript(self):
|
||||
"""Commit a Rust, a PHP and a TypeScript file, then change line 2 of each in the working tree, PHP's with a byte that is not UTF-8."""
|
||||
"""Commit a Rust, a PHP and a TypeScript file, then change them: Rust's line 2 in the index, PHP's line 2 with a byte that is
|
||||
not UTF-8, and TypeScript's lines 1 and 4."""
|
||||
(self.checkout / "src").mkdir()
|
||||
(self.checkout / "src" / "lib.rs").write_text("pub fn add(a: i32, b: i32) -> i32 {\n\ta + b\n}\n")
|
||||
(self.checkout / "src" / "Calc.php").write_text("<?php\nfunction add($a, $b) { return $a + $b; }\n")
|
||||
(self.checkout / "src" / "calc.ts").write_text("export function add(a: number, b: number) {\n\treturn a + b;\n}\n")
|
||||
(self.checkout / "src" / "calc.ts").write_text("export function add(a: number, b: number) {\n\treturn a + b;\n}\nexport const one = 1;\n")
|
||||
self.commit()
|
||||
(self.checkout / "src" / "lib.rs").write_text("pub fn add(a: i32, b: i32) -> i32 {\n\tb + a\n}\n")
|
||||
self.git("add", "src/lib.rs")
|
||||
(self.checkout / "src" / "Calc.php").write_bytes(b"<?php\nfunction add($a, $b) { return $b + $a; } // caf\xe9\n")
|
||||
(self.checkout / "src" / "calc.ts").write_text("export function add(a: number, b: number) {\n\treturn b + a;\n}\n")
|
||||
(self.checkout / "src" / "calc.ts").write_text("export function add(b: number, a: number) {\n\treturn a + b;\n}\nexport const one = 2;\n")
|
||||
|
||||
def path_with_git(self):
|
||||
"""A PATH that finds git and no mutation tool."""
|
||||
tools = self.temp / "tools"
|
||||
tools.mkdir()
|
||||
(tools / "git").symlink_to(shutil.which("git"))
|
||||
return tools
|
||||
|
||||
def test_prints_each_mutant_on_a_changed_line_that_its_tests_do_not_kill(self):
|
||||
ran = self.run_tool(*self.faked("passes"), "--jobs", "2")
|
||||
@@ -197,9 +207,7 @@ class MutateChangesRuns(unittest.TestCase):
|
||||
self.assertEqual(ran.stderr, "mutmut run in pkg exited 1:\n")
|
||||
|
||||
def test_without_a_prefix_each_tool_runs_from_path(self):
|
||||
tools = self.temp / "tools"
|
||||
tools.mkdir()
|
||||
(tools / "git").symlink_to(shutil.which("git"))
|
||||
tools = self.path_with_git()
|
||||
ran = self.run_tool(env={"PATH": str(tools)})
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertRegex(ran.stderr, "^mutmut run .* could not start: ")
|
||||
@@ -208,18 +216,30 @@ class MutateChangesRuns(unittest.TestCase):
|
||||
ran = self.run_tool(env={"PATH": str(tools)})
|
||||
self.assertEqual((ran.returncode, ran.stdout.splitlines()[:2]), (0, PASSED), ran.stderr)
|
||||
|
||||
def test_rust_php_and_typescript_go_to_cargo_mutants_infection_and_stryker(self):
|
||||
def test_rust_php_and_typescript_go_to_cargo_mutants_infection_and_stryker_at_the_checkouts_top(self):
|
||||
self.change_rust_php_and_typescript()
|
||||
ran = self.run_tool("--base", "HEAD", "--jobs=3", "--prefix", f"python3 {self.temp / 'fake_tools.py'} {self.log} 2")
|
||||
ran = self.run_tool("--base", "HEAD", "--jobs=3", "--prefix", f"python3 {self.temp / 'fake_tools.py'} {self.log} 2", cwd=self.checkout / "src")
|
||||
report = ["cargo-mutants: 3 mutants on changed lines, 2 not caught.", "src/lib.rs:2:5: missed: replace add -> i32 with 0", "src/lib.rs:2:7: timeout: replace + with * in add"]
|
||||
self.assertEqual((ran.returncode, ran.stdout.splitlines()[:-1]), (0, [*report, "Infection exited 2; its report:", "vendor/bin/infection reports", "Stryker exited 2; its report:", "npx reports"]), ran.stderr)
|
||||
calls = self.log.read_text().splitlines()
|
||||
self.assertRegex(calls[0], r"^cargo mutants --in-diff (\.mutate-changes-\w+)/branch\.diff --output \1 --jobs 3$")
|
||||
self.assertEqual([line for line in calls[1:-2] if line[:1] in "+-"], ["--- a/src/lib.rs", "+++ b/src/lib.rs", "-\ta + b", "+\tb + a"])
|
||||
infection = f"vendor/bin/infection --git-diff-lines --git-diff-base={self.git('rev-parse', 'HEAD').strip()} --threads=3 --show-mutations=max --no-progress"
|
||||
self.assertEqual(calls[-2:], [infection, "npx stryker run --mutate src/calc.ts:2-2 --concurrency 3 --reporters clear-text"])
|
||||
cargo, infection, stryker = self.log.read_text().split(f"{self.checkout.resolve()}\n")[1:]
|
||||
command, diff = cargo.split("\n", 1)
|
||||
self.assertRegex(command, r"^cargo mutants --in-diff (\.mutate-changes-\w+)/branch\.diff --output \1 --jobs 3$")
|
||||
self.assertEqual([line for line in diff.splitlines() if line[:1] in "+-"], ["--- a/src/lib.rs", "+++ b/src/lib.rs", "-\ta + b", "+\tb + a"])
|
||||
self.assertEqual(infection, f"vendor/bin/infection --git-diff-lines --git-diff-base={self.git('rev-parse', 'HEAD').strip()} --threads=3 --show-mutations=max --no-progress\n")
|
||||
self.assertEqual(stryker, "npx stryker run --mutate src/calc.ts:1-1,src/calc.ts:4-4 --concurrency 3 --reporters clear-text\n")
|
||||
self.assertEqual(sorted(path.name for path in self.checkout.iterdir()), [".git", "README.md", "pkg", "src"])
|
||||
|
||||
def test_a_tool_that_cannot_start_fails_the_run(self):
|
||||
self.change_rust_php_and_typescript()
|
||||
path = str(self.path_with_git())
|
||||
# The tools run in the order of their names, so undoing the change of the one that failed lets the next one run.
|
||||
for tool, undone in (("cargo mutants", "src/lib.rs"), ("vendor/bin/infection", "src/Calc.php"), ("npx stryker", "src/calc.ts")):
|
||||
with self.subTest(tool):
|
||||
ran = self.run_tool("--base", "HEAD", env={"PATH": path})
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertRegex(ran.stderr, f"^{re.escape(tool)} .* could not start: ")
|
||||
self.git("checkout", "HEAD", "--", undone)
|
||||
|
||||
def test_cargo_mutants_fails_the_run_unless_it_finished(self):
|
||||
self.change_rust_php_and_typescript()
|
||||
for code, failed in ((0, False), (1, True), (3, False), (4, True)):
|
||||
|
||||
Reference in New Issue
Block a user