python data_error ai_generated true

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

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-12-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
7.x active — — —
8.x active — — —

Root Cause

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

中文

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

Workarounds

  1. 95% success
    @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% success
    @pytest.fixture(autouse=True)
    def reset_state():
        yield
        global_state.clear()

Dead Ends

Common approaches that don't work:

  1. 70% fail

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

  2. 90% fail

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