Skip to content
Merged
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
4 changes: 2 additions & 2 deletions src/mutmut/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
from mutmut.mutation.file_mutation import MutatedFile
from mutmut.mutation.file_mutation import filter_mutants_with_type_checker
from mutmut.mutation.file_mutation import mutate_file_contents
from mutmut.mutation.trampoline import set_dependency_tracking_depth
from mutmut.mutation.trampoline import set_mutant_under_test
from mutmut.runners.harness import CollectTestsFailedException
from mutmut.runners.harness import PytestRunner
Expand Down Expand Up @@ -402,8 +403,7 @@ def run_stats_collection(runner: MutantRunner, tests: Iterable[str] | None = Non

set_mutant_under_test("stats")
os.environ["PY_IGNORE_IMPORTMISMATCH"] = "1"
depth = config().dependency_tracking_depth
os.environ["MUTMUT_DEPENDENCY_DEPTH"] = str(depth)
set_dependency_tracking_depth(config().dependency_tracking_depth)
start_cpu_time = process_time()

with CatchOutput(spinner_title="Running stats") as output_catcher:
Expand Down
40 changes: 37 additions & 3 deletions src/mutmut/mutation/trampoline.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,40 @@ def get_mutant_under_test() -> str:
If the key is missing (for example after ``patch.dict(..., clear=True)``),
fall back to the process-local copy set by ``set_mutant_under_test``.
"""
if "MUTANT_UNDER_TEST" in os.environ:
# The trampoline calls this on every call of a mutated function, so read os.environ once.
try:
return os.environ["MUTANT_UNDER_TEST"]
except KeyError:
pass
if _mutant_under_test is not None:
return _mutant_under_test
return ""


# Process-local copy of the dependency tracking depth of the stats run, so the trampoline
# does not read and parse ``MUTMUT_DEPENDENCY_DEPTH`` on every call.
_dependency_tracking_depth: int | None = None


def set_dependency_tracking_depth(depth: int | None) -> None:
"""Record the dependency tracking depth of the stats run in process-local state.

``None`` clears it so the trampoline falls back to ``os.environ``. An int value is
also mirrored into ``MUTMUT_DEPENDENCY_DEPTH`` for processes that do not inherit it.
"""
global _dependency_tracking_depth
_dependency_tracking_depth = depth
if depth is not None:
os.environ["MUTMUT_DEPENDENCY_DEPTH"] = str(depth)


def get_dependency_tracking_depth() -> int:
"""Return the dependency tracking depth of the stats run, -1 for no limit."""
if _dependency_tracking_depth is not None:
return _dependency_tracking_depth
return int(os.environ.get("MUTMUT_DEPENDENCY_DEPTH", "-1"))


def get_class_attribute(owner: Any, name: str) -> Any:
"""Return ``owner.name`` without calling a ``__getattribute__`` of the metaclass.

Expand All @@ -82,7 +109,12 @@ def mutmut_mutated(decorated_func: Callable[P, R]) -> Callable[P, R]:
or to the currently active mutated method.
"""

# The qualified name of the original function, built on the first call in the stats run.
# It cannot be built here: the mutants dict is filled after the function is defined.
orig_qual_name: str | None = None

def trampoline(*args: P.args, **kwargs: P.kwargs) -> R:
nonlocal orig_qual_name
# orig_func is the non-mutated implementation.
# we do not use `decorated_func` directly,
# because using the func via SomeClass.foo makes it easier for classmethod wrapping
Expand All @@ -104,9 +136,11 @@ def trampoline(*args: P.args, **kwargs: P.kwargs) -> R:
)

if mutant_under_test == "stats":
orig_qual_name = f"{orig_func.__module__}.{mangled_name_from_mutant_name(orig_func.__name__)}"
if orig_qual_name is None:
orig = mutants_dict["_mutmut_orig"]
orig_qual_name = f"{orig.__module__}.{mangled_name_from_mutant_name(orig.__name__)}"
caller_name, depth = MutmutCallStack.get()
max_depth = int(os.environ.get("MUTMUT_DEPENDENCY_DEPTH", "-1"))
max_depth = get_dependency_tracking_depth()
if max_depth == -1 or depth < max_depth:
record_trampoline_hit(orig_qual_name, caller=caller_name)
token = MutmutCallStack.set((orig_qual_name, depth + 1))
Expand Down
95 changes: 95 additions & 0 deletions tests/mutation/test_trampoline.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,15 @@
import asyncio
import inspect
import os
from unittest.mock import Mock
from unittest.mock import patch

import pytest
from typing_extensions import Self

import mutmut.mutation.trampoline
from mutmut.mutation.trampoline import get_mutant_under_test
from mutmut.mutation.trampoline import set_dependency_tracking_depth
from mutmut.mutation.trampoline import set_mutant_under_test
from mutmut.mutation.trampoline import wrap_in_trampoline

Expand Down Expand Up @@ -457,3 +460,95 @@ def test_trampoline_classmethod_baseclass_original(self, monkeypatch):
assert type(SomeNumberChild.add_zero(123)) is SomeNumberChild, "Should use the subclass"
# assert type(SomeNumberChild(1).add_zero(123)) is SomeNumberChild, 'Should use the subclass'
# assert SomeNumberChild.add_zero(123).number == 123, 'Should use the subclass'


mutants_return_value = {}
mutants_call_return_value = {}


@wrap_in_trampoline(mutants_return_value)
def return_value(a: int) -> int:
return a


def x_return_value__mutmut_orig(a: int) -> int:
return a


@wrap_in_trampoline(mutants_call_return_value)
def call_return_value(a: int) -> int:
return return_value(a)


def x_call_return_value__mutmut_orig(a: int) -> int:
return return_value(a)


mutants_return_value["_mutmut_orig"] = x_return_value__mutmut_orig
mutants_call_return_value["_mutmut_orig"] = x_call_return_value__mutmut_orig


class TestStatsRun:
@pytest.fixture
def recorded_hits(self, monkeypatch):
"""Run the trampolines in stats mode and collect the hits they record."""
hits = []
monkeypatch.setattr(
mutmut.mutation.trampoline,
"record_trampoline_hit",
lambda name, caller=None: hits.append(name),
)
monkeypatch.setenv("MUTANT_UNDER_TEST", "stats")
# set_dependency_tracking_depth() writes os.environ, which monkeypatch restores afterwards
monkeypatch.setenv("MUTMUT_DEPENDENCY_DEPTH", "-1")
yield hits
set_dependency_tracking_depth(None)

def test_dependency_tracking_depth_set_in_process_limits_hits(self, recorded_hits):
"""
The stats run records only calls up to the dependency tracking depth given to set_dependency_tracking_depth().

A call at depth 1 (return_value called by call_return_value) is not recorded with depth 1.
"""
set_dependency_tracking_depth(1)
assert call_return_value(2) == 2
assert recorded_hits == [f"{__name__}.x_call_return_value"]

recorded_hits.clear()
set_dependency_tracking_depth(-1)
assert call_return_value(2) == 2
assert recorded_hits == [f"{__name__}.x_call_return_value", f"{__name__}.x_return_value"]

def test_dependency_tracking_depth_falls_back_to_env(self, recorded_hits, monkeypatch):
"""
The stats run reads the dependency tracking depth from MUTMUT_DEPENDENCY_DEPTH when it was not set in process.
"""
set_dependency_tracking_depth(None)
monkeypatch.setenv("MUTMUT_DEPENDENCY_DEPTH", "1")
assert call_return_value(2) == 2
assert recorded_hits == [f"{__name__}.x_call_return_value"]

def test_qualified_name_is_built_once_per_trampoline(self, recorded_hits, monkeypatch):
"""
The stats run builds the qualified name of a trampolined function on its first call only.

A function in an inner loop runs millions of times in one test.
"""
mutants = {}

@wrap_in_trampoline(mutants)
def return_value_once(a: int) -> int:
return a

def x_return_value_once__mutmut_orig(a: int) -> int:
return a

mutants["_mutmut_orig"] = x_return_value_once__mutmut_orig
mangle = Mock(wraps=mutmut.mutation.trampoline.mangled_name_from_mutant_name)
monkeypatch.setattr(mutmut.mutation.trampoline, "mangled_name_from_mutant_name", mangle)

for _ in range(3):
assert return_value_once(2) == 2

assert recorded_hits == [f"{__name__}.x_return_value_once"] * 3
assert mangle.call_count == 1
Loading