Run mutate-changes in-process in its tests, so mutmut sees the code they reach, and kill the mutants of mutmut_setup and mutmut_mutants that change behaviour

This commit is contained in:
2026-11-11 19:39:40 +01:00
parent 8f253dae3b
commit aa777819e8
2 changed files with 45 additions and 8 deletions
+1 -1
View File
@@ -78,4 +78,4 @@ def defined(tree: ast.Module, key: str) -> ast.AsyncFunctionDef | ast.FunctionDe
def as_named(lines: list[str], function: ast.AsyncFunctionDef | ast.FunctionDef, name: str) -> list[str]: def as_named(lines: list[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.""" """A function's lines from its def, decorators left out, with the def naming it name."""
spanned = lines[function.lineno - 1:function.end_lineno] spanned = lines[function.lineno - 1:function.end_lineno]
return [spanned[0].replace(function.name, name, 1), *spanned[1:]] if spanned else [] return [spanned[0].replace(function.name, name), *spanned[1:]]
+44 -7
View File
@@ -1,10 +1,14 @@
import configparser import configparser
import contextlib
import io
import os
import pathlib import pathlib
import subprocess import subprocess
import sys import sys
import tempfile import tempfile
import textwrap import textwrap
import unittest import unittest
import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
@@ -13,6 +17,7 @@ from failure import Failure
from mutate_changes.mutmut_mutants import function_keys, mutant_globs, mutated_line, named, statuses from mutate_changes.mutmut_mutants import function_keys, mutant_globs, mutated_line, named, statuses
from test_env import isolated_env from test_env import isolated_env
from mutate_changes.mutmut_setup import left_out, mutmut_config from mutate_changes.mutmut_setup import left_out, mutmut_config
from mutate_changes import main
TOOL = pathlib.Path(__file__).resolve().parents[1] / "mutate-changes" 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" 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"
@@ -74,9 +79,11 @@ class ChangedLines(unittest.TestCase):
class MutmutSetup(unittest.TestCase): class MutmutSetup(unittest.TestCase):
def test_the_config_mutates_the_sources_and_copies_each_entry_of_the_folder(self): def test_the_config_mutates_the_sources_and_copies_each_entry_of_the_folder(self):
text = mutmut_config("", ["x/a.py", "b.py"], ["b.py", "x"], []) for existing in ("", "[mutmut]\nsource_paths = old.py\nalso_copy = old\n"):
self.assertEqual(read_as_mutmut(text, "source_paths"), ["x/a.py", "b.py"]) with self.subTest(existing):
self.assertEqual(read_as_mutmut(text, "also_copy"), ["b.py", "x"]) text = mutmut_config(existing, ["x/a.py", "b.py"], ["b.py", "x"], [])
self.assertEqual(read_as_mutmut(text, "source_paths"), ["x/a.py", "b.py"])
self.assertEqual(read_as_mutmut(text, "also_copy"), ["b.py", "x"])
def test_the_config_keeps_the_projects_settings_and_appends_the_tests_left_out(self): def test_the_config_keeps_the_projects_settings_and_appends_the_tests_left_out(self):
existing = "[tool:pytest]\naddopts = -q\n\n[mutmut]\npytest_add_cli_args = -k\n not Slow\ndebug = true\n" existing = "[tool:pytest]\naddopts = -q\n\n[mutmut]\npytest_add_cli_args = -k\n not Slow\ndebug = true\n"
@@ -87,12 +94,18 @@ class MutmutSetup(unittest.TestCase):
config.read_string(text) config.read_string(text)
self.assertEqual(config.get("tool:pytest", "addopts"), "-q") self.assertEqual(config.get("tool:pytest", "addopts"), "-q")
def test_the_tests_left_out_are_the_only_pytest_options_where_the_project_sets_none(self):
self.assertEqual(read_as_mutmut(mutmut_config("", ["a.py"], ["a.py"], ["--ignore=t.py"]), "pytest_add_cli_args"), ["--ignore=t.py"])
def test_a_setup_cfg_that_cannot_be_read_fails(self): def test_a_setup_cfg_that_cannot_be_read_fails(self):
self.assertIsInstance(mutmut_config("[mutmut]\na = 1\na = 2\n", ["a.py"], ["a.py"], []), Failure) failed = mutmut_config("[mutmut]\na = 1\na = 2\n", ["a.py"], ["a.py"], [])
assert isinstance(failed, Failure)
self.assertIn("could not read setup.cfg", failed.reason)
def test_left_out_names_each_test_the_summary_reports_failing(self): def test_left_out_names_each_test_the_summary_reports_failing(self):
output = textwrap.dedent("""\ output = textwrap.dedent("""\
FAILED fake.py::t - this line is a test's own output, above the summary ==== short test summary info ====
FAILED fake.py::t - these two lines are a test's own output, above the summary
ERROR root:x.py:3 a log line ERROR root:x.py:3 a log line
=========================== short test summary info ============================ =========================== short test summary info ============================
FAILED repo_checks/test_repo_checks.py::Repo::test_a - AssertionError: x - y FAILED repo_checks/test_repo_checks.py::Repo::test_a - AssertionError: x - y
@@ -128,7 +141,7 @@ class MutmutMutants(unittest.TestCase):
self.assertIsNone(named("other.x_f__mutmut_1", paths)) self.assertIsNone(named("other.x_f__mutmut_1", paths))
def test_statuses_read_mutmut_results(self): def test_statuses_read_mutmut_results(self):
results = " pkg.x_f__mutmut_1: survived\n pkg.x_f__mutmut_2: no tests\n\n pkg.x_f__mutmut_3: killed\n" results = " pkg.x_f__mutmut_1: survived\n pkg.x_f__mutmut_2: no tests\n\n pkg.x_f__mutmut_3: killed\n pkg.x_f__mutmut_4:\n mutants: 4\n"
self.assertEqual(statuses(results), {"pkg.x_f__mutmut_1": "survived", "pkg.x_f__mutmut_2": "no tests", "pkg.x_f__mutmut_3": "killed"}) self.assertEqual(statuses(results), {"pkg.x_f__mutmut_1": "survived", "pkg.x_f__mutmut_2": "no tests", "pkg.x_f__mutmut_3": "killed"})
def test_a_mutated_line_is_the_first_line_the_mutant_changes_at_its_place_in_the_source(self): def test_a_mutated_line_is_the_first_line_the_mutant_changes_at_its_place_in_the_source(self):
@@ -139,6 +152,17 @@ class MutmutMutants(unittest.TestCase):
def test_a_mutant_the_copy_lacks_or_a_copy_unlike_the_source_has_no_line(self): def test_a_mutant_the_copy_lacks_or_a_copy_unlike_the_source_has_no_line(self):
self.assertIsNone(mutated_line(SOURCE, COPY, "x_double", 9)) self.assertIsNone(mutated_line(SOURCE, COPY, "x_double", 9))
self.assertIsNone(mutated_line(SOURCE.replace("n * 2", "n * 2 + 1"), COPY, "x_double", 1)) self.assertIsNone(mutated_line(SOURCE.replace("n * 2", "n * 2 + 1"), COPY, "x_double", 1))
self.assertIsNone(mutated_line(SOURCE, COPY + "def x_double__mutmut_2(n):\n\treturn n * 2\n", "x_double", 2))
def test_a_key_the_source_does_not_define_has_no_line(self):
for key in ("x_double", "x_nope", "xǁNopeǁmoved", "xǁPtǁnope"):
with self.subTest(key):
self.assertIsNone(mutated_line("import os\n\n\nclass Pt:\n\tpass\n", COPY, key, 1))
def test_a_mutated_line_is_found_in_the_function_or_method_its_key_names_among_others(self):
others = "import os\n\n\ndef triple(n):\n\treturn n * 3\n\n\nclass Q:\n\tdef moved(self, by=1):\n\t\treturn 0\n\n\n"
self.assertEqual(mutated_line(others + SOURCE, COPY, "x_double", 1), (14, "return n / 2"))
self.assertEqual(mutated_line(others + SOURCE, COPY, "xǁPtǁmoved", 2), (19, "return self.x - by"))
self.assertIsNone(mutated_line(SOURCE, "def broken(:\n", "x_double", 1)) self.assertIsNone(mutated_line(SOURCE, "def broken(:\n", "x_double", 1))
@@ -188,7 +212,15 @@ class MutateChangesTool(unittest.TestCase):
self.git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "x") self.git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "x")
def run_tool(self, *args): def run_tool(self, *args):
return subprocess.run([str(TOOL), *args], capture_output=True, cwd=self.checkout, encoding="utf-8", env=isolated_env()) """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): def faked(self, mode):
return ["--prefix", f"python3 {self.temp / 'fake_mutmut.py'} {self.log} {mode}"] return ["--prefix", f"python3 {self.temp / 'fake_mutmut.py'} {self.log} {mode}"]
@@ -230,6 +262,11 @@ class MutateChangesTool(unittest.TestCase):
self.assertEqual(ran.returncode, 1) self.assertEqual(ran.returncode, 1)
self.assertIn("usage: mutate-changes", ran.stderr) 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__": if __name__ == "__main__":
unittest.main() unittest.main()