From 4c9bc080bbd2b9634899dd837bd2a8791bc89d39 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 11 Nov 2026 20:01:42 +0100 Subject: [PATCH] Kill mutate-changes' surviving mutants with tests of its other tools, its git config, its output and the files it copies, and move its runs to their own test file --- bin/mutate_changes/test_mutate_changes.py | 123 ++------- .../test_mutate_changes_runs.py | 255 ++++++++++++++++++ 2 files changed, 274 insertions(+), 104 deletions(-) create mode 100644 bin/mutate_changes/test_mutate_changes_runs.py diff --git a/bin/mutate_changes/test_mutate_changes.py b/bin/mutate_changes/test_mutate_changes.py index 8800bec0..b2fa7228 100644 --- a/bin/mutate_changes/test_mutate_changes.py +++ b/bin/mutate_changes/test_mutate_changes.py @@ -1,25 +1,20 @@ import configparser -import contextlib -import io import os import pathlib -import subprocess import sys import tempfile import textwrap import unittest -import unittest.mock 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 failure import Failure from mutate_changes.mutmut_mutants import function_keys, mutant_globs, mutated_line, named, statuses -from test_env import isolated_env from mutate_changes.mutmut_setup import left_out, mutmut_config from mutate_changes import main -TOOL = pathlib.Path(__file__).resolve().parents[1] / "mutate-changes" SOURCE = "def double(n):\n\treturn n * 2\n\n\nclass Pt:\n\tdef moved(self, by=1):\n\t\treturn self.x + by\n" # The shape of the file mutmut 3 writes under mutants/: the original of each function and its mutants, with the original's lines. COPY = """from inspect import signature as _mutmut_signature @@ -166,106 +161,26 @@ class MutmutMutants(unittest.TestCase): self.assertIsNone(mutated_line(SOURCE, "def broken(:\n", "x_double", 1)) -# Stands in for mutmut, run through --prefix as `python3 mutmut ...` in the scratch copy. It logs each call with -# the setup.cfg it finds there, then writes a mutants/ copy and prints results, both shaped like mutmut 3's. -FAKE_MUTMUT = r"""import pathlib, sys -log, mode, args = pathlib.Path(sys.argv[1]), sys.argv[2], sys.argv[3:] -config = pathlib.Path("setup.cfg").read_text() -with log.open("a") as written: - written.write(" ".join(args) + "\n" + config + "---\n") -if args[:2] == ["mutmut", "results"]: - print(" calc.x_triple__mutmut_1: survived\n calc.x_triple__mutmut_2: killed\n calc.x_double__mutmut_1: survived") -elif mode == "fails-once" and not ("--deselect=test_calc.py::Calc::test_slow" in config and "--ignore=test_io.py" in config): - print("==== short test summary info ====\nFAILED test_calc.py::Calc::test_slow - boom\nERROR test_io.py - FileNotFoundError\nfailed to collect stats. runner returned 1") - sys.exit(1) -else: - pathlib.Path("mutants").mkdir(exist_ok=True) - functions = ["x_double__mutmut_orig(n):\n\treturn n * 2", "x_double__mutmut_1(n):\n\treturn n / 2", "x_triple__mutmut_orig(n):\n\treturn n * 3", "x_triple__mutmut_1(n):\n\treturn n / 3", "x_triple__mutmut_2(n):\n\treturn n * 4"] - pathlib.Path("mutants/calc.py").write_text("".join(f"def {function}\n" for function in functions)) -""" +class MutmutTool(unittest.TestCase): + 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") + for path in ("a.py", "d/b.py", "mutants/x.py", ".mutate-changes-old/copy/y.py", "sub/c.py"): + (root / path).parent.mkdir(parents=True, exist_ok=True) + (root / path).write_text("") + (root / "link").symlink_to("a.py") + (root / "dirlink").symlink_to("d") + # The list names a submodule as one path, a folder, and ends with an empty path. + listed = ["", "mutants/x.py", ".mutate-changes-old/copy/y.py", "gone.py", "sub", "a.py", "d/b.py", "dirlink", "link"] + self.assertEqual(copy_files(str(root), listed, str(copy)), ["a.py", "d", "dirlink", "link"]) + walked = sorted(os.path.relpath(os.path.join(folder, name), copy) for folder, folders, files in os.walk(copy) for name in folders + files) + self.assertEqual(walked, ["a.py", "d", "d/b.py", "dirlink", "link"]) + self.assertEqual((os.readlink(copy / "link"), os.readlink(copy / "dirlink")), ("a.py", "d")) -class MutateChangesTool(unittest.TestCase): - def setUp(self): - temp = tempfile.TemporaryDirectory() - self.addCleanup(temp.cleanup) - self.temp = pathlib.Path(temp.name) - self.checkout = self.temp / "proj" - (self.checkout / "pkg").mkdir(parents=True) - (self.checkout / "pkg" / "setup.cfg").write_text("[mutmut]\n") - (self.checkout / "pkg" / "calc.py").write_text("def double(n):\n\treturn n * 2\n") - (self.checkout / "pkg" / "test_calc.py").write_text("") - self.git("init", "-q", "-b", "main") - self.commit() - self.git("checkout", "-q", "-b", "work") - (self.checkout / "pkg" / "calc.py").write_text("def double(n):\n\treturn n * 2\n\n\ndef triple(n):\n\treturn n * 3\n") - (self.checkout / "pkg" / "test_calc.py").write_text("# changed, but a test file is not mutated\n") - self.commit() - (self.temp / "fake_mutmut.py").write_text(FAKE_MUTMUT) - self.log = self.temp / "calls.log" - - def git(self, *args): - subprocess.run(["git", *args], check=True, cwd=self.checkout, env={**isolated_env(), "GIT_CONFIG_GLOBAL": "/dev/null"}) - - def commit(self): - self.git("add", ".") - self.git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "x") - - def run_tool(self, *args): - """Run mutate-changes in this process, from the checkout: mutmut counts only the code a test reaches in its own process.""" - before = os.getcwd() - os.chdir(self.checkout) - try: - with unittest.mock.patch.dict(os.environ, isolated_env(), clear=True), contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as err: - code = main.main(list(args)) - finally: - os.chdir(before) - return subprocess.CompletedProcess(args, code, out.getvalue(), err.getvalue()) - - def faked(self, mode): - return ["--prefix", f"python3 {self.temp / 'fake_mutmut.py'} {self.log} {mode}"] - - 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") - self.assertEqual(ran.returncode, 0, ran.stderr) - self.assertEqual(ran.stdout.splitlines()[:2], ["mutmut in pkg: 2 mutants on changed lines, 1 not killed.", "pkg/calc.py:6: survived: return n / 3"]) - calls = self.log.read_text() - self.assertIn("mutmut run --max-children 2 calc.x_triple*\n", calls) - self.assertIn("source_paths = calc.py\n", calls) - self.assertIn("also_copy = calc.py\n\tsetup.cfg\n\ttest_calc.py\n", calls) - self.assertEqual((self.checkout / "pkg" / "setup.cfg").read_text(), "[mutmut]\n") - self.assertEqual(sorted(path.name for path in self.checkout.iterdir()), [".git", "pkg"]) - - def test_leaves_out_the_tests_that_fail_before_any_mutant_and_names_them(self): - ran = self.run_tool(*self.faked("fails-once")) - self.assertEqual(ran.returncode, 0, ran.stderr) - self.assertEqual(ran.stdout.splitlines()[:2], ["mutmut in pkg: 2 mutants on changed lines, 1 not killed. Left out tests in test_calc.py, test_io.py that fail without a mutant.", "pkg/calc.py:6: survived: return n / 3"]) - first, second = self.log.read_text().split("---\n")[:2] - self.assertIn("--maxfail=0", first) - self.assertNotIn("--maxfail=0", second) - - def test_a_tool_that_fails_fails_the_run_with_its_output(self): - ran = self.run_tool("--prefix", "echo broken; false") - self.assertEqual(ran.returncode, 1) - self.assertIn("mutmut run in pkg exited 1", ran.stderr) - self.assertIn("broken", ran.stderr) - - def test_a_branch_that_changes_no_mutated_language_says_so(self): - ran = self.run_tool(*self.faked("passes"), "--base", "HEAD") - self.assertEqual((ran.returncode, ran.stdout), (0, "No line the branch changes is in a language mutate-changes mutates.\n")) - self.assertFalse(self.log.exists()) - - def test_unknown_arguments_fail(self): - for args in (["--jobs", "0"], ["--jobs"], ["--colour"], ["--base", "a", "--base", "b"]): - with self.subTest(args): - ran = self.run_tool(*args) - self.assertEqual(ran.returncode, 1) - self.assertIn("usage: mutate-changes", ran.stderr) - - def test_the_launcher_runs_the_tool(self): - # Run from the launcher's folder: there, under mutmut, the child finds the setup.cfg that mutmut's mutated code reads. - ran = subprocess.run([str(TOOL), "--help"], capture_output=True, cwd=TOOL.parent, encoding="utf-8", env=isolated_env()) - self.assertEqual((ran.returncode, ran.stdout.splitlines()[0]), (0, "Mutation-test the lines a branch adds or changes, and print each mutant its tests don't kill.")) +class Took(unittest.TestCase): + def test_took_rounds_to_the_second_and_counts_minutes_from_one(self): + self.assertEqual([main.took(seconds) for seconds in (59.4, 59.6, 61, 3725.4)], ["59 s", "1 min 0 s", "1 min 1 s", "62 min 5 s"]) if __name__ == "__main__": diff --git a/bin/mutate_changes/test_mutate_changes_runs.py b/bin/mutate_changes/test_mutate_changes_runs.py new file mode 100644 index 00000000..2b01c900 --- /dev/null +++ b/bin/mutate_changes/test_mutate_changes_runs.py @@ -0,0 +1,255 @@ +"""mutate-changes run on a branch, against fake mutation tools that log how they were called.""" +import contextlib +import io +import os +import pathlib +import re +import shutil +import subprocess +import sys +import tempfile +import unittest +import unittest.mock + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from test_env import isolated_env +from mutate_changes import main + +TOOL = pathlib.Path(__file__).resolve().parents[1] / "mutate-changes" +SETUP = "[mutmut]\ndo_not_mutate = *_old.py\n" +PASSED = ["mutmut in pkg: 2 mutants on changed lines, 1 not killed.", "pkg/calc.py:6: survived: return n / 3"] +# Stands in for mutmut, run through --prefix as `python3 mutmut ...` in the scratch copy. It logs each call with +# the folder it runs in and the setup.cfg it finds there, then writes a mutants/ copy and prints results, both shaped like mutmut 3's. +FAKE_MUTMUT = r"""import os, pathlib, sys +log, mode, args = pathlib.Path(sys.argv[1]), sys.argv[2], sys.argv[3:] +config = pathlib.Path("setup.cfg").read_text() +with log.open("a") as written: + written.write(f"{os.getcwd()}\n{' '.join(args)}\n{config}---\n") +if args[:2] == ["mutmut", "results"]: + if mode == "results-fail" or args[2:] != ["--all", "true"]: + sys.exit("mutmut results broke") + double, triple_1, triple_2 = ("no tests",) * 3 if mode == "no-test" else ("survived", "survived", "killed") + print(f" other.x_f__mutmut_1: survived\n calc.x_double__mutmut_1: {double}\n calc.x_triple__mutmut_1: {triple_1}\n calc.x_triple__mutmut_2: {triple_2}") +elif mode == "fails-once" and not ("--deselect=test_calc.py::test_slow[n=1]" in config and "--ignore=test_io.py" in config): + print("==== short test summary info ====\nFAILED test_calc.py::test_slow[n=1] - boom\nERROR test_io.py - FileNotFoundError\nfailed to collect stats. runner returned 1") + sys.exit(1) +else: + if mode != "no-copy": + pathlib.Path("mutants").mkdir(exist_ok=True) + functions = ["x_double__mutmut_orig(n): # doubles\n\treturn n * 2", "x_double__mutmut_1(n): # doubles\n\treturn n / 2", "x_triple__mutmut_orig(n):\n\treturn n * 3", "x_triple__mutmut_1(n):\n\treturn n / 3", "x_triple__mutmut_2(n):\n\treturn n * 4"] + pathlib.Path("mutants/calc.py").write_bytes(b"# \xff is not UTF-8\n" + "".join(f"def {function}\n" for function in functions).encode()) + if mode == "no-test": + 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 +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") + 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 / "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") +sys.exit(code) +""" + + +@contextlib.contextmanager +def stdin_holding(text: str): + """This process's stdin, the one a child inherits, as a pipe holding text.""" + read, write = os.pipe() + os.write(write, text.encode()) + os.close(write) + saved = os.dup(0) + os.dup2(read, 0) + os.close(read) + try: + yield + finally: + os.dup2(saved, 0) + os.close(saved) + + +class MutateChangesRuns(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.temp = pathlib.Path(temp.name) + self.checkout = self.temp / "proj" + (self.checkout / "pkg").mkdir(parents=True) + (self.checkout / "pkg" / "setup.cfg").write_text(SETUP) + (self.checkout / "pkg" / "calc.py").write_text("def double(n):\n\treturn n * 2\n") + (self.checkout / "pkg" / "test_calc.py").write_text("") + self.git("init", "-q", "-b", "main") + self.commit() + self.git("checkout", "-q", "-b", "work") + # git lists the README first, and mutate-changes mutates no Markdown. + (self.checkout / "README.md").write_text("Doubles and triples.\n") + (self.checkout / "pkg" / "calc.py").write_text("def double(n): # doubles\n\treturn n * 2\n\n\ndef triple(n):\n\treturn n * 3\n") + (self.checkout / "pkg" / "test_calc.py").write_text("# changed, but a test file is not mutated\n") + self.commit() + # Settings a user may have that change what git diff prints, and a file git lists as untracked and one it ignores. + for name, value in (("color.diff", "always"), ("diff.relative", "true"), ("diff.external", "true"), ("diff.blank.textconv", "true")): + self.git("config", name, value) + (self.checkout / ".git" / "info").mkdir(exist_ok=True) + (self.checkout / ".git" / "info" / "attributes").write_text("* diff=blank\n") + (self.checkout / ".git" / "info" / "exclude").write_text("*.log\n") + (self.checkout / "pkg" / "fixture.txt").write_text("") + (self.checkout / "pkg" / "run.log").write_text("") + (self.temp / "fake_mutmut.py").write_text(FAKE_MUTMUT) + (self.temp / "fake_tools.py").write_text(FAKE_TOOLS) + self.log = self.temp / "calls.log" + + def git(self, *args): + return subprocess.run(["git", *args], check=True, capture_output=True, cwd=self.checkout, encoding="utf-8", env={**isolated_env(), "GIT_CONFIG_GLOBAL": "/dev/null"}).stdout + + def commit(self): + self.git("add", ".") + self.git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "x") + + def run_tool(self, *args, cwd=None, env=None): + """Run mutate-changes in this process, from cwd, else the checkout: mutmut counts only the code a test reaches in its own process.""" + before = os.getcwd() + os.chdir(cwd or self.checkout) + try: + with unittest.mock.patch.dict(os.environ, {**isolated_env(), **(env or {})}, clear=True), contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as err: + code = main.main(list(args)) + finally: + os.chdir(before) + return subprocess.CompletedProcess(args, code, out.getvalue(), err.getvalue()) + + def faked(self, mode): + 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.""" + (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(" i32 {\n\tb + a\n}\n") + (self.checkout / "src" / "Calc.php").write_bytes(b"&2; printf '\\377'; false") + self.assertEqual((ran.returncode, ran.stderr), (1, "\n".join(["mutmut run in pkg exited 1:", *map(str, range(8, 46)), "broken", "�"]) + "\n")) + + def test_mutmut_results_that_fails_fails_the_run(self): + ran = self.run_tool(*self.faked("results-fail")) + self.assertEqual((ran.returncode, ran.stderr), (1, "mutmut results in pkg exited 1:\nmutmut results broke\n")) + + def test_a_tool_gets_an_empty_input_in_place_of_the_terminal(self): + # npx, for one, asks before it installs a package, and would wait for an answer. + with stdin_holding("y\n"): + ran = self.run_tool("--prefix", "cat; false") + 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")) + ran = self.run_tool(env={"PATH": str(tools)}) + self.assertEqual(ran.returncode, 1) + self.assertRegex(ran.stderr, "^mutmut run .* could not start: ") + (tools / "mutmut").write_text(f'#!/bin/sh\nexec {sys.executable} {self.temp / "fake_mutmut.py"} {self.log} passes mutmut "$@"\n') + (tools / "mutmut").chmod(0o755) + 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): + 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") + 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"]) + self.assertEqual(sorted(path.name for path in self.checkout.iterdir()), [".git", "README.md", "pkg", "src"]) + + 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)): + with self.subTest(code): + ran = self.run_tool("--base", "HEAD", "--prefix", f"python3 {self.temp / 'fake_tools.py'} {self.log} {code}") + self.assertEqual((ran.returncode, ran.stderr), (1, f"cargo mutants exited {code}:\ncargo reports\n") if failed else (0, "")) + + def test_a_branch_that_changes_no_mutated_language_says_so(self): + ran = self.run_tool(*self.faked("passes"), "--base", "HEAD") + self.assertEqual((ran.returncode, ran.stdout), (0, "No line the branch changes is in a language mutate-changes mutates.\n")) + self.assertFalse(self.log.exists()) + + def test_help_prints_the_usage(self): + for flag in ("-h", "--help"): + with self.subTest(flag): + ran = self.run_tool(flag) + self.assertEqual((ran.returncode, ran.stdout.splitlines()[0]), (0, "Mutation-test the lines a branch adds or changes, and print each mutant its tests don't kill.")) + + def test_unknown_arguments_fail(self): + for args in (["--jobs", "0"], ["--jobs", "x"], ["--jobs"], ["--colour"], ["--base", "a", "--base", "b"]): + with self.subTest(args): + ran = self.run_tool(*args) + self.assertEqual(ran.returncode, 1) + self.assertIn("usage: mutate-changes", ran.stderr) + + def test_the_launcher_runs_the_tool(self): + # Run from the launcher's folder: there, under mutmut, the child finds the setup.cfg that mutmut's mutated code reads. + ran = subprocess.run([str(TOOL), "--help"], capture_output=True, cwd=TOOL.parent, encoding="utf-8", env=isolated_env()) + self.assertEqual((ran.returncode, ran.stdout.splitlines()[0]), (0, "Mutation-test the lines a branch adds or changes, and print each mutant its tests don't kill.")) + + +if __name__ == "__main__": + unittest.main()