From 0136cf555797f1c9552388c40207eb2f13af9535 Mon Sep 17 00:00:00 2001 From: "Robert C. Martin" Date: Tue, 24 Nov 2026 03:22:55 -0600 Subject: [PATCH] Skip test directories only at the project root or under src/test. Why: crapper.discover treats any test-named folder at any depth as a test path. That silently skipped production fixtures such as src/agnesse/slim/test/SymbolManagingTableTable.java, even when the file was named directly, because "test" appeared in the path. What: Mutator now walks the tree itself. A path relative to the project root is a test path when its first component is a TEST_DIRS name (test, tests, spec, specs, or __tests__), or when it sits under src/test or src/tests, the Maven and Gradle layout. SKIP_DIRS are still skipped at any depth. Filename-based test files are still detected by crapper.discover.is_test_file, applied to the filename so the any-depth directory check is not reused. crapper itself is unchanged. README and --help describe the new rule. Proof: 12 new tests in test_sources.py plus help assertions. 84 tests were green before; 96 pass now. crapper on the changed files: every new function is under 10 (iter_source_files 9.0, is_test_path 5.0, is_mutable_source 5.0); parse_args remains 30.2, the existing option-parser exception. dryer: no candidates. mutator on sources.py: 25 killed, 0 survived, 0 uncovered. Dry run against /tmp/agn at 58fd81c37: SymbolManagingTableTable.java is discovered along with 54 other files under src/agnesse/slim/test/; no files under test/ are. --- README.md | 4 +- src/mutator/cli.py | 115 +++++++++++++-------------- src/mutator/sources.py | 90 ++++++++++++++++++++++ tests/test_boundaries.py | 4 +- tests/test_cli.py | 3 + tests/test_sources.py | 162 +++++++++++++++++++++++++++++++++++++++ 6 files changed, 318 insertions(+), 60 deletions(-) create mode 100644 src/mutator/sources.py create mode 100644 tests/test_sources.py diff --git a/README.md b/README.md index 1152ce6..389457b 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,9 @@ A mutant is killed when the tests fail or time out. It survives when the tests s ./mutator ``` -The first run creates `.venv` and installs the tool. crapper has to be checked out next to this directory (`../crapper`), because that is where the namespace and function names come from. From a project root the tool walks the tree, skips `test`, `spec`, `vendor`, `node_modules`, and `target`, and writes `.metrics/mutate/.edn`. +The first run creates `.venv` and installs the tool. crapper has to be checked out next to this directory (`../crapper`), because that is where the namespace and function names come from. From a project root the tool walks the tree and writes `.metrics/mutate/.edn`. + +Directories such as `vendor`, `node_modules`, `target`, `build`, and `testdata` are skipped at any depth. A test directory (`test`, `tests`, `spec`, `specs`, or `__tests__`) is skipped when it is the first component of the path, and so is `src/test` and `src/tests`. A deeper directory with one of those names, such as `src/pkg/test`, is mutated. Files whose names mark them as tests, such as `test_foo.py`, `foo_test.go`, or `foo.test.ts`, are also skipped. The first run of a tree executes every covered mutant. Start with the file you are working on. diff --git a/src/mutator/cli.py b/src/mutator/cli.py index 9a556b5..5f574ed 100644 --- a/src/mutator/cli.py +++ b/src/mutator/cli.py @@ -13,42 +13,56 @@ from mutator.coverage import covered_lines from mutator.engine import mutate_file, restore_backups, scan_file from mutator.report import format_results, format_site_log from mutator.runner import CommandRunner +from mutator.sources import is_mutable_source, is_skipped_test, iter_source_files -def _skipped_directory_text() -> str: - """The directories the walker skips, named the same way in --help.""" +def _comma_and(names: set[str]) -> str: + ordered = sorted(names) + if len(ordered) == 1: + return ordered[0] + return ", ".join(ordered[:-1]) + ", and " + ordered[-1] - names = { - ".clj-kondo", - ".git", - ".hg", - ".idea", - ".metrics", - ".svn", - ".venv", - "__pycache__", - "__tests__", - "build", - "coverage", - "dist", - "node_modules", - "out", - "spec", - "specs", - "target", - "test", - "testdata", - "tests", - "venv", - "vendor", - } + +def _directory_text(attr: str, fallback: set[str]) -> str: + names = set(fallback) try: - crapper = ensure_crapper() - names = set(crapper.discover.SKIP_DIRS) | set(crapper.discover.TEST_DIRS) + names = set(getattr(ensure_crapper().discover, attr)) except ImportError: pass - ordered = sorted(names) - return ", ".join(ordered[:-1]) + ", and " + ordered[-1] + return _comma_and(names) + + +def _skip_directory_text() -> str: + """SKIP_DIRS, named the same way in --help.""" + + return _directory_text( + "SKIP_DIRS", + { + ".clj-kondo", + ".git", + ".hg", + ".idea", + ".metrics", + ".svn", + ".venv", + "__pycache__", + "build", + "coverage", + "dist", + "node_modules", + "out", + "target", + "testdata", + "venv", + "vendor", + }, + ) + + +def _test_directory_text() -> str: + """TEST_DIRS, named the same way in --help.""" + + return _directory_text("TEST_DIRS", {"test", "tests", "spec", "specs", "__tests__"}) HELP = f"""\ @@ -105,7 +119,11 @@ Arguments: path contains this text are mutated. With no paths, source files under the project root are mutated. Directories -named {_skipped_directory_text()} are skipped. +named {_skip_directory_text()} are skipped at any depth. A test directory +({_test_directory_text()}) is skipped when it is the first component of the +path, and so is src/test and src/tests. A deeper directory with one of those +names, such as src/pkg/test, is mutated. Files whose names mark them as tests +are also skipped. The default, once a snapshot exists, reruns survivors and sites in functions whose text changed. Killed mutants in unchanged functions are kept. @@ -359,37 +377,19 @@ def _positionals(root: Path, args: list[str]) -> tuple[list[Path], list[str]]: def _changed_sources(root: Path, crapper) -> list[Path]: - skip = set(crapper.discover.SKIP_DIRS) | set(crapper.discover.TEST_DIRS) - root_resolved = root.resolve() - files = [] - for path in _changed_files(root): - relative = path.relative_to(root_resolved) - if not skip.isdisjoint(relative.parts): - continue - if crapper.discover.language_of(path) is None: - continue - if crapper.discover.is_test_file(path): - continue - files.append(path) - return files + return [path for path in _changed_files(root) if is_mutable_source(path, root, crapper)] -def _is_source(path: Path, crapper) -> bool: - if crapper.discover.language_of(path) is None: - return False - return not crapper.discover.is_test_file(path) - - -def _explicit_sources(existing: list[Path], crapper) -> list[Path]: +def _explicit_sources(existing: list[Path], root: Path, crapper) -> list[Path]: files = [] for path in existing: if path.is_dir(): - files.extend(crapper.discover.iter_source_files([path])) + files.extend(iter_source_files([path], root, crapper)) continue - if _is_source(path, crapper): + if is_mutable_source(path, root, crapper): files.append(path) continue - if crapper.discover.is_test_file(path): + if is_skipped_test(path, root, crapper): print(f"Skipping test file {path}", file=sys.stderr) return files @@ -398,10 +398,11 @@ def _choose_files(options: Options, root: Path, existing: list[Path], crapper) - if options.changed: return _changed_sources(root, crapper) if options.source_roots: - return crapper.discover.iter_source_files([(root / path).resolve() for path in options.source_roots]) + starts = [(root / path).resolve() for path in options.source_roots] + return iter_source_files(starts, root, crapper) if existing: - return _explicit_sources(existing, crapper) - return crapper.discover.iter_source_files([root]) + return _explicit_sources(existing, root, crapper) + return iter_source_files([root], root, crapper) def _matching(files: list[Path], filters: list[str]) -> list[Path]: diff --git a/src/mutator/sources.py b/src/mutator/sources.py new file mode 100644 index 0000000..a11edd7 --- /dev/null +++ b/src/mutator/sources.py @@ -0,0 +1,90 @@ +"""Choose the source files a mutation run will consider. + +crapper.discover treats any TEST_DIRS name at any depth as a test path, which +skips production fixtures such as src/agnesse/slim/test/. Mutator therefore +walks the tree itself. + +A path relative to the project root is a test path when its first component is +a TEST_DIRS name (test, tests, spec, specs, or __tests__), or when it sits +under src/test or src/tests, the Maven and Gradle test layout. SKIP_DIRS are +skipped at any depth. Filename-based test files are still detected by +crapper.discover.is_test_file, applied to the filename so the any-depth +directory check is not reused. +""" + +from __future__ import annotations + +import os +from pathlib import Path + +SRC_TEST_DIRS = frozenset({"test", "tests"}) + + +def is_test_path(relative: Path, test_dirs: set[str]) -> bool: + parts = relative.parts + if not parts: + return False + if parts[0] in test_dirs: + return True + return len(parts) >= 2 and parts[0] == "src" and parts[1] in SRC_TEST_DIRS + + +def _relative_to(path: Path, root: Path) -> Path | None: + try: + return path.resolve().relative_to(root.resolve()) + except ValueError: + return None + + +def is_mutable_source(path: Path, root: Path, crapper) -> bool: + if crapper.discover.language_of(path) is None: + return False + relative = _relative_to(path, root) + if relative is None: + return False + if not set(crapper.discover.SKIP_DIRS).isdisjoint(relative.parts): + return False + if is_test_path(relative, set(crapper.discover.TEST_DIRS)): + return False + return not crapper.discover.is_test_file(path.name) + + +def is_skipped_test(path: Path, root: Path, crapper) -> bool: + if crapper.discover.language_of(path) is None: + return False + relative = _relative_to(path, root) + if relative is not None and is_test_path(relative, set(crapper.discover.TEST_DIRS)): + return True + return crapper.discover.is_test_file(path.name) + + +def _enter(current: Path, name: str, root: Path, skip_dirs: set[str], test_dirs: set[str]) -> bool: + if name in skip_dirs: + return False + relative = _relative_to(current / name, root) + return relative is None or not is_test_path(relative, test_dirs) + + +def iter_source_files(roots: list[Path], project_root: Path, crapper) -> list[Path]: + skip_dirs = set(crapper.discover.SKIP_DIRS) + test_dirs = set(crapper.discover.TEST_DIRS) + project_root = project_root.resolve() + files: set[Path] = set() + for start in roots: + start = start.resolve() + if start.is_file(): + if is_mutable_source(start, project_root, crapper): + files.add(start) + continue + if not start.exists(): + continue + for dirpath, dirnames, filenames in os.walk(start): + current = Path(dirpath) + dirnames[:] = [ + name for name in dirnames if _enter(current, name, project_root, skip_dirs, test_dirs) + ] + for name in filenames: + path = (current / name).resolve() + if is_mutable_source(path, project_root, crapper): + files.add(path) + return sorted(files, key=lambda path: path.as_posix()) diff --git a/tests/test_boundaries.py b/tests/test_boundaries.py index 701cce9..61edc55 100644 --- a/tests/test_boundaries.py +++ b/tests/test_boundaries.py @@ -16,7 +16,6 @@ import pytest from mutator.cli import ( GitStatusError, _changed_files, - _is_source, _prepare_coverage, _take, parse_args, @@ -25,6 +24,7 @@ from mutator.cli import ( ) from mutator.coverage import _candidates, _jacoco_index, covered_lines from mutator.crapper_link import ensure_crapper +from mutator.sources import is_mutable_source from mutator.edn import loads from mutator.engine import ( _backup, @@ -495,7 +495,7 @@ def test_selection_joins_the_root_and_skips_unknown_files(tmp_path, capsys): note = tmp_path / "note.txt" note.write_text("hello\n", encoding="utf-8") crapper = ensure_crapper() - assert _is_source(note, crapper) is False + assert is_mutable_source(note, tmp_path, crapper) is False options = parse_args(["--root", str(tmp_path), "src/demo.py"]) assert select_files(options) == [path.resolve()] diff --git a/tests/test_cli.py b/tests/test_cli.py index aaa08ad..7a26975 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -44,6 +44,9 @@ def test_help_and_conflicting_flags(): assert "uml-viewer" in help_options.message assert "__pycache__" in help_options.message assert "testdata" in help_options.message + assert "skipped at any depth" in help_options.message + assert "src/test" in help_options.message + assert "first component" in help_options.message conflict = parse_args(["--mutate-all", "--since-last-run", "src/demo.py"]) assert conflict.exit_code == 1 assert run(["--help"]) == 0 diff --git a/tests/test_sources.py b/tests/test_sources.py new file mode 100644 index 0000000..9da1818 --- /dev/null +++ b/tests/test_sources.py @@ -0,0 +1,162 @@ +"""Mutator skips root test trees and src/test, not a deeper test directory.""" + +import subprocess +from pathlib import Path + +from mutator.cli import _comma_and, parse_args, select_files +from mutator.crapper_link import ensure_crapper +from mutator.sources import is_mutable_source, is_skipped_test, is_test_path, iter_source_files + + +SOURCE = "def place(x):\n return x > 0\n" +JAVA = "class Foo { boolean ok() { return true; } }\n" + + +def _write(root: Path, relative: str, body: str | None = None) -> Path: + path = root / relative + path.parent.mkdir(parents=True, exist_ok=True) + if body is None: + body = JAVA if path.suffix == ".java" else SOURCE + path.write_text(body, encoding="utf-8") + return path.resolve() + + +def _chosen(root: Path, *args: str) -> set[str]: + files = select_files(parse_args(["--root", str(root), *args])) + return {path.relative_to(root).as_posix() for path in files} + + +CASES = { + "test/Foo.java": False, + "tests/foo.py": False, + "spec/foo.py": False, + "specs/foo.py": False, + "__tests__/foo.py": False, + "src/test/java/com/example/Foo.java": False, + "src/tests/foo.py": False, + "src/agnesse/slim/test/SymbolManagingTableTable.java": True, + "src/foo/tests/bar.py": True, + "src/pkg/spec/foo.py": True, + "src/demo.py": True, + "lib/test/deep.py": True, + "src/pkg/node_modules/foo.py": False, + "target/generated/Foo.java": False, + "build/out.py": False, + "src/pkg/foo_test.go": False, + "src/pkg/test_foo.py": False, + "src/pkg/foo_test.py": False, + "src/pkg/foo.test.ts": False, + "src/pkg/foo.spec.ts": False, + "src/pkg/conftest.py": False, +} + + +def _tree(root: Path) -> None: + for relative in CASES: + _write(root, relative) + + +def test_walk_skips_root_and_src_test_trees_but_mutates_a_deeper_test_directory(tmp_path): + _tree(tmp_path) + assert _chosen(tmp_path) == {relative for relative, keep in CASES.items() if keep} + + +def test_changed_files_use_the_same_test_path_rule(tmp_path): + _tree(tmp_path) + subprocess.run(["git", "init"], cwd=tmp_path, check=True, capture_output=True) + subprocess.run(["git", "add", "-A"], cwd=tmp_path, check=True, capture_output=True) + assert _chosen(tmp_path, "--changed") == {relative for relative, keep in CASES.items() if keep} + + +def test_an_explicit_deep_test_file_is_mutated_and_a_root_test_file_is_skipped(tmp_path, capsys): + fixture = _write(tmp_path, "src/agnesse/slim/test/SymbolManagingTableTable.java") + root_test = _write(tmp_path, "test/Foo.java") + maven = _write(tmp_path, "src/test/java/com/example/Foo.java") + chosen = select_files( + parse_args( + [ + "--root", + str(tmp_path), + str(fixture), + str(root_test), + str(maven), + ] + ) + ) + captured = capsys.readouterr() + assert chosen == [fixture] + assert "Skipping test file" in captured.err + assert "test/Foo.java" in captured.err + assert "src/test/java" in captured.err + + +def test_a_deep_test_directory_argument_is_walked_and_a_root_test_directory_is_not(tmp_path): + fixture = _write(tmp_path, "src/agnesse/slim/test/SymbolManagingTableTable.java") + sibling = _write(tmp_path, "src/agnesse/slim/test/Other.java") + _write(tmp_path, "test/Foo.java") + _write(tmp_path, "src/demo.py") + deep = _chosen(tmp_path, "src/agnesse/slim/test") + assert deep == { + "src/agnesse/slim/test/SymbolManagingTableTable.java", + "src/agnesse/slim/test/Other.java", + } + assert fixture.relative_to(tmp_path).as_posix() in deep + assert sibling.relative_to(tmp_path).as_posix() in deep + assert _chosen(tmp_path, "test") == set() + + +def test_source_root_walks_a_deep_test_directory(tmp_path): + _write(tmp_path, "src/agnesse/slim/test/SymbolManagingTableTable.java") + _write(tmp_path, "test/Foo.java") + _write(tmp_path, "src/demo.py") + assert _chosen(tmp_path, "--source-root", "src/agnesse/slim") == { + "src/agnesse/slim/test/SymbolManagingTableTable.java" + } + + +def test_an_empty_relative_path_is_not_a_test_path(): + assert is_test_path(Path(""), {"test"}) is False + + +def test_a_path_outside_the_project_is_not_mutable(tmp_path): + root = tmp_path / "proj" + root.mkdir() + outside = _write(tmp_path, "outside.py") + crapper = ensure_crapper() + assert is_mutable_source(outside, root, crapper) is False + assert is_skipped_test(tmp_path / "note.txt", root, crapper) is False + + +def test_iter_source_files_accepts_a_file_and_ignores_a_missing_path(tmp_path): + kept = _write(tmp_path, "src/demo.py") + crapper = ensure_crapper() + found = iter_source_files([kept, tmp_path / "missing"], tmp_path, crapper) + assert found == [kept] + + +def test_comma_and_names_a_single_item(): + assert _comma_and({"only"}) == "only" + + +def test_src_test_itself_is_a_test_path(): + test_dirs = {"test", "tests"} + assert is_test_path(Path("src/test"), test_dirs) is True + assert is_test_path(Path("src/tests"), test_dirs) is True + assert is_test_path(Path("src"), test_dirs) is False + + +def test_an_explicit_skip_dir_file_is_not_reported_as_a_test(tmp_path, capsys): + build = _write(tmp_path, "target/generated/Foo.java") + chosen = select_files(parse_args(["--root", str(tmp_path), str(build)])) + assert chosen == [] + assert "Skipping test file" not in capsys.readouterr().err + + +def test_a_skip_directory_is_not_entered(tmp_path): + from mutator.sources import _enter + + assert _enter(tmp_path, "target", tmp_path, {"target"}, {"test"}) is False + assert _enter(tmp_path, "src", tmp_path, {"target"}, {"test"}) is True + (tmp_path / "src").mkdir() + assert _enter(tmp_path / "src", "test", tmp_path, {"target"}, {"test", "tests"}) is False + assert _enter(tmp_path / "src", "main", tmp_path, {"target"}, {"test", "tests"}) is True