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

其他格式: JSON · Markdown 中文 · English
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.

generic

解决方案

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

无效尝试

常见但无效的做法:

  1. 90% 失败

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

  2. 60% 失败

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

  3. 85% 失败

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