python
runtime_error
ai_generated
true
AssertionError: assert <MagicMock> == '/tmp/real' # 单独运行时第一个测试通过,一起运行时第二个失败
AssertionError: assert <MagicMock> == '/tmp/real' # first test passes, second fails when run together
ID: python/pytest-monkeypatch-not-undone
80%修复率
90%置信度
0证据数
2024-05-09首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
根因分析
某个测试修改了全局对象(环境变量、模块属性、字典),但未使用 monkeypatch 或 addfinalizer,导致变更泄漏到后续测试。
English
A test mutates a global (env var, module attribute, dict) without using monkeypatch or addfinalizer, so the change leaks into subsequent tests.
解决方案
-
98% 成功率
def test_x(monkeypatch): monkeypatch.setenv('APP_MODE', 'test') monkeypatch.setattr('myapp.config.DEBUG', True) run() -
90% 成功率
@pytest.fixture def temp_registry(): old = myapp.registry.copy() yield myapp.registry myapp.registry.clear() myapp.registry.update(old)
无效尝试
常见但无效的做法:
-
90% 失败
Fragile and unpredictable; pytest ordering depends on collection and xdist distribution.
-
60% 失败
If the test fails before finally, or uses yield fixtures incorrectly, restoration still may not happen.
-
85% 失败
Only helps if pytest-randomly is the cause; the underlying leak persists.