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
2 changes: 2 additions & 0 deletions HISTORY.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ Unreleased

* Add a ``pytest_add_cli_args_stats_run`` config for pytest arguments of the stats run alone. Under pytest-xdist each worker records which of its tests reach which function and returns them to mutmut, so the stats come out the same as a serial run's. Workers of both runs import the mutated code first, whatever ``sys.path`` pytest-xdist froze for them

* Faster calls of mutated functions in every run: the trampoline reads the active mutant from a module global instead of ``os.environ``, which takes 30 to 40 % off each call. ``MUTANT_UNDER_TEST`` and ``MUTMUT_DEPENDENCY_DEPTH`` are read once, when a process imports mutmut; setting them later in a running process has no effect

3.9.0
~~~~~

Expand Down
65 changes: 24 additions & 41 deletions src/mutmut/mutation/trampoline.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,63 +26,45 @@
F = TypeVar("F", bound=Callable[..., Any])


# Process-local copy of the active mutant. Tests that scrub os.environ
# (``patch.dict(..., clear=True)``) must not be able to disable it. See #511.
_mutant_under_test: str | None = None
# The active mutant, "" for none. The trampoline reads it on every call of a mutated
# function, so it lives in a module global: a lookup in os.environ costs about ten times as
# much. A process that mutmut does not set up itself, such as a pytest-xdist worker or a
# subprocess that a test starts, inherits it through MUTANT_UNDER_TEST, read once here.
# Tests that scrub os.environ (``patch.dict(..., clear=True)``) cannot disable it. See #511.
_mutant_under_test: str = os.environ.get("MUTANT_UNDER_TEST", "")


def set_mutant_under_test(name: str | None) -> None:
"""Record the active mutant in process-local state.
def set_mutant_under_test(name: str) -> None:
"""Make ``name`` the active mutant of this process and of the processes it starts.

``None`` clears the override so the trampoline falls back to ``os.environ``.
A string value is also mirrored into ``MUTANT_UNDER_TEST`` for compatibility.
``MUTANT_UNDER_TEST`` is written as well, so a process started afterwards imports
the same value. Changing the env var alone does not change the active mutant.
"""
global _mutant_under_test
_mutant_under_test = name
if name is not None:
os.environ["MUTANT_UNDER_TEST"] = name
os.environ["MUTANT_UNDER_TEST"] = name


def get_mutant_under_test() -> str:
"""Return the active mutant name.

If ``MUTANT_UNDER_TEST`` is in the environment, that value wins so
existing tests and callers that only set the env var keep working.
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``.
"""
# 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 ""
"""Return the active mutant name, "" for none."""
return _mutant_under_test


# 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
# The dependency tracking depth of the stats run, -1 for no limit. A module global for the
# same reasons as ``_mutant_under_test``.
_dependency_tracking_depth: int = int(os.environ.get("MUTMUT_DEPENDENCY_DEPTH", "-1"))


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.
"""
def set_dependency_tracking_depth(depth: int) -> None:
"""Set the dependency tracking depth of the stats run in this process and the processes it starts."""
global _dependency_tracking_depth
_dependency_tracking_depth = depth
if depth is not None:
os.environ["MUTMUT_DEPENDENCY_DEPTH"] = str(depth)
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"))
return _dependency_tracking_depth


