diff --git a/HISTORY.rst b/HISTORY.rst index 392b80f5..0c7a3f94 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -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 ~~~~~ diff --git a/src/mutmut/mutation/trampoline.py b/src/mutmut/mutation/trampoline.py index 926cbd47..e7b401d1 100644 --- a/src/mutmut/mutation/trampoline.py +++ b/src/mutmut/mutation/trampoline.py @@ -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: @@ -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. """ @@ -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( @@ -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)) diff --git a/tests/conftest.py b/tests/conftest.py index c17b931f..aac0d47c 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,8 +1,10 @@ +import os from typing import Any import pytest import mutmut.configuration +import mutmut.mutation.trampoline @pytest.fixture(autouse=True) @@ -10,6 +12,26 @@ 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. diff --git a/tests/mutation/test_mutation.py b/tests/mutation/test_mutation.py index 42b60d5a..e3794a66 100644 --- a/tests/mutation/test_mutation.py +++ b/tests/mutation/test_mutation.py @@ -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 @@ -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 @@ -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 diff --git a/tests/mutation/test_mutation_runtime.py b/tests/mutation/test_mutation_runtime.py index efa58fe2..d3e808a7 100644 --- a/tests/mutation/test_mutation_runtime.py +++ b/tests/mutation/test_mutation_runtime.py @@ -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 @@ -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"] @@ -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 @@ -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"] @@ -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. @@ -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"] @@ -116,7 +117,7 @@ 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. @@ -124,21 +125,21 @@ def test_metaclass_getattribute_classmethod_mutant_activation(monkeypatch): 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. @@ -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. @@ -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"] @@ -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: @@ -221,7 +222,7 @@ 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"] @@ -229,12 +230,12 @@ def add(a, b): 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: @@ -251,7 +252,7 @@ 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"] @@ -259,12 +260,12 @@ def __init__(self, value): 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): @@ -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"] @@ -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 diff --git a/tests/mutation/test_trampoline.py b/tests/mutation/test_trampoline.py index e06b371a..8b477b1c 100644 --- a/tests/mutation/test_trampoline.py +++ b/tests/mutation/test_trampoline.py @@ -6,6 +6,8 @@ import asyncio import inspect import os +import subprocess +import sys from unittest.mock import Mock from unittest.mock import patch @@ -246,47 +248,76 @@ def __init__(self, number: int): class TestSimpleFunc: - def test_trampoline_simple_func_original(self, monkeypatch): - monkeypatch.setenv("MUTANT_UNDER_TEST", "") + def test_trampoline_simple_func_original(self): + set_mutant_under_test("") assert simple_func(2, 3) == 5, "Should call original function" - def test_trampoline_simple_func_mutated(self, monkeypatch): - monkeypatch.setenv("MUTANT_UNDER_TEST", "test_trampoline.simple_func__mutmut_1") + def test_trampoline_simple_func_mutated(self): + set_mutant_under_test("test_trampoline.simple_func__mutmut_1") assert simple_func(2, 3) == -1, "Should call mutated function" - def test_trampoline_simple_func_other_module(self, monkeypatch): + def test_trampoline_simple_func_other_module(self): # if we have the same mutant name in a different module, we should not mutate - monkeypatch.setenv("MUTANT_UNDER_TEST", "other_test_trampoline.simple_func__mutmut_1") + set_mutant_under_test("other_test_trampoline.simple_func__mutmut_1") assert simple_func(2, 3) == 5, "Should call mutated function" def test_trampoline_survives_cleared_environ(self): # Tests that scrub os.environ (patch.dict(..., clear=True)) used to # make the trampoline fall back to the original function. See #511. set_mutant_under_test("test_trampoline.simple_func__mutmut_1") - try: - with patch.dict(os.environ, {"IN_DOCKER": "1"}, clear=True): - assert "MUTANT_UNDER_TEST" not in os.environ - assert simple_func(2, 3) == -1, "Should still call mutated function" - finally: - set_mutant_under_test(None) + with patch.dict(os.environ, {"IN_DOCKER": "1"}, clear=True): + assert "MUTANT_UNDER_TEST" not in os.environ + assert simple_func(2, 3) == -1, "Should still call mutated function" + + def test_trampoline_ignores_env_var_changed_in_process(self): + """ + The active mutant changes only through set_mutant_under_test(), not through MUTANT_UNDER_TEST. + + The trampoline reads a module global on every call instead of os.environ, which costs + about ten times as much. The env var is read once, when the module is imported. + """ + set_mutant_under_test("") + os.environ["MUTANT_UNDER_TEST"] = "test_trampoline.simple_func__mutmut_1" + assert simple_func(2, 3) == 5, "Should call original function" + assert get_mutant_under_test() == "" + + +@pytest.mark.parametrize( + ("env_var", "value", "getter"), + [ + pytest.param("MUTANT_UNDER_TEST", "pkg.func__mutmut_1", "get_mutant_under_test", id="mutant-under-test"), + pytest.param("MUTMUT_DEPENDENCY_DEPTH", "1", "get_dependency_tracking_depth", id="dependency-tracking-depth"), + ], +) +def test_new_process_reads_env_var_on_import(env_var, value, getter): + """ + A process that mutmut did not set up takes the active mutant and the dependency tracking depth from its environment. - def test_get_mutant_under_test_falls_back_to_env(self, monkeypatch): - set_mutant_under_test(None) - monkeypatch.setenv("MUTANT_UNDER_TEST", "from-env") - assert get_mutant_under_test() == "from-env" + pytest-xdist workers of the stats run and subprocesses that tests start import the + trampoline module fresh and only inherit MUTANT_UNDER_TEST and MUTMUT_DEPENDENCY_DEPTH. + """ + code = f"from mutmut.mutation.trampoline import {getter}; print({getter}())" + result = subprocess.run( + [sys.executable, "-c", code], + env={**os.environ, env_var: value}, + capture_output=True, + text=True, + check=True, + ) + assert result.stdout.strip() == value class TestAsyncAndGeneratorFunc: - def test_generator_func_original(self, monkeypatch): - monkeypatch.setenv("MUTANT_UNDER_TEST", "") + def test_generator_func_original(self): + set_mutant_under_test("") assert list(generator_func([1, 2, 3])) == [2, 4, 6], "Should call original func" - def test_generator_func_mutated(self, monkeypatch): - monkeypatch.setenv("MUTANT_UNDER_TEST", "test_trampoline.generator_func__mutmut_1") + def test_generator_func_mutated(self): + set_mutant_under_test("test_trampoline.generator_func__mutmut_1") assert list(generator_func([1, 2, 3])) == [3, 6, 9], "Should call mutated func" - def test_generator_func_return_value_original(self, monkeypatch): - monkeypatch.setenv("MUTANT_UNDER_TEST", "") + def test_generator_func_return_value_original(self): + set_mutant_under_test("") def consume(): result = yield from returning_generator_func([1, 2, 3]) @@ -294,8 +325,8 @@ def consume(): assert list(consume()) == [2, 4, 6, "done"], "Should forward the return value" - def test_generator_func_return_value_mutated(self, monkeypatch): - monkeypatch.setenv("MUTANT_UNDER_TEST", "test_trampoline.returning_generator_func__mutmut_1") + def test_generator_func_return_value_mutated(self): + set_mutant_under_test("test_trampoline.returning_generator_func__mutmut_1") def consume(): result = yield from returning_generator_func([1, 2, 3]) @@ -304,26 +335,26 @@ def consume(): assert list(consume()) == [3, 6, 9, "done"], "Should forward the return value" @pytest.mark.asyncio - async def test_async_func_original(self, monkeypatch): - monkeypatch.setenv("MUTANT_UNDER_TEST", "") + async def test_async_func_original(self): + set_mutant_under_test("") assert await async_func(2, 3) == 5, "Should call original func" @pytest.mark.asyncio - async def test_async_func_mutated(self, monkeypatch): - monkeypatch.setenv("MUTANT_UNDER_TEST", "test_trampoline.async_func__mutmut_1") + async def test_async_func_mutated(self): + set_mutant_under_test("test_trampoline.async_func__mutmut_1") assert await async_func(2, 3) == -1, "Should call mutated func" @pytest.mark.asyncio - async def test_async_generator_func_original(self, monkeypatch): - monkeypatch.setenv("MUTANT_UNDER_TEST", "") + async def test_async_generator_func_original(self): + set_mutant_under_test("") result = [] async for n in async_generator_func([1, 2, 3]): result.append(n) assert result == [2, 4, 6], "Should call original func" @pytest.mark.asyncio - async def test_async_generator_func_mutated(self, monkeypatch): - monkeypatch.setenv("MUTANT_UNDER_TEST", "test_trampoline.async_generator_func__mutmut_1") + async def test_async_generator_func_mutated(self): + set_mutant_under_test("test_trampoline.async_generator_func__mutmut_1") result = [] async for n in async_generator_func([1, 2, 3]): result.append(n) @@ -357,8 +388,8 @@ class TestAsyncGeneratorProtocolForwarding: """ @pytest.mark.asyncio - async def test_aclose_runs_cleanup_synchronously(self, monkeypatch): - monkeypatch.setenv("MUTANT_UNDER_TEST", "") + async def test_aclose_runs_cleanup_synchronously(self): + set_mutant_under_test("") log: list = [] agen = cleanup_async_gen(log) assert await agen.__anext__() == 1 @@ -369,8 +400,8 @@ async def test_aclose_runs_cleanup_synchronously(self, monkeypatch): assert log == ["cleaned-up"] @pytest.mark.asyncio - async def test_athrow_is_forwarded_into_generator(self, monkeypatch): - monkeypatch.setenv("MUTANT_UNDER_TEST", "") + async def test_athrow_is_forwarded_into_generator(self): + set_mutant_under_test("") agen = recovering_async_gen() assert await agen.__anext__() == 1 @@ -380,8 +411,8 @@ async def test_athrow_is_forwarded_into_generator(self, monkeypatch): await agen.aclose() @pytest.mark.asyncio - async def test_unhandled_athrow_propagates(self, monkeypatch): - monkeypatch.setenv("MUTANT_UNDER_TEST", "") + async def test_unhandled_athrow_propagates(self): + set_mutant_under_test("") agen = recovering_async_gen() assert await agen.__anext__() == 1 @@ -389,8 +420,8 @@ async def test_unhandled_athrow_propagates(self, monkeypatch): await agen.athrow(KeyError("nope")) @pytest.mark.asyncio - async def test_asend_is_forwarded_into_generator(self, monkeypatch): - monkeypatch.setenv("MUTANT_UNDER_TEST", "") + async def test_asend_is_forwarded_into_generator(self): + set_mutant_under_test("") received: list = [] agen = echo_async_gen(received) await agen.asend(None) # prime @@ -402,21 +433,21 @@ async def test_asend_is_forwarded_into_generator(self, monkeypatch): class TestSimpleClassMethods: - def test_trampoline_simple_methods_original(self, monkeypatch): - monkeypatch.setenv("MUTANT_UNDER_TEST", "") + def test_trampoline_simple_methods_original(self): + set_mutant_under_test("") n = SomeNumber(123) assert n.number == 123, "Should call original __init__" n.add(1) assert n.number == 124, "Should call original add" - def test_trampoline_simple_methods_init_mutated(self, monkeypatch): - monkeypatch.setenv("MUTANT_UNDER_TEST", "test_trampoline.SomeNumberǁ__init___mutmut_1") + def test_trampoline_simple_methods_init_mutated(self): + set_mutant_under_test("test_trampoline.SomeNumberǁ__init___mutmut_1") n = SomeNumber(123) assert n.number is None, "Should call mutated __init__" - def test_trampoline_sipmle_methods_add_mutated(self, monkeypatch): - monkeypatch.setenv("MUTANT_UNDER_TEST", "test_trampoline.SomeNumberǁadd__mutmut_1") + def test_trampoline_sipmle_methods_add_mutated(self): + set_mutant_under_test("test_trampoline.SomeNumberǁadd__mutmut_1") n = SomeNumber(123) assert n.number == 123, "Should call original __init__" @@ -425,20 +456,20 @@ def test_trampoline_sipmle_methods_add_mutated(self, monkeypatch): class TestStaticMethods: - def test_trampoline_staticmethod_original(self, monkeypatch): - monkeypatch.setenv("MUTANT_UNDER_TEST", "") + def test_trampoline_staticmethod_original(self): + set_mutant_under_test("") assert SomeNumber.negate(123) == -123, "Should call original negate on class" assert SomeNumber(1).negate(123) == -123, "Should call original negate on instance" - def test_trampoline_staticmethod_mutated(self, monkeypatch): - monkeypatch.setenv("MUTANT_UNDER_TEST", "test_trampoline.SomeNumberǁnegate__mutmut_1") + def test_trampoline_staticmethod_mutated(self): + set_mutant_under_test("test_trampoline.SomeNumberǁnegate__mutmut_1") assert SomeNumber.negate(123) == 123, "Should call mutated negate on class" assert SomeNumber(1).negate(123) == 123, "Should call mutated negate on instance" class TestClassMethods: - def test_trampoline_classmethod_original(self, monkeypatch): - monkeypatch.setenv("MUTANT_UNDER_TEST", "") + def test_trampoline_classmethod_original(self): + set_mutant_under_test("") # on class assert type(SomeNumber.add_zero(123)) is SomeNumber, "Should use the class" assert SomeNumber.add_zero(123).number == 123, "Should use the original method" @@ -446,8 +477,8 @@ def test_trampoline_classmethod_original(self, monkeypatch): assert type(SomeNumber(1).add_zero(123)) is SomeNumber, "Should use the class" assert SomeNumber(1).add_zero(123).number == 123, "Should use the original method" - def test_trampoline_classmethod_mutated(self, monkeypatch): - monkeypatch.setenv("MUTANT_UNDER_TEST", "test_trampoline.SomeNumberǁadd_zero__mutmut_1") + def test_trampoline_classmethod_mutated(self): + set_mutant_under_test("test_trampoline.SomeNumberǁadd_zero__mutmut_1") # on class assert type(SomeNumber.add_zero(123)) is SomeNumber, "Should use the class" assert SomeNumber.add_zero(123).number == 124, "Should use the mutated method" @@ -455,8 +486,8 @@ def test_trampoline_classmethod_mutated(self, monkeypatch): assert type(SomeNumber(1).add_zero(123)) is SomeNumber, "Should use the class" assert SomeNumber(1).add_zero(123).number == 124, "Should use the mutated method" - def test_trampoline_classmethod_baseclass_original(self, monkeypatch): - monkeypatch.setenv("MUTANT_UNDER_TEST", "") + def test_trampoline_classmethod_baseclass_original(self): + set_mutant_under_test("") 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' @@ -498,11 +529,9 @@ def recorded_hits(self, monkeypatch): "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) + set_mutant_under_test("stats") + set_dependency_tracking_depth(-1) + return hits def test_dependency_tracking_depth_set_in_process_limits_hits(self, recorded_hits): """ @@ -519,15 +548,6 @@ def test_dependency_tracking_depth_set_in_process_limits_hits(self, recorded_hit 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.