python data_error ai_generated true

AssertionError: assert 5 == 3 # 但单独运行时通过: pytest tests/test_counter.py::test_reset 通过

AssertionError: assert 5 == 3 # but passes when run individually: pytest tests/test_counter.py::test_reset passes

ID: python/pytest-session-fixture-mutation-leak

其他格式: JSON · Markdown 中文 · English
80%修复率
86%置信度
0证据数
2024-12-01首次发现

版本兼容性

版本状态引入弃用备注
7.x active — — —
8.x active — — —

根因分析

session 作用域的 fixture 持有可变状态,被前一个测试修改;测试顺序依赖导致单独运行通过但完整运行时失败。

English

A session-scoped fixture holds mutable state that a previous test mutated; test order dependence makes it pass in isolation but fail in the full run.

generic

解决方案

  1. 95% 成功率
    @pytest.fixture
    def counter():
        return Counter()  # function scope, fresh each test
    
    # or use a factory:
    @pytest.fixture
    def make_counter():
        def _make():
            return Counter()
        return _make
  2. 88% 成功率
    @pytest.fixture(autouse=True)
    def reset_state():
        yield
        global_state.clear()

无效尝试

常见但无效的做法:

  1. 70% 失败

    May make the suite pass by accident on one order, but the underlying shared state bug remains.

  2. 90% 失败

    Timing is not the issue; state leakage is. The failure persists.