test_monkeypatch.py


Overview

This file contains a comprehensive suite of tests for the `MonkeyPatch` utility class from the `_pytest.monkeypatch` module. The `MonkeyPatch` class is a powerful tool used primarily in testing environments to safely and temporarily modify or replace attributes, dictionary items, environment variables, and system states such as the current working directory or the Python import path (`sys.path`).

The tests in this file validate `MonkeyPatch`'s core functionalities, including setting and deleting attributes and items, patching environment variables, manipulating the Python import system, and ensuring proper undoing of patches to revert system state after tests run. It also covers edge cases, error handling, and integration behavior with other parts of the `pytest` ecosystem.


Detailed Components

Imports and Fixtures


Test Functions and Classes

1. test_setattr()

Tests the `setattr` method of `MonkeyPatch` for:

**Usage example:**

class A:
    x = 1

monkeypatch = MonkeyPatch()
monkeypatch.setattr(A, "x", 2)
assert A.x == 2
monkeypatch.undo()
assert A.x == 1

2. TestSetattrWithImportPath

A class grouping tests for `MonkeyPatch.setattr` when using string import paths to specify the target attribute:


3. test_delattr()

Tests the `delattr` method:


4. test_setitem() and test_delitem()

Test the patching of dictionary items via `setitem` and `delitem`:


5. Environment Variable Tests: test_setenv(), test_delenv(), TestEnvironWarnings, test_setenv_prepend()


6. test_monkeypatch_plugin

Validates that `monkeypatch` is correctly injected as a pytest fixture and has the expected class.


7. test_syspath_prepend() and related tests


8. Working Directory Tests: test_chdir_with_path_local(), test_chdir_with_str(), test_chdir_undo(), test_chdir_double_undo()


9. Issue and Edge Case Tests


Classes

Sample and SampleInherit

Simple classes with a static method `hello()` used in parameterized tests verifying patching and undo of static methods in base and inherited classes.


Important Implementation Details and Algorithms


Interaction with Other System Components


Usage Examples

Basic attribute patching and undo

class MyClass:
    attr = 10

mp = MonkeyPatch()
mp.setattr(MyClass, "attr", 20)
assert MyClass.attr == 20
mp.undo()
assert MyClass.attr == 10

Patching environment variables with prepend

mp = MonkeyPatch()
mp.setenv("PATH", "/custom/path", prepend=":")
# os.environ['PATH'] now has "/custom/path" prepended
mp.undo()

Using MonkeyPatch as context manager

with MonkeyPatch.context() as mp:
    mp.setattr(some_module, "func", lambda: 42)
    # patched func active here
# patch undone after block

Mermaid Diagram: Class Diagram for Test Classes

classDiagram
    class TestSetattrWithImportPath {
        +test_string_expression(monkeypatch)
        +test_string_expression_class(monkeypatch)
        +test_unicode_string(monkeypatch)
        +test_wrong_target(monkeypatch)
        +test_unknown_import(monkeypatch)
        +test_unknown_attr(monkeypatch)
        +test_unknown_attr_non_raising(monkeypatch)
        +test_delattr(monkeypatch)
    }

    class TestEnvironWarnings {
        +test_setenv_non_str_warning(monkeypatch)
    }

    class Sample {
        +static hello() bool
    }

    class SampleInherit {
    }

    TestSetattrWithImportPath ..|> object
    TestEnvironWarnings ..|> object
    SampleInherit --|> Sample

Summary

`test_monkeypatch.py` is a critical test suite that ensures the robustness, correctness, and usability of `pytest`'s `MonkeyPatch` utility. It covers a wide range of patching scenarios, including attributes, dictionary items, environment variables, system path manipulation, and working directory changes, while carefully validating undo functionality and error cases. It also ensures compatibility with Python's import system and third-party modules, providing confidence for users relying on `MonkeyPatch` in complex testing environments.