From d3c4e67487fac2bc9b324fd3d2afe8a0627eaea4 Mon Sep 17 00:00:00 2001 From: nafiurahman00 Date: Fri, 13 Nov 2026 02:03:10 +0600 Subject: [PATCH] Re-run mutants when tests are edited or added Cached results were only invalidated when the source changed, so removing an assertion from a test left its mutants as "killed", and a new test that kills a survivor didn't change anything until mutants/ was deleted. Store a hash of each test file (and the conftest.py files above it). When a test file changes, its tests are collected again and the mutants of the functions they covered are re-run. Functions covered by new tests get their survived/no tests results reset. conftest.py changes go through on_dependency_change since they can affect every test. Fixes #626 --- README.rst | 10 +- src/mutmut/__main__.py | 110 +++++++++++++++++++- src/mutmut/state.py | 3 + src/mutmut/stats.py | 3 + tests/mutation/test_mutation.py | 177 ++++++++++++++++++++++++++++++++ 5 files changed, 297 insertions(+), 6 deletions(-) diff --git a/README.rst b/README.rst index 9e0f542a..bdad0361 100644 --- a/README.rst +++ b/README.rst @@ -520,7 +520,15 @@ To catch this, mutmut detects non-Python files that changed since the last full run and warns you about them. If your project is a git repository and git is installed, mutmut uses git (a soft dependency no extra package is required) to find every changed non-Python file, respecting your `.gitignore`. Python files -are excluded because their changes are already tracked per function. +are excluded because their changes are already tracked: source files per +function, and test files as described below. + +Test files are tracked by their content. If you edit or delete a test file, +mutmut re-runs the mutants of the functions its tests covered, so removing an +assertion won't leave old ``killed`` results around. New tests also re-run the +``survived`` and ``no tests`` mutants of the functions they cover. Changes to a +``conftest.py`` are handled like a dependency file change (see +``on_dependency_change`` below), since they can affect any test. On a full run with git available, mutmut also records the content hashes of the tracked non-Python files. This means a later run in an environment without git diff --git a/src/mutmut/__main__.py b/src/mutmut/__main__.py index 0254aef6..1814b239 100644 --- a/src/mutmut/__main__.py +++ b/src/mutmut/__main__.py @@ -454,6 +454,95 @@ def compute_watched_file_hashes() -> dict[str, str]: return _hash_files(paths) +def _test_file_of(test_name: str) -> str: + # "tests/test_x.py::TestA::test_b[1]" -> "tests/test_x.py" + return test_name.split("::", 1)[0] + + +def _is_conftest(path: str) -> bool: + return Path(path).name == "conftest.py" + + +def compute_test_file_hashes(test_names: Iterable[str]) -> dict[str, str]: + """Hash the files these tests live in, plus any conftest.py above them.""" + files = {_test_file_of(name) for name in test_names} + conftests = { + str(parent / "conftest.py") for f in files for parent in Path(f).parents if (parent / "conftest.py").is_file() + } + return _hash_files(sorted(files | conftests)) + + +def _changed_test_files() -> set[str]: + """Test files (and conftest.py files) that were changed, added or deleted since the last run.""" + old = state().old_test_file_hashes + if not old: + return set() + new = _hash_files(old.keys()) + new.update(compute_test_file_hashes(collected_test_names())) + return {p for p in old.keys() | new.keys() if old.get(p) != new.get(p)} + + +def _forget_tests_in_changed_files() -> set[str]: + """Forget the stats of tests in changed files so they get collected again as new tests. + + Returns the functions those tests used to cover. conftest.py changes are left to + on_dependency_change since they can affect any test. + """ + changed_files = {p for p in _changed_test_files() if not _is_conftest(p)} + if not changed_files: + return set() + + tests_by_function = state().tests_by_mangled_function_name + known_tests = collected_test_names().union(*tests_by_function.values()) + stale_tests = {t for t in known_tests if _test_file_of(t) in changed_files} + covered = {f for f, tests in tests_by_function.items() if tests & stale_tests} + for f in covered: + tests_by_function[f] -= stale_tests + for t in stale_tests: + state().duration_by_test.pop(t, None) + + print(f" {len(changed_files)} test file(s) changed since the last run: {', '.join(sorted(changed_files))}") + return covered + + +def _reset_results_for_test_changes(edited_functions: set[str], recollected_tests: set[str]) -> None: + """Reset verdicts that new or edited tests may have changed. + + Functions an edited test used to cover get all their verdicts reset (a weaker test + can turn a kill into a survivor). Functions that new/edited tests now cover only get + survived and "no tests" reset, since extra coverage can't un-kill a mutant. + """ + newly_covered = { + f for f, tests in state().tests_by_mangled_function_name.items() if tests & recollected_tests + } - edited_functions + if not edited_functions and not newly_covered: + return + + def should_reset(key: str, exit_code: int) -> bool: + function = mangled_name_from_mutant_name(key) + if function in edited_functions: + return True + return function in newly_covered and status_by_exit_code[exit_code] in ("survived", "no tests") + + count = _reset_mutant_results(should_reset) + if count: + print(f" Re-testing {count} mutant(s) affected by the test changes") + + +def _refresh_test_file_baseline(*, full_run: bool) -> None: + """Save test file hashes for the next run. + + conftest.py hashes are only updated on a full run, same as the watched files, so the + warning keeps showing until the cache is rebuilt. + """ + new = compute_test_file_hashes(collected_test_names()) + old = state().old_test_file_hashes + if not full_run and old: + new = {p: h for p, h in new.items() if not _is_conftest(p)} + new.update({p: h for p, h in old.items() if _is_conftest(p)}) + state().test_file_hashes = new + + def _run_git(args: list[str]) -> str | None: """Run a git command at the project root. Returns stdout, or None on any failure (git not installed, not a repo, unknown ref, ...). Git is a soft dependency: this @@ -547,6 +636,8 @@ def _changed_dependency_files() -> set[str]: changed = _changed_hashed_files() else: changed = _changed_hashed_files() + # conftest.py can affect every test, so treat it like a dependency file + changed |= {p for p in _changed_test_files() if _is_conftest(p)} return {p for p in changed if not _is_excluded(p, cfg)} @@ -598,7 +689,7 @@ def _reset_mutant_results(should_reset: Callable[[str, int], bool]) -> int: def _report_watched_file_changes() -> bool: - """Surface non-Python files that changed since the last full run. + """Surface non-Python files (and conftest.py) that changed since the last full run. Returns True only when the configured policy is ``rerun`` and something changed, asking the caller to reset all results. Silent when there is no baseline yet. @@ -612,10 +703,10 @@ def _report_watched_file_changes() -> bool: return False listed = sorted(changed) if policy == "rerun": - print(f" {len(listed)} non-Python file(s) changed; rerunning all mutants: {', '.join(listed)}") + print(f" {len(listed)} dependency file(s) changed; rerunning all mutants: {', '.join(listed)}") return True # default: warn but keep the cache - print(f" Warning: {len(listed)} non-Python file(s) changed since the last full run: {', '.join(listed)}") + print(f" Warning: {len(listed)} dependency file(s) changed since the last full run: {', '.join(listed)}") print(" These cannot be tracked for behavioral changes, so cached results were kept.") print(' If the changes affect your tests, delete the mutants/ directory or set on_dependency_change = "rerun".') return False @@ -668,7 +759,8 @@ def collect_or_load_stats( if did_load and apply_config_invalidation: force_full = _apply_config_change_invalidation(mutants_caught_by_type_checker or {}) - if not did_load or force_full: + full_run = not did_load or force_full + if full_run: # A full run rebuilds the cache, so reset the change-detection baseline to "now". _refresh_change_detection_baseline() # Run full stats @@ -679,6 +771,9 @@ def collect_or_load_stats( _invalidate_stale_dependency_edges() save_stats() + # tests in edited files are forgotten here so they get picked up as new tests below + edited_functions = _forget_tests_in_changed_files() + # Run incremental stats with CatchOutput(spinner_title="Listing all tests") as output_catcher: set_mutant_under_test("list_all_tests") @@ -694,9 +789,14 @@ def collect_or_load_stats( new_tests = all_tests_result.new_tests() if new_tests: - print(f"Found {len(new_tests)} new tests, rerunning stats collection") + print(f"Found {len(new_tests)} new or changed tests, rerunning stats collection") run_stats_collection(runner, tests=new_tests) + _reset_results_for_test_changes(edited_functions, new_tests) + + _refresh_test_file_baseline(full_run=full_run) + save_stats() + def save_cicd_stats(source_file_mutation_data_by_path: dict[str, SourceFileMutationData]) -> None: s = calculate_summary_stats(source_file_mutation_data_by_path) diff --git a/src/mutmut/state.py b/src/mutmut/state.py index 7605b915..a27880a4 100644 --- a/src/mutmut/state.py +++ b/src/mutmut/state.py @@ -19,6 +19,9 @@ class MutmutState: watched_file_hashes: dict[str, str] = field(default_factory=dict) old_git_commit: str | None = None git_commit: str | None = None + # Hashes of test files (and conftest.py) from the last run, updated every run. + old_test_file_hashes: dict[str, str] = field(default_factory=dict) + test_file_hashes: dict[str, str] = field(default_factory=dict) # Migrated from module-level globals in mutmut/__init__.py. stats_time: float | None = None duration_by_test: defaultdict[str, float] = field(default_factory=lambda: defaultdict(float)) diff --git a/src/mutmut/stats.py b/src/mutmut/stats.py index 6277c667..89ef71e8 100644 --- a/src/mutmut/stats.py +++ b/src/mutmut/stats.py @@ -119,6 +119,8 @@ def load_stats() -> bool: state().old_config_fingerprint = data.pop("config_fingerprint", {}) state().old_watched_file_hashes = data.pop("watched_file_hashes", {}) state().old_git_commit = data.pop("git_commit", None) + state().old_test_file_hashes = data.pop("test_file_hashes", {}) + state().test_file_hashes = state().old_test_file_hashes # Preserve the loaded baseline; only a full run refreshes it. state().watched_file_hashes = state().old_watched_file_hashes state().git_commit = state().old_git_commit @@ -141,6 +143,7 @@ def save_stats() -> None: config_fingerprint=config().config_fingerprint(), watched_file_hashes=state().watched_file_hashes, git_commit=state().git_commit, + test_file_hashes=state().test_file_hashes, ), f, indent=4, diff --git a/tests/mutation/test_mutation.py b/tests/mutation/test_mutation.py index 48f7cf85..4404cad6 100644 --- a/tests/mutation/test_mutation.py +++ b/tests/mutation/test_mutation.py @@ -16,12 +16,17 @@ from mutmut.__main__ import CatchOutput from mutmut.__main__ import _apply_config_change_invalidation from mutmut.__main__ import _changed_dependency_files +from mutmut.__main__ import _changed_test_files from mutmut.__main__ import _cleanup_stale_stats +from mutmut.__main__ import _forget_tests_in_changed_files from mutmut.__main__ import _invalidate_stale_dependency_edges from mutmut.__main__ import _refresh_change_detection_baseline +from mutmut.__main__ import _refresh_test_file_baseline from mutmut.__main__ import _register_mutant_result from mutmut.__main__ import _report_watched_file_changes from mutmut.__main__ import _reset_mutant_results +from mutmut.__main__ import _reset_results_for_test_changes +from mutmut.__main__ import compute_test_file_hashes from mutmut.__main__ import compute_watched_file_hashes from mutmut.__main__ import git_changed_non_py_files from mutmut.__main__ import git_head @@ -1851,6 +1856,178 @@ def test_compute_watched_file_hashes_includes_user_globs(tmp_path, monkeypatch): assert "query.sql" in hashes +# --- test file change detection --- + + +def _write_tests(files): + for rel, content in files.items(): + path = pathlib.Path(rel) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content) + + +def test_compute_test_file_hashes_includes_conftests_above_test_files(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + _write_tests( + { + "conftest.py": "", + "tests/conftest.py": "", + "tests/unit/test_a.py": "def test_a(): pass", + "other/conftest.py": "", # not above any test, so not tracked + } + ) + + hashes = compute_test_file_hashes(["tests/unit/test_a.py::test_a", "tests/unit/test_a.py::TestX::test_b[1]"]) + + assert set(hashes) == {"conftest.py", "tests/conftest.py", "tests/unit/test_a.py"} + + +def test_compute_test_file_hashes_skips_ids_without_a_file(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + assert compute_test_file_hashes(["tests.test_a.test_a"]) == {} + + +def test_edited_test_file_forgets_its_tests_and_returns_covered_functions(tmp_path, monkeypatch): + reset_state() + monkeypatch.chdir(tmp_path) + _write_tests({"tests/test_a.py": "v1", "tests/test_b.py": "v1"}) + state().old_test_file_hashes = compute_test_file_hashes(["tests/test_a.py::t", "tests/test_b.py::t"]) + state().duration_by_test.update({"tests/test_a.py::t": 1.0, "tests/test_b.py::t": 1.0}) + state().tests_by_mangled_function_name["mymod.x_foo"] = {"tests/test_a.py::t"} + state().tests_by_mangled_function_name["mymod.x_bar"] = {"tests/test_a.py::t", "tests/test_b.py::t"} + state().tests_by_mangled_function_name["mymod.x_baz"] = {"tests/test_b.py::t"} + + pathlib.Path("tests/test_a.py").write_text("v2") + + assert _forget_tests_in_changed_files() == {"mymod.x_foo", "mymod.x_bar"} + # the edited test is forgotten, so the incremental stats collection treats it as new + assert set(state().duration_by_test) == {"tests/test_b.py::t"} + assert state().tests_by_mangled_function_name["mymod.x_foo"] == set() + assert state().tests_by_mangled_function_name["mymod.x_bar"] == {"tests/test_b.py::t"} + assert state().tests_by_mangled_function_name["mymod.x_baz"] == {"tests/test_b.py::t"} + reset_state() + + +def test_deleted_test_file_counts_as_changed(tmp_path, monkeypatch): + reset_state() + monkeypatch.chdir(tmp_path) + _write_tests({"tests/test_a.py": "v1"}) + state().old_test_file_hashes = compute_test_file_hashes(["tests/test_a.py::t"]) + state().duration_by_test["tests/test_a.py::t"] = 1.0 + state().tests_by_mangled_function_name["mymod.x_foo"] = {"tests/test_a.py::t"} + + pathlib.Path("tests/test_a.py").unlink() + + assert _forget_tests_in_changed_files() == {"mymod.x_foo"} + reset_state() + + +def test_unchanged_test_files_keep_their_stats(tmp_path, monkeypatch): + reset_state() + monkeypatch.chdir(tmp_path) + _write_tests({"tests/test_a.py": "v1"}) + state().old_test_file_hashes = compute_test_file_hashes(["tests/test_a.py::t"]) + state().duration_by_test["tests/test_a.py::t"] = 1.0 + state().tests_by_mangled_function_name["mymod.x_foo"] = {"tests/test_a.py::t"} + + assert _forget_tests_in_changed_files() == set() + assert set(state().duration_by_test) == {"tests/test_a.py::t"} + reset_state() + + +def test_absent_test_file_baseline_is_silent(tmp_path, monkeypatch): + # cache written by an older mutmut, without test file hashes + reset_state() + monkeypatch.chdir(tmp_path) + _write_tests({"tests/test_a.py": "v1"}) + state().duration_by_test["tests/test_a.py::t"] = 1.0 + + assert _changed_test_files() == set() + assert _forget_tests_in_changed_files() == set() + reset_state() + + +def test_conftest_changes_are_left_to_the_dependency_policy(tmp_path, monkeypatch, capsys): + reset_state() + monkeypatch.chdir(tmp_path) + monkeypatch.setattr(mutmut.__main__, "config", lambda: _config_for_invalidation()) + _write_tests({"tests/conftest.py": "v1", "tests/test_a.py": "v1"}) + state().old_test_file_hashes = compute_test_file_hashes(["tests/test_a.py::t"]) + state().duration_by_test["tests/test_a.py::t"] = 1.0 + + pathlib.Path("tests/conftest.py").write_text("v2") + + assert _forget_tests_in_changed_files() == set() + assert _report_watched_file_changes() is False # default policy: warn + assert "tests/conftest.py" in capsys.readouterr().out + + monkeypatch.setattr(mutmut.__main__, "config", lambda: _config_for_invalidation(on_dependency_change="rerun")) + assert _report_watched_file_changes() is True + reset_state() + + +def test_new_conftest_next_to_known_tests_is_detected(tmp_path, monkeypatch): + reset_state() + monkeypatch.chdir(tmp_path) + _write_tests({"tests/test_a.py": "v1"}) + state().old_test_file_hashes = compute_test_file_hashes(["tests/test_a.py::t"]) + state().duration_by_test["tests/test_a.py::t"] = 1.0 + + _write_tests({"tests/conftest.py": "import pytest"}) + + assert _changed_test_files() == {"tests/conftest.py"} + reset_state() + + +def test_test_changes_reset_only_affected_verdicts(tmp_path, monkeypatch): + reset_state() + monkeypatch.chdir(tmp_path) + monkeypatch.setattr(mutmut.__main__, "config", lambda: _config_for_invalidation()) + state().tests_by_mangled_function_name["mymod.x_newly_covered"] = {"tests/test_new.py::t"} + state().tests_by_mangled_function_name["mymod.x_unrelated"] = {"tests/test_other.py::t"} + _write_meta( + { + "mymod.x_edited__mutmut_1": 1, # killed by a test that was edited -> may now survive + "mymod.x_edited__mutmut_2": 0, + "mymod.x_newly_covered__mutmut_1": 0, # survived -> new test may kill it + "mymod.x_newly_covered__mutmut_2": 33, # no tests -> new test may kill it + "mymod.x_newly_covered__mutmut_3": 1, # killed by another test -> stays killed + "mymod.x_unrelated__mutmut_1": 0, + } + ) + + _reset_results_for_test_changes({"mymod.x_edited"}, {"tests/test_new.py::t"}) + + assert _load_results() == { + "mymod.x_edited__mutmut_1": None, + "mymod.x_edited__mutmut_2": None, + "mymod.x_newly_covered__mutmut_1": None, + "mymod.x_newly_covered__mutmut_2": None, + "mymod.x_newly_covered__mutmut_3": 1, + "mymod.x_unrelated__mutmut_1": 0, + } + reset_state() + + +def test_test_file_baseline_keeps_changed_conftest_until_full_run(tmp_path, monkeypatch): + reset_state() + monkeypatch.chdir(tmp_path) + _write_tests({"tests/conftest.py": "v1", "tests/test_a.py": "v1"}) + state().duration_by_test["tests/test_a.py::t"] = 1.0 + state().old_test_file_hashes = compute_test_file_hashes(["tests/test_a.py::t"]) + old = dict(state().old_test_file_hashes) + + _write_tests({"tests/conftest.py": "v2", "tests/test_a.py": "v2"}) + + _refresh_test_file_baseline(full_run=False) + assert state().test_file_hashes["tests/conftest.py"] == old["tests/conftest.py"] # warn keeps firing + assert state().test_file_hashes["tests/test_a.py"] != old["tests/test_a.py"] # edit already handled + + _refresh_test_file_baseline(full_run=True) + assert state().test_file_hashes == compute_test_file_hashes(["tests/test_a.py::t"]) + reset_state() + + # --- git-based change detection (soft dependency) --- _GIT = shutil.which("git")