From ce3197f72bec9a1b2cb3ec1d7b216f5689e6c34e Mon Sep 17 00:00:00 2001 From: Dan Neal Date: Thu, 19 Nov 2026 19:29:41 -0800 Subject: [PATCH] Add configurable mutants_dir option Hardcoding ./mutants/ pollutes project roots, lets pytest accidentally collect generated files, and blocks running against read-only source directories or out-of-tree caches. Add a mutants_dir option in pyproject.toml and setup.cfg (defaulting to "mutants") and default log_file_path under it when unset. Route generation, execution, coverage, cache, and CLI paths through get_mutants_dir(), which returns the loaded config value when available and otherwise reads mutants_dir directly without requiring source_paths resolution. Key edge cases handled: - Resolve paths consistently for coverage.py and pass source when mutants_dir lives outside the project root (including ../ and symlinked paths). - Exclude in-repo mutants_dir paths from git dependency-change detection so unignored caches do not invalidate incremental runs. - Reject empty, non-string, project-root, ancestor, or source_paths/also_copy-overlapping mutants_dir values. --- ARCHITECTURE.rst | 2 +- README.rst | 27 +++- src/mutmut/__main__.py | 44 +++++-- src/mutmut/code_coverage.py | 24 ++-- src/mutmut/configuration.py | 55 ++++++-- src/mutmut/mutation/data.py | 9 +- src/mutmut/mutation/diff_apply.py | 3 +- src/mutmut/mutation/file_mutation.py | 3 +- src/mutmut/runners/harness.py | 16 ++- src/mutmut/stats.py | 5 +- src/mutmut/utils/file_utils.py | 12 +- tests/test_configuration.py | 89 +++++++++++++ tests/test_mutants_dir.py | 182 +++++++++++++++++++++++++++ 13 files changed, 423 insertions(+), 48 deletions(-) create mode 100644 tests/test_mutants_dir.py diff --git a/ARCHITECTURE.rst b/ARCHITECTURE.rst index 73f11574..f2514a38 100644 --- a/ARCHITECTURE.rst +++ b/ARCHITECTURE.rst @@ -9,7 +9,7 @@ Phases of ``mutmut run`` Generating mutants ^^^^^^^^^^^^^^^^^^ -This phase creates a ``./mutants/`` directory, which will be used by all following phases. +This phase creates the mutants directory (``./mutants/`` by default, configurable via ``mutants_dir``), which will be used by all following phases. We start by copying ``source_paths`` to ``mutants/`` and then mutate the ``*.py`` files in there. Finally, we also copy ``also_copy`` paths to ``mutants/``, including the (guessed) test directories and some project files. diff --git a/README.rst b/README.rst index 9e0f542a..c089d4bf 100644 --- a/README.rst +++ b/README.rst @@ -102,6 +102,26 @@ If you use `pyproject.toml`, you must specify the paths as array in a `tool.mutm See below for more options for configuring mutmut. +Custom mutants directory +~~~~~~~~~~~~~~~~~~~~~~~~ + +By default, mutmut writes mutated files, metadata, stats, and debug logs into ``mutants/`` in the current working directory. You can point it to a different relative or absolute directory with ``mutants_dir``: + +.. code-block:: toml + + # pyproject.toml + [tool.mutmut] + mutants_dir = ".mutmut-cache" + +.. code-block:: ini + + # setup.cfg + [mutmut] + mutants_dir = /tmp/my-project-mutants + +When ``log_file_path`` is not set explicitly, it defaults to ``/mutmut-debug.log``. + + "also copy" files ~~~~~~~~~~~~~~~~~ @@ -617,9 +637,10 @@ This section describes how to work with mutmut to enhance your test suite. 3. Find a mutant you want to work on and write a test to try to kill it. 4. Press `r` to rerun the mutant and see if you successfully managed to kill it. -Mutmut keeps the data of what it has done and the mutants in the `mutants/` -directory. If you want to make sure you run a full mutmut run you can delete -this directory to start from scratch. +Mutmut keeps the data of what it has done and the mutants in the ``mutants/`` +directory (or the directory configured via ``mutants_dir``). If you want to +make sure you run a full mutmut run you can delete this directory to start +from scratch. Mutation score badges diff --git a/src/mutmut/__main__.py b/src/mutmut/__main__.py index 0254aef6..8c7b3fd6 100644 --- a/src/mutmut/__main__.py +++ b/src/mutmut/__main__.py @@ -47,6 +47,7 @@ from mutmut.code_coverage import get_excluded_lines_for_file from mutmut.configuration import Config from mutmut.configuration import config +from mutmut.configuration import get_mutants_dir from mutmut.core import MutmutProgrammaticFailException from mutmut.mutation.data import MutantLineSpans from mutmut.mutation.data import SourceFileMutationData @@ -133,7 +134,7 @@ def create_mutants(max_children: int) -> MutantGenerationStats: def create_file_mutants(path: Path) -> FileMutationResult: try: print(path) - output_path = Path("mutants") / path + output_path = get_mutants_dir() / path makedirs(output_path.parent, exist_ok=True) if config().should_mutate(path): @@ -517,11 +518,24 @@ def _changed_hashed_files(restrict_to: list[str] | None = None) -> set[str]: return changed +def _is_in_mutants_dir(path: str, mutants_dir: Path) -> bool: + cwd = Path.cwd().resolve() + resolved_mutants = (cwd / mutants_dir).resolve() + if not resolved_mutants.is_relative_to(cwd): + return False + rel_mutants = resolved_mutants.relative_to(cwd).as_posix() + rel_path = Path(path).as_posix() + return rel_path == rel_mutants or rel_path.startswith(f"{rel_mutants}/") + + def _is_excluded(path: str, config: Config) -> bool: """Whether ``path`` should be dropped from change reporting as noise. - Files explicitly registered in ``cache_invalidation_files`` are never excluded. + Generated files under ``mutants_dir`` are always excluded. Files explicitly + registered in ``cache_invalidation_files`` are otherwise never excluded. """ + if _is_in_mutants_dir(path, config.mutants_dir): + return True if any(fnmatch.fnmatch(path, pat) for pat in config.cache_invalidation_files): return False patterns = list(_DEFAULT_INVALIDATION_EXCLUDE) + list(config.cache_invalidation_exclude) @@ -581,7 +595,7 @@ def _reset_mutant_results(should_reset: Callable[[str, int], bool]) -> int: """ count = 0 for path in walk_mutatable_files(): - meta_path = Path("mutants") / (str(path) + ".meta") + meta_path = get_mutants_dir() / (str(path) + ".meta") if not meta_path.exists(): continue m = SourceFileMutationData(path=path) @@ -617,7 +631,9 @@ def _report_watched_file_changes() -> bool: # default: warn but keep the cache print(f" Warning: {len(listed)} non-Python 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".') + print( + f' If the changes affect your tests, delete the {get_mutants_dir()}/ directory or set on_dependency_change = "rerun".' + ) return False @@ -700,7 +716,7 @@ def collect_or_load_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) - with open("mutants/mutmut-cicd-stats.json", "w") as f: + with open(get_mutants_dir() / "mutmut-cicd-stats.json", "w") as f: json.dump( dict( killed=s.killed, @@ -732,7 +748,7 @@ def export_cicd_stats() -> None: source_file_mutation_data_by_path: dict[str, SourceFileMutationData] = {} for path in walk_mutatable_files(): - meta_path = Path("mutants") / (str(path) + ".meta") + meta_path = get_mutants_dir() / (str(path) + ".meta") if not meta_path.exists(): continue @@ -748,20 +764,24 @@ def export_cicd_stats() -> None: return save_cicd_stats(source_file_mutation_data_by_path) - print("Saved CI/CD stats to mutants/mutmut-cicd-stats.json") + print(f"Saved CI/CD stats to {get_mutants_dir() / 'mutmut-cicd-stats.json'}") @cli.command() @click.option( "--input", "input_path", - default="mutants/mutmut-cicd-stats.json", - show_default=True, + default=None, type=click.Path(exists=True, dir_okay=False, path_type=Path), + help="Path to mutmut-cicd-stats.json (defaults to /mutmut-cicd-stats.json).", ) @click.option("--output", required=True, type=click.Path(dir_okay=False, path_type=Path)) @click.option("--label", default="mutation", show_default=True) -def badge(input_path: Path, output: Path, label: str) -> None: +def badge(input_path: Path | None, output: Path, label: str) -> None: + if input_path is None: + input_path = get_mutants_dir() / "mutmut-cicd-stats.json" + if not input_path.is_file(): + raise click.ClickException(f"{input_path} does not exist") try: with input_path.open() as f: stats = json.load(f) @@ -951,7 +971,9 @@ def _run(mutant_names: tuple[str, ...] | list[str], max_children: int | None) -> max_children = os.cpu_count() or 4 start = datetime.now() - makedirs(Path("mutants"), exist_ok=True) + # Validate full config before creating the output directory. + config() + makedirs(get_mutants_dir(), exist_ok=True) with CatchOutput(spinner_title="Generating mutants"): copy_src_dir() copy_also_copy_files() diff --git a/src/mutmut/code_coverage.py b/src/mutmut/code_coverage.py index 235e5536..25af6561 100644 --- a/src/mutmut/code_coverage.py +++ b/src/mutmut/code_coverage.py @@ -10,13 +10,15 @@ from coverage import CoverageData from coverage.exceptions import CoverageException +from mutmut.configuration import get_mutants_dir + if TYPE_CHECKING: from mutmut.runners.harness import TestRunner @dataclass class CoverageInfo: - """What coverage.py knows about the source files, keyed by absolute path in `mutants/`. + """What coverage.py knows about the source files, keyed by resolved path in the mutants directory. `covered_lines` are the lines that actually executed. `excluded_lines` are the lines coverage.py was told to ignore (`# pragma: no cover`, `exclude_lines`, `exclude_also`). @@ -37,7 +39,7 @@ def get_covered_lines_for_file(filename: str, covered_lines: dict[str, set[int]] if covered_lines is None or filename is None: return None - abs_filename = str((Path("mutants") / filename).absolute()) + abs_filename = str((get_mutants_dir() / filename).resolve()) lines: set[int] = set() if abs_filename in covered_lines: lines = set(covered_lines[abs_filename]) @@ -52,7 +54,7 @@ def get_excluded_lines_for_file(filename: str, excluded_lines: dict[str, set[int if excluded_lines is None or filename is None: return set() - abs_filename = str((Path("mutants") / filename).absolute()) + abs_filename = str((get_mutants_dir() / filename).resolve()) return set(excluded_lines.get(abs_filename, ())) @@ -72,10 +74,16 @@ def gather_coverage(runner: TestRunner, source_files: Iterable[Path]) -> Coverag def _gather_coverage_in_this_process(runner: TestRunner, source_files: Iterable[Path]) -> CoverageInfo: """The actual measurement. Pollutes the calling process; see gather_coverage.""" - mutants_path = Path("mutants") - - # Run the tests and gather coverage - cov = coverage.Coverage(data_file=None) + # Run the tests and gather coverage. When mutants_dir lives outside the + # project root, coverage.py's default cwd-based filter would ignore it + # unless we explicitly point `source` at the mutants directory. + resolved_mutants = get_mutants_dir().resolve() + source = ( + [str(resolved_mutants)] + if resolved_mutants.is_dir() and not resolved_mutants.is_relative_to(Path.cwd().resolve()) + else None + ) + cov = coverage.Coverage(data_file=None, source=source) runner.collect_main_test_coverage(cov) # Build mapping of filenames to covered lines @@ -85,7 +93,7 @@ def _gather_coverage_in_this_process(runner: TestRunner, source_files: Iterable[ coverage_data: CoverageData = cov.get_data() for filename in source_files: - abs_filename = str((mutants_path / filename).absolute()) + abs_filename = str((resolved_mutants / filename).resolve()) info.covered_lines[abs_filename] = set(coverage_data.lines(abs_filename) or []) info.excluded_lines[abs_filename] = _excluded_lines(cov, abs_filename) diff --git a/src/mutmut/configuration.py b/src/mutmut/configuration.py index a1b7650c..b8058a95 100644 --- a/src/mutmut/configuration.py +++ b/src/mutmut/configuration.py @@ -135,6 +135,28 @@ def _guess_source_paths() -> list[str]: ) +def _parse_mutants_dir(raw: Any) -> Path: + if not isinstance(raw, str) or not raw.strip(): + raise ValueError("Invalid mutants_dir value: must be a non-empty path.") + mutants_dir = Path(raw) + cwd = Path.cwd().resolve() + resolved = (cwd / mutants_dir).resolve() + if cwd.is_relative_to(resolved): + raise ValueError("Invalid mutants_dir value: must not be the project root or an ancestor directory.") + return mutants_dir + + +def _validate_mutants_dir_overlap(mutants_dir: Path, source_paths: list[Path], also_copy: list[Path]) -> None: + cwd = Path.cwd().resolve() + resolved_mutants = (cwd / mutants_dir).resolve() + for entry in [*source_paths, *also_copy]: + resolved_entry = (cwd / entry).resolve() + if resolved_entry == cwd: + continue + if resolved_mutants.is_relative_to(resolved_entry) or resolved_entry.is_relative_to(resolved_mutants): + raise ValueError(f"Invalid mutants_dir value: {mutants_dir} must not overlap configured path {entry}.") + + def _load_config() -> Config: s = _config_reader() @@ -144,8 +166,11 @@ def _load_config() -> Config: source_paths = [Path(path) for path in s("source_paths", [])] source_paths = source_paths or paths_to_mutate or [Path(path) for path in _guess_source_paths()] + mutants_dir = _parse_mutants_dir(s("mutants_dir", "mutants")) + resolved_mutants = (Path.cwd().resolve(strict=True) / mutants_dir).resolve() + # We resolve at startup, s.t. we are still in the current working directory (and no tests modified the directory) - resolved_mutated_source_paths = [Path.cwd().resolve(strict=True) / "mutants" / p for p in source_paths] + resolved_mutated_source_paths = [(resolved_mutants / p).resolve() for p in source_paths] tests_dir = s("tests_dir", []) if tests_dir: @@ -177,11 +202,8 @@ def _load_config() -> Config: valid = [e.value for e in ForkServerWarmup] raise ValueError(f"Invalid forkserver_warmup value: {warmup_str!r}. Expected one of: {valid}") from None - return Config( - only_mutate=only_mutate, - do_not_mutate=do_not_mutate, - do_not_mutate_patterns=s("do_not_mutate_patterns", []), - also_copy=[Path(y) for y in s("also_copy", [])] + also_copy = ( + [Path(y) for y in s("also_copy", [])] + [ Path("tests/"), Path("test/"), @@ -192,7 +214,15 @@ def _load_config() -> Config: Path("Pipfile.lock"), Path("pdm.lock"), ] - + list(Path(".").glob("test*.py")), + + list(Path(".").glob("test*.py")) + ) + _validate_mutants_dir_overlap(mutants_dir, source_paths, also_copy) + + return Config( + only_mutate=only_mutate, + do_not_mutate=do_not_mutate, + do_not_mutate_patterns=s("do_not_mutate_patterns", []), + also_copy=also_copy, max_stack_depth=s("max_stack_depth", -1), debug=s("debug", False), mutate_only_covered_lines=s("mutate_only_covered_lines", False), @@ -217,7 +247,8 @@ def _load_config() -> Config: max_forkserver_restarts=s("max_forkserver_restarts", 3), preload_modules_file=s("preload_modules_file", None), log_to_file=s("log_to_file", False), - log_file_path=s("log_file_path", "mutants/mutmut-debug.log"), + log_file_path=s("log_file_path", str(mutants_dir / "mutmut-debug.log")), + mutants_dir=mutants_dir, ) @@ -253,6 +284,7 @@ class Config: preload_modules_file: str | None log_to_file: bool log_file_path: str + mutants_dir: Path = Path("mutants") def config_fingerprint(self) -> dict[str, str]: """Hash the config fields that can change cached mutant *results*, grouped so the @@ -308,6 +340,13 @@ def config() -> Config: return _config +def get_mutants_dir() -> Path: + """Return the configured mutants directory without requiring source_paths to resolve.""" + if _config is not None: + return _config.mutants_dir + return _parse_mutants_dir(_config_reader()("mutants_dir", "mutants")) + + def reset_config() -> None: global _config _config = None diff --git a/src/mutmut/mutation/data.py b/src/mutmut/mutation/data.py index bb3ab0b3..d2820658 100644 --- a/src/mutmut/mutation/data.py +++ b/src/mutmut/mutation/data.py @@ -5,6 +5,8 @@ from itertools import islice from pathlib import Path +from mutmut.configuration import get_mutants_dir + @dataclass(frozen=True) class LineSpan: @@ -26,9 +28,10 @@ class MutantLineSpans: format_version = 1 def __init__(self, *, path: Path | str, span_by_function_name: Mapping[str, LineSpan]) -> None: + base = get_mutants_dir() self.path = path - self.mutants_path = Path("mutants") / str(path) - self.index_path = Path("mutants") / (str(path) + ".spans") + self.mutants_path = base / str(path) + self.index_path = base / (str(path) + ".spans") self.span_by_function_name = span_by_function_name @classmethod @@ -98,7 +101,7 @@ class SourceFileMutationData: def __init__(self, *, path: Path | str) -> None: self.estimated_time_of_tests_by_mutant: dict[str, float] = {} self.path = path - self.meta_path = Path("mutants") / (str(path) + ".meta") + self.meta_path = get_mutants_dir() / (str(path) + ".meta") self.exit_code_by_key: dict[str, int | None] = {} self.hash_by_function_name: dict[str, str] = {} self.durations_by_key: dict[str, float] = {} diff --git a/src/mutmut/mutation/diff_apply.py b/src/mutmut/mutation/diff_apply.py index 8978c4be..037cd1f2 100644 --- a/src/mutmut/mutation/diff_apply.py +++ b/src/mutmut/mutation/diff_apply.py @@ -7,6 +7,7 @@ import libcst as cst +from mutmut.configuration import get_mutants_dir from mutmut.mutation.data import MutantLineSpans from mutmut.mutation.data import SourceFileMutationData from mutmut.utils.file_utils import walk_mutatable_files @@ -15,7 +16,7 @@ def read_mutants_module(path: Path | str) -> cst.Module: - with open(Path("mutants") / path) as f: + with open(get_mutants_dir() / path) as f: return cst.parse_module(f.read()) diff --git a/src/mutmut/mutation/file_mutation.py b/src/mutmut/mutation/file_mutation.py index e9297c52..91745775 100644 --- a/src/mutmut/mutation/file_mutation.py +++ b/src/mutmut/mutation/file_mutation.py @@ -20,6 +20,7 @@ from libcst.metadata import PositionProvider from mutmut.configuration import config +from mutmut.configuration import get_mutants_dir from mutmut.mutation.data import LineSpan from mutmut.mutation.mutators import OPERATORS_TYPE from mutmut.mutation.mutators import mutation_operators @@ -671,7 +672,7 @@ def group_by_path(errors: list[TypeCheckingError]) -> dict[Path, list[TypeChecki def filter_mutants_with_type_checker() -> dict[str, FailedTypeCheckMutant]: - with change_cwd(Path("mutants")): + with change_cwd(get_mutants_dir()): errors = run_type_checker(config().type_check_command) errors_by_path = group_by_path(errors) diff --git a/src/mutmut/runners/harness.py b/src/mutmut/runners/harness.py index ed4bc9db..45ae951b 100644 --- a/src/mutmut/runners/harness.py +++ b/src/mutmut/runners/harness.py @@ -8,6 +8,7 @@ from mutmut.configuration import ForkServerWarmup from mutmut.configuration import config +from mutmut.configuration import get_mutants_dir from mutmut.state import state from mutmut.stats import save_stats from mutmut.utils.file_utils import change_cwd @@ -104,7 +105,7 @@ def warm_up(self) -> None: warmup = config().forkserver_warmup if warmup == ForkServerWarmup.COLLECT: - with change_cwd("mutants"): + with change_cwd(get_mutants_dir()): self.execute_pytest(["--collect-only", "-qqq"] + self._pytest_add_cli_args_test_selection) elif warmup == ForkServerWarmup.IMPORT: preload_file = config().preload_modules_file @@ -145,6 +146,9 @@ def _pytest_args_regular_run(self, tests: Iterable[str]) -> list[str]: return pytest_args def run_stats(self, *, tests: Iterable[str]) -> int: + mutants_dir = get_mutants_dir() + prefix = f"{mutants_dir.as_posix().rstrip('/')}/" + class StatsCollector: # noinspection PyMethodMayBeStatic def pytest_runtest_logstart(self, nodeid: str, location: Any) -> None: @@ -154,7 +158,7 @@ def pytest_runtest_logstart(self, nodeid: str, location: Any) -> None: def pytest_runtest_teardown(self, item: Any, nextitem: Any) -> None: unused(nextitem) for function in state()._stats: - state().tests_by_mangled_function_name[function].add(strip_prefix(item.nodeid, prefix="mutants/")) + state().tests_by_mangled_function_name[function].add(strip_prefix(item.nodeid, prefix=prefix)) state()._stats.clear() # noinspection PyMethodMayBeStatic @@ -165,15 +169,15 @@ def pytest_runtest_makereport(self, item: Any, call: Any) -> None: stats_collector = StatsCollector() - with change_cwd("mutants"): + with change_cwd(mutants_dir): return int(self.execute_pytest(self._pytest_args_regular_run(tests), plugins=[stats_collector])) def run_tests(self, *, mutant_name: str | None, tests: Iterable[str]) -> int: - with change_cwd("mutants"): + with change_cwd(get_mutants_dir()): return int(self.execute_pytest(self._pytest_args_regular_run(tests))) def collect_main_test_coverage(self, cov: Coverage) -> int: - with change_cwd("mutants"), cov.collect(): + with change_cwd(get_mutants_dir()), cov.collect(): self.prepare_main_test_run() return int(self.execute_pytest(self._pytest_args_regular_run([]))) @@ -196,7 +200,7 @@ def pytest_deselected(self, items: Any) -> None: pytest_args = ["-x", "-q", "--collect-only"] + self._pytest_add_cli_args_test_selection - with change_cwd("mutants"): + with change_cwd(get_mutants_dir()): exit_code = int(self.execute_pytest(pytest_args, plugins=[collector])) if exit_code != 0: raise CollectTestsFailedException() diff --git a/src/mutmut/stats.py b/src/mutmut/stats.py index 97a31b7e..e76950c1 100644 --- a/src/mutmut/stats.py +++ b/src/mutmut/stats.py @@ -8,6 +8,7 @@ from pathlib import Path from mutmut.configuration import config +from mutmut.configuration import get_mutants_dir from mutmut.mutation.data import SourceFileMutationData from mutmut.state import state from mutmut.ui.terminal import print_status @@ -107,7 +108,7 @@ def print_stats( def load_stats() -> bool: did_load = False try: - with open("mutants/mutmut-stats.json") as f: + with open(get_mutants_dir() / "mutmut-stats.json") as f: data = json.load(f) for k, v in data.pop("tests_by_mangled_function_name").items(): state().tests_by_mangled_function_name[k] |= set(v) @@ -130,7 +131,7 @@ def load_stats() -> bool: def save_stats() -> None: - with open("mutants/mutmut-stats.json", "w") as f: + with open(get_mutants_dir() / "mutmut-stats.json", "w") as f: json.dump( dict( tests_by_mangled_function_name={k: list(v) for k, v in state().tests_by_mangled_function_name.items()}, diff --git a/src/mutmut/utils/file_utils.py b/src/mutmut/utils/file_utils.py index 82ef9498..dcc296c4 100644 --- a/src/mutmut/utils/file_utils.py +++ b/src/mutmut/utils/file_utils.py @@ -11,6 +11,7 @@ from pathlib import Path from mutmut.configuration import config +from mutmut.configuration import get_mutants_dir @contextmanager @@ -48,9 +49,10 @@ def walk_mutatable_files() -> Iterator[Path]: def copy_src_dir() -> None: + mutants_dir = get_mutants_dir() for root, name in walk_all_files(): source_path = Path(root) / name - target_path = Path("mutants") / root / name + target_path = mutants_dir / root / name if target_path.exists(): continue @@ -65,10 +67,11 @@ def copy_src_dir() -> None: def copy_also_copy_files() -> None: assert isinstance(config().also_copy, list) + mutants_dir = get_mutants_dir() for path in config().also_copy: print(" also copying", path) path = Path(path) - destination = Path("mutants") / path + destination = mutants_dir / path if not path.exists(): continue if path.is_file(): @@ -79,11 +82,12 @@ def copy_also_copy_files() -> None: def setup_source_paths() -> None: # ensure that the mutated source code can be imported by the tests + mutants_dir = get_mutants_dir() source_code_paths = [Path("."), Path("src"), Path("source")] for path in source_code_paths: - mutated_path = Path("mutants") / path + mutated_path = mutants_dir / path if mutated_path.exists(): - sys.path.insert(0, str(mutated_path.absolute())) + sys.path.insert(0, str(mutated_path.resolve())) # ensure that the original code CANNOT be imported by the tests for path in source_code_paths: diff --git a/tests/test_configuration.py b/tests/test_configuration.py index 33a7438b..5bf24db1 100644 --- a/tests/test_configuration.py +++ b/tests/test_configuration.py @@ -9,6 +9,7 @@ from mutmut.configuration import _guess_source_paths from mutmut.configuration import _load_config from mutmut.configuration import config +from mutmut.configuration import get_mutants_dir from mutmut.configuration import reset_config @@ -395,3 +396,91 @@ def test_also_copy_includes_defaults(self, in_tmp_dir: Path): assert Path("poetry.lock") in config.also_copy assert Path("Pipfile.lock") in config.also_copy assert Path("pdm.lock") in config.also_copy + + +class TestMutantsDirConfig: + def test_defaults_to_mutants(self, in_tmp_dir: Path): + (in_tmp_dir / "src").mkdir() + cfg = _load_config() + assert cfg.mutants_dir == Path("mutants") + assert cfg.log_file_path == str(Path("mutants") / "mutmut-debug.log") + assert cfg.resolved_mutated_source_paths == [(in_tmp_dir / "mutants" / "src").resolve()] + + def test_relative_mutants_dir_from_pyproject(self, in_tmp_dir: Path): + (in_tmp_dir / "src").mkdir() + (in_tmp_dir / "pyproject.toml").write_text('[tool.mutmut]\nmutants_dir = ".cache/mutmut"\n') + cfg = _load_config() + assert cfg.mutants_dir == Path(".cache/mutmut") + assert cfg.log_file_path == str(Path(".cache/mutmut") / "mutmut-debug.log") + assert cfg.resolved_mutated_source_paths == [(in_tmp_dir / ".cache/mutmut/src").resolve()] + + def test_absolute_mutants_dir_from_setup_cfg(self, in_tmp_dir: Path, tmp_path_factory: pytest.TempPathFactory): + out_dir = tmp_path_factory.mktemp("external_mutants") + (in_tmp_dir / "src").mkdir() + (in_tmp_dir / "setup.cfg").write_text(f"[mutmut]\nmutants_dir = {out_dir}\n") + cfg = _load_config() + assert cfg.mutants_dir == out_dir + assert cfg.log_file_path == str(out_dir / "mutmut-debug.log") + assert cfg.resolved_mutated_source_paths == [(out_dir / "src").resolve()] + + def test_explicit_log_file_path_overrides_mutants_dir_default(self, in_tmp_dir: Path): + (in_tmp_dir / "src").mkdir() + (in_tmp_dir / "pyproject.toml").write_text( + '[tool.mutmut]\nmutants_dir = "build/mutants"\nlog_file_path = "custom.log"\n' + ) + cfg = _load_config() + assert cfg.mutants_dir == Path("build/mutants") + assert cfg.log_file_path == "custom.log" + + @pytest.mark.parametrize("bad_value", ["", " ", ".", "./", "..", "../..", "/"]) + def test_rejects_empty_root_or_ancestor_mutants_dir(self, in_tmp_dir: Path, bad_value: str): + (in_tmp_dir / "src").mkdir() + (in_tmp_dir / "pyproject.toml").write_text(f'[tool.mutmut]\nmutants_dir = "{bad_value}"\n') + with pytest.raises(ValueError, match="Invalid mutants_dir value"): + _load_config() + + @pytest.mark.parametrize("toml_literal", ["123", '["mutants"]']) + def test_rejects_non_string_mutants_dir(self, in_tmp_dir: Path, toml_literal: str): + (in_tmp_dir / "src").mkdir() + (in_tmp_dir / "pyproject.toml").write_text(f"[tool.mutmut]\nmutants_dir = {toml_literal}\n") + with pytest.raises(ValueError, match="Invalid mutants_dir value"): + _load_config() + + @pytest.mark.parametrize( + ("source_paths", "mutants_dir", "extra_config"), + [ + ('["src"]', "src", ""), + ('["src"]', "src/mutants", ""), + ('["src/pkg"]', "src", ""), + ('["src"]', "tests", ""), + ('["src"]', "tests/mutants", ""), + ('["src"]', "fixtures/mutants", 'also_copy = ["fixtures"]\n'), + ('["src"]', "fixtures", 'also_copy = ["fixtures/data"]\n'), + ], + ) + def test_rejects_mutants_dir_overlapping_source_or_also_copy( + self, in_tmp_dir: Path, source_paths: str, mutants_dir: str, extra_config: str + ): + (in_tmp_dir / "src" / "pkg").mkdir(parents=True) + (in_tmp_dir / "pyproject.toml").write_text( + f'[tool.mutmut]\nsource_paths = {source_paths}\nmutants_dir = "{mutants_dir}"\n{extra_config}' + ) + with pytest.raises(ValueError, match="Invalid mutants_dir value"): + _load_config() + + def test_allows_mutants_dir_sharing_name_prefix_with_source_path(self, in_tmp_dir: Path): + (in_tmp_dir / "src").mkdir() + (in_tmp_dir / "pyproject.toml").write_text( + '[tool.mutmut]\nsource_paths = ["src"]\nmutants_dir = "src_mutants"\n' + ) + assert _load_config().mutants_dir == Path("src_mutants") + + def test_get_mutants_dir_works_without_source_paths(self, in_tmp_dir: Path): + assert get_mutants_dir() == Path("mutants") + (in_tmp_dir / "pyproject.toml").write_text('[tool.mutmut]\nmutants_dir = "alt_mutants"\n') + assert get_mutants_dir() == Path("alt_mutants") + + def test_get_mutants_dir_reads_loaded_config(self, in_tmp_dir: Path, patch_config): + (in_tmp_dir / "src").mkdir() + patch_config("mutants_dir", Path("patched_mutants")) + assert get_mutants_dir() == Path("patched_mutants") diff --git a/tests/test_mutants_dir.py b/tests/test_mutants_dir.py new file mode 100644 index 00000000..dd5422a8 --- /dev/null +++ b/tests/test_mutants_dir.py @@ -0,0 +1,182 @@ +"""End-to-end tests for configuring a custom ``mutants_dir``.""" + +import json +import os +import shutil +import subprocess +import sys +from contextlib import contextmanager +from pathlib import Path + +import pytest +from click.testing import CliRunner + +import mutmut +from mutmut.__main__ import _changed_dependency_files +from mutmut.__main__ import _run +from mutmut.__main__ import cli +from mutmut.stats import load_stats + + +@contextmanager +def _sample_project( + monkeypatch: pytest.MonkeyPatch, + project_dir: Path, + *, + pkg_name: str, + mutants_dir: str, + extra_config: str = "", +): + (project_dir / "src" / pkg_name).mkdir(parents=True) + (project_dir / "tests").mkdir(parents=True) + (project_dir / "src" / pkg_name / "__init__.py").write_text( + "def add(a: int, b: int) -> int:\n return a + b\n\ndef unused() -> int:\n return 42\n" + ) + (project_dir / "tests" / f"test_{pkg_name}.py").write_text( + f"from {pkg_name} import add\n\ndef test_add() -> None:\n assert add(2, 3) == 5\n" + ) + (project_dir / "pyproject.toml").write_text( + f'[tool.mutmut]\nsource_paths = ["src"]\nmutants_dir = "{mutants_dir}"\n{extra_config}' + ) + + saved_sys_path = list(sys.path) + monkeypatch.chdir(project_dir) + mutmut._reset_globals() + try: + yield + finally: + sys.path[:] = saved_sys_path + sys.modules.pop(pkg_name, None) + sys.modules.pop(f"test_{pkg_name}", None) + mutmut._reset_globals() + + +@pytest.mark.skipif(os.name == "nt", reason="Forking not supported on Windows") +class TestCustomMutantsDir: + def test_out_of_tree_mutants_dir_end_to_end(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + pkg_name = "mutants_dir_ext_pkg" + project_dir = tmp_path / "project" + external_dir = tmp_path / "external_mutants" + + with _sample_project(monkeypatch, project_dir, pkg_name=pkg_name, mutants_dir=str(external_dir)): + _run([], max_children=2) + + assert not (project_dir / "mutants").exists() + assert (external_dir / "mutmut-stats.json").is_file() + assert (external_dir / "src" / pkg_name / "__init__.py.meta").is_file() + assert (external_dir / "src" / pkg_name / "__init__.py.spans").is_file() + + runner = CliRunner() + + results_res = runner.invoke(cli, ["results"]) + assert results_res.exit_code == 0 + assert f"{pkg_name}.x_unused__mutmut_1: no tests" in results_res.output + + show_res = runner.invoke(cli, ["show", f"{pkg_name}.x_unused__mutmut_1"]) + assert show_res.exit_code == 0 + assert "- return 42" in show_res.output + assert "+ return 43" in show_res.output + + tests_res = runner.invoke(cli, ["tests-for-mutant", f"{pkg_name}.x_add__mutmut_1"]) + assert tests_res.exit_code == 0 + assert f"tests/test_{pkg_name}.py::test_add" in tests_res.output + + badge_path = tmp_path / "badge.json" + missing_badge_res = runner.invoke(cli, ["badge", "--output", str(badge_path)]) + assert missing_badge_res.exit_code != 0 + assert str(external_dir / "mutmut-cicd-stats.json") in missing_badge_res.output + + export_res = runner.invoke(cli, ["export-cicd-stats"]) + assert export_res.exit_code == 0 + cicd_stats = external_dir / "mutmut-cicd-stats.json" + assert cicd_stats.is_file() + assert str(cicd_stats) in export_res.output + + badge_res = runner.invoke(cli, ["badge", "--output", str(badge_path)]) + assert badge_res.exit_code == 0 + badge_data = json.loads(badge_path.read_text()) + assert badge_data["schemaVersion"] == 1 + assert badge_data["label"] == "mutation" + + apply_res = runner.invoke(cli, ["apply", f"{pkg_name}.x_unused__mutmut_1"]) + assert apply_res.exit_code == 0 + assert "return 43" in (project_dir / "src" / pkg_name / "__init__.py").read_text() + + def test_relative_nested_mutants_dir_with_forkserver(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + pkg_name = "mutants_dir_fs_pkg" + project_dir = tmp_path / "project_fs" + + with _sample_project( + monkeypatch, + project_dir, + pkg_name=pkg_name, + mutants_dir=".cache/mutants", + extra_config='process_isolation = "forkserver"\n', + ): + _run([], max_children=2) + + assert not (project_dir / "mutants").exists() + cache_dir = project_dir / ".cache" / "mutants" + assert (cache_dir / "mutmut-stats.json").is_file() + meta = json.loads((cache_dir / "src" / pkg_name / "__init__.py.meta").read_text()) + assert meta["exit_code_by_key"][f"{pkg_name}.x_add__mutmut_1"] == 1 + assert meta["exit_code_by_key"][f"{pkg_name}.x_unused__mutmut_1"] == 33 + + @pytest.mark.parametrize("mode", ["absolute", "relative_parent", "symlink"]) + def test_custom_mutants_dir_with_mutate_only_covered_lines( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mode: str + ): + pkg_name = f"mutants_dir_cov_{mode}_pkg" + project_dir = tmp_path / f"project_{mode}" + target_dir = tmp_path / f"cov_mutants_{mode}" + + if mode == "absolute": + mutants_dir = str(target_dir) + elif mode == "relative_parent": + mutants_dir = f"../{target_dir.name}" + else: + target_dir.mkdir() + link_dir = tmp_path / f"link_{mode}" + link_dir.symlink_to(target_dir) + mutants_dir = str(link_dir) + + with _sample_project( + monkeypatch, + project_dir, + pkg_name=pkg_name, + mutants_dir=mutants_dir, + extra_config="mutate_only_covered_lines = true\n", + ): + _run([], max_children=2) + + assert not (project_dir / "mutants").exists() + meta = json.loads((target_dir / "src" / pkg_name / "__init__.py.meta").read_text()) + assert f"{pkg_name}.x_add__mutmut_1" in meta["exit_code_by_key"] + assert f"{pkg_name}.x_unused__mutmut_1" not in meta["exit_code_by_key"] + + @pytest.mark.skipif(shutil.which("git") is None, reason="git not installed") + def test_git_change_detection_ignores_custom_mutants_dir(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + pkg_name = "mutants_dir_git_pkg" + project_dir = tmp_path / "project_git" + + with _sample_project(monkeypatch, project_dir, pkg_name=pkg_name, mutants_dir=".mutmut-cache"): + for cmd in [ + ["init", "-q"], + ["config", "user.email", "test@example.com"], + ["config", "user.name", "Test"], + ["config", "commit.gpgsign", "false"], + ["add", "."], + ["commit", "-q", "-m", "init"], + ]: + subprocess.run(["git", *cmd], cwd=project_dir, check=True) + + _run([], max_children=2) + + mutmut._reset_globals() + assert load_stats() + assert _changed_dependency_files() == set() + + sibling_file = project_dir / ".mutmut-cache-extra" / "data.json" + sibling_file.parent.mkdir() + sibling_file.write_text("{}") + assert _changed_dependency_files() == {".mutmut-cache-extra/data.json"}