Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ARCHITECTURE.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
27 changes: 24 additions & 3 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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 ``<mutants_dir>/mutmut-debug.log``.


"also copy" files
~~~~~~~~~~~~~~~~~

Expand Down Expand Up @@ -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
Expand Down
44 changes: 33 additions & 11 deletions src/mutmut/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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


Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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

Expand All @@ -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 <mutants_dir>/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)
Expand Down Expand Up @@ -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()
Expand Down
24 changes: 16 additions & 8 deletions src/mutmut/code_coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -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`).
Expand All @@ -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])
Expand All @@ -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, ()))


Expand All @@ -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
Expand All @@ -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)

Expand Down
55 changes: 47 additions & 8 deletions src/mutmut/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand All @@ -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:
Expand Down Expand Up @@ -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/"),
Expand All @@ -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),
Expand All @@ -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,
)


Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
9 changes: 6 additions & 3 deletions src/mutmut/mutation/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
from itertools import islice
from pathlib import Path

from mutmut.configuration import get_mutants_dir


@dataclass(frozen=True)
class LineSpan:
Expand All @@ -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
Expand Down Expand Up @@ -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] = {}
Expand Down
3 changes: 2 additions & 1 deletion src/mutmut/mutation/diff_apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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())


Expand Down
Loading