def get_class_attribute(owner: Any, name: str) -> Any:
Expand All @@ -105,7 +87,7 @@ def wrap_in_trampoline(
def mutmut_mutated(decorated_func: Callable[P, R]) -> Callable[P, R]:
"""Wrap the ``decorated_func`` in a trampoline.
The trampoline forwards calls based on the active mutant
(see ``get_mutant_under_test``), either to a copy of the original method,
(see ``set_mutant_under_test``), either to a copy of the original method,
or to the currently active mutated method.
"""

Expand All @@ -128,7 +110,8 @@ def trampoline(*args: P.args, **kwargs: P.kwargs) -> R:
call_args = list(args[1:])
orig_func = get_class_attribute(args[0], orig_func.__name__)

mutant_under_test = get_mutant_under_test()
# Read the module globals directly: a function call per trampoline call is measurable.
mutant_under_test = _mutant_under_test

if mutant_under_test == "fail":
raise MutmutProgrammaticFailException(
Expand All @@ -140,7 +123,7 @@ def trampoline(*args: P.args, **kwargs: P.kwargs) -> R:
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 = get_dependency_tracking_depth()
max_depth = _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
22 changes: 22 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,37 @@
import os
from typing import Any

import pytest

import mutmut.configuration
import mutmut.mutation.trampoline


@pytest.fixture(autouse=True)
def reset_config():
mutmut.configuration.reset_config()


@pytest.fixture(autouse=True)
def restore_mutant_under_test():
"""Restore the active mutant, the dependency tracking depth and their env vars after each test.

set_mutant_under_test() and set_dependency_tracking_depth() write module globals and os.environ,
so a test that calls them, directly or through mutmut, would otherwise change the next test.
"""
trampoline = mutmut.mutation.trampoline
saved_globals = {name: getattr(trampoline, name) for name in ("_mutant_under_test", "_dependency_tracking_depth")}
saved_env = {key: os.environ.get(key) for key in ("MUTANT_UNDER_TEST", "MUTMUT_DEPENDENCY_DEPTH")}
yield
for name, value in saved_globals.items():
setattr(trampoline, name, value)
for key, env_value in saved_env.items():
if env_value is None:
os.environ.pop(key, None)
else:
os.environ[key] = env_value


@pytest.fixture(name="patch_config")
def monkeypatch_config_get(monkeypatch):
"""Utility to overwrite values in the loaded Config.
Expand Down
5 changes: 3 additions & 2 deletions tests/mutation/test_mutation.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
from mutmut.mutation.file_mutation import compute_function_hashes
from mutmut.mutation.file_mutation import create_mutations
from mutmut.mutation.file_mutation import mutate_file_contents
from mutmut.mutation.trampoline import get_mutant_under_test
from mutmut.mutation.trampoline_templates import CLASS_NAME_SEPARATOR
from mutmut.mutation.trampoline_templates import mangle_function_name
from mutmut.state import reset_state
Expand Down Expand Up @@ -1313,7 +1314,7 @@ def test_run_forced_fail_test_with_failing_test(_start, _stop, _dump_output, cap
print(f"out: {out}")
print(f"err: {err}")
assert "done" in out
assert not os.environ["MUTANT_UNDER_TEST"]
assert get_mutant_under_test() == ""


# Negate the effects of CatchOutput because it does not play nicely with capfd in GitHub Actions
Expand All @@ -1327,7 +1328,7 @@ def test_run_forced_fail_test_with_mutmut_programmatic_fail_exception(_start, _s

out, _ = capfd.readouterr()
assert "done" in out
assert not os.environ["MUTANT_UNDER_TEST"]
assert get_mutant_under_test() == ""


# Negate the effects of CatchOutput because it does not play nicely with capfd in GitHub Actions
Expand Down
47 changes: 24 additions & 23 deletions tests/mutation/test_mutation_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
"""

from mutmut.mutation.file_mutation import mutate_file_contents
from mutmut.mutation.trampoline import set_mutant_under_test


def test_enum_mutation_runtime_execution(monkeypatch):
def test_enum_mutation_runtime_execution():
"""Test that mutated enum code can actually be executed and mutants activated."""
source = """
from enum import Enum
Expand All @@ -24,7 +25,7 @@ def describe(self):
mutated_code, mutant_names = mutated_file.code, mutated_file.mutant_names
assert len(mutant_names) > 0, "Should have at least one mutant"

monkeypatch.setenv("MUTANT_UNDER_TEST", "none")
set_mutant_under_test("none")
namespace = {"__name__": "test_module"}
exec(mutated_code, namespace)
Color = namespace["Color"]
Expand All @@ -35,10 +36,10 @@ def describe(self):
assert Color.RED.describe() == "red"

mutant_name = "test_module." + mutant_names[0]
monkeypatch.setenv("MUTANT_UNDER_TEST", mutant_name)
set_mutant_under_test(mutant_name)


def test_enum_creation_hooks_runtime_execution(monkeypatch):
def test_enum_creation_hooks_runtime_execution():
"""Test that an enum whose __init__ and _generate_next_value_ run during class creation can be executed."""
source = """
from enum import Enum, auto
Expand All @@ -61,7 +62,7 @@ def describe(self):
mutated_code, mutant_names = mutated_file.code, mutated_file.mutant_names
assert len(mutant_names) > 0, "Should have at least one mutant"

monkeypatch.setenv("MUTANT_UNDER_TEST", "none")
set_mutant_under_test("none")
namespace = {"__name__": "test_module"}
exec(mutated_code, namespace)
Color = namespace["Color"]
Expand Down Expand Up @@ -94,7 +95,7 @@ def describe(self):
""".strip()


def test_metaclass_getattribute_runtime_execution(monkeypatch):
def test_metaclass_getattribute_runtime_execution():
"""
Classes whose metaclass refuses reads of unknown attributes can be imported and run when mutated.

Expand All @@ -104,7 +105,7 @@ def test_metaclass_getattribute_runtime_execution(monkeypatch):
mutated_file = mutate_file_contents("test.py", GUARDED_METACLASS_SOURCE)
assert "xǁCatalogǁcreate__mutmut_1" in mutated_file.mutant_names

monkeypatch.setenv("MUTANT_UNDER_TEST", "none")
set_mutant_under_test("none")
namespace = {"__name__": "test_module"}
exec(mutated_file.code, namespace)
Child = namespace["Child"]
Expand All @@ -116,29 +117,29 @@ def test_metaclass_getattribute_runtime_execution(monkeypatch):
assert created.describe() == "child 7"


def test_metaclass_getattribute_classmethod_mutant_activation(monkeypatch):
def test_metaclass_getattribute_classmethod_mutant_activation():
"""
A mutant of a classmethod can be activated on a class whose metaclass refuses reads of unknown attributes.

The trampoline of a classmethod looks the method up on the class it was called on (here the
subclass Child), which must not go through the __getattribute__ of the metaclass.
"""
mutated_file = mutate_file_contents("test.py", GUARDED_METACLASS_SOURCE)
monkeypatch.setenv("MUTANT_UNDER_TEST", "none")
set_mutant_under_test("none")
namespace = {"__name__": "test_module"}
exec(mutated_file.code, namespace)
Child = namespace["Child"]
child = Child(0)

# mutant 2 turns `value * 2` into `value / 2`
monkeypatch.setenv("MUTANT_UNDER_TEST", "test_module.xǁCatalogǁcreate__mutmut_2")
set_mutant_under_test("test_module.xǁCatalogǁcreate__mutmut_2")
created = child.create(3)

assert type(created) is Child
assert created.value == 2.5


def test_class_replaced_by_decorator_import(monkeypatch):
def test_class_replaced_by_decorator_import():
"""
A mutated module still imports when a class decorator replaces the class with an instance.

Expand All @@ -158,14 +159,14 @@ def get(self):
mutated_file = mutate_file_contents("test.py", source)
assert "xǁConfigǁget__mutmut_1" in mutated_file.mutant_names

monkeypatch.setenv("MUTANT_UNDER_TEST", "none")
set_mutant_under_test("none")
namespace = {"__name__": "test_module"}
exec(mutated_file.code, namespace)

assert type(namespace["Config"]).__name__ == "Config"


def test_type_annotation_runtime_execution(monkeypatch):
def test_type_annotation_runtime_execution():
"""Test that forward and quoted annotations can be executed

We don't really care about any mutations, we just care if the annotations are processed properly.
Expand Down Expand Up @@ -197,7 +198,7 @@ def from_name(cls, name: str) -> "Color":
mutated_code, mutant_names = mutated_file.code, mutated_file.mutant_names
assert len(mutant_names) > 0, "Should have at least one mutant"

monkeypatch.setenv("MUTANT_UNDER_TEST", "none")
set_mutant_under_test("none")
namespace = {"__name__": "test_module"}
exec(mutated_code, namespace)
Color = namespace["Color"]
Expand All @@ -208,7 +209,7 @@ def from_name(cls, name: str) -> "Color":
assert Color.from_name("green") == Color.GREEN


def test_regular_class_staticmethod_runtime(monkeypatch):
def test_regular_class_staticmethod_runtime():
"""Test that staticmethod mutation in regular classes works at runtime."""
source = """
class Calculator:
Expand All @@ -221,20 +222,20 @@ def add(a, b):
mutated_code, mutant_names = mutated_file.code, mutated_file.mutant_names
assert len(mutant_names) > 0, "Should have at least one mutant"

monkeypatch.setenv("MUTANT_UNDER_TEST", "none")
set_mutant_under_test("none")
namespace = {"__name__": "test_module"}
exec(mutated_code, namespace)
Calculator = namespace["Calculator"]

assert Calculator.add(2, 3) == 5

mutant_name = "test_module." + mutant_names[0]
monkeypatch.setenv("MUTANT_UNDER_TEST", mutant_name)
set_mutant_under_test(mutant_name)

assert Calculator.add(5, 3) == 2


def test_classmethod_subclass_runtime(monkeypatch):
def test_classmethod_subclass_runtime():
"""Test that a @classmethod works at runtime"""
source = """
class Base:
Expand All @@ -251,20 +252,20 @@ def __init__(self, value):
mutated_code, mutant_names = mutated_file.code, mutated_file.mutant_names
assert len(mutant_names) > 0, "Should have at least one mutant"

monkeypatch.setenv("MUTANT_UNDER_TEST", "none")
set_mutant_under_test("none")
namespace = {"__name__": "test_module"}
exec(mutated_code, namespace)
SubClass = namespace["SubClass"]

assert SubClass.create().value == 1

mutant_name = "test_module." + mutant_names[0]
monkeypatch.setenv("MUTANT_UNDER_TEST", mutant_name)
set_mutant_under_test(mutant_name)

assert SubClass.create().value is None


def test_default_arg_mutation(monkeypatch):
def test_default_arg_mutation():
"""Test that simple default arguments are mutated"""
source = """
def foo(a: int, b: int = 2):
Expand All @@ -275,7 +276,7 @@ def foo(a: int, b: int = 2):
mutated_code, mutant_names = mutated_file.code, mutated_file.mutant_names
assert len(mutant_names) > 0, "Should have at least one mutant"

monkeypatch.setenv("MUTANT_UNDER_TEST", "none")
set_mutant_under_test("none")
namespace = {"__name__": "test_module"}
exec(mutated_code, namespace)
foo = namespace["foo"]
Expand All @@ -284,7 +285,7 @@ def foo(a: int, b: int = 2):
assert foo(1, 10) == 11

mutant_name = "test_module." + mutant_names[0]
monkeypatch.setenv("MUTANT_UNDER_TEST", mutant_name)
set_mutant_under_test(mutant_name)

assert foo(1) == 4
assert foo(1, 10) == 11
Loading
Loading