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

This commit is contained in:
2026-11-11 20:01:42 +01:00
parent 38c64c9f12
commit 4c9bc080bb
2 changed files with 274 additions and 104 deletions
+19 -104
View File
@@ -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 <this> <log> <mode> 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__":