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
80%Fix Rate
90%Confidence
0Evidence
2024-05-09First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 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
-
98% success
def test_x(monkeypatch): monkeypatch.setenv('APP_MODE', 'test') monkeypatch.setattr('myapp.config.DEBUG', True) run() -
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:
-
90% fail
Fragile and unpredictable; pytest ordering depends on collection and xdist distribution.
-
60% fail
If the test fails before finally, or uses yield fixtures incorrectly, restoration still may not happen.
-
85% fail
Only helps if pytest-randomly is the cause; the underlying leak persists.