python runtime_error ai_generated true

AssertionError: assert <MagicMock> == '/tmp/real' # first test passes, second fails when run together

ID: python/pytest-monkeypatch-not-undone

Also available as: JSON · Markdown · 中文
80%Fix Rate
90%Confidence
0Evidence
2024-05-09First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
7.x active
8.x active

Root Cause

A test mutates a global (env var, module attribute, dict) without using monkeypatch or addfinalizer, so the change leaks into subsequent tests.

generic

中文

某个测试修改了全局对象(环境变量、模块属性、字典),但未使用 monkeypatch 或 addfinalizer,导致变更泄漏到后续测试。

Workarounds

  1. 98% success
    def test_x(monkeypatch):
        monkeypatch.setenv('APP_MODE', 'test')
        monkeypatch.setattr('myapp.config.DEBUG', True)
        run()
  2. 90% success
    @pytest.fixture
    def temp_registry():
        old = myapp.registry.copy()
        yield myapp.registry
        myapp.registry.clear()
        myapp.registry.update(old)

Dead Ends

Common approaches that don't work:

  1. 90% fail

    Fragile and unpredictable; pytest ordering depends on collection and xdist distribution.

  2. 60% fail

    If the test fails before finally, or uses yield fixtures incorrectly, restoration still may not happen.

  3. 85% fail

    Only helps if pytest-randomly is the cause; the underlying leak persists.