python runtime_error ai_generated true

ERROR at teardown of test_create_user E RuntimeError: database connection already closed ERROR at setup of test_create_user E RuntimeError: database connection already closed

ID: python/pytest-fixture-teardown-error-masked

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

Version Compatibility

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

Root Cause

A session- or module-scoped fixture closed a shared resource in its teardown, but subsequent tests in the same scope still tried to use it, producing errors at both teardown and the next setup.

generic

中文

会话或模块作用域的 fixture 在其 teardown 中关闭了共享资源,但同一作用域中的后续测试仍试图使用它,导致 teardown 和下一次 setup 都报错。

Workarounds

  1. 95% success
    @pytest.fixture
    def db():
        conn = connect()
        yield conn
        conn.close()
    # each test gets a fresh connection
  2. 90% success
    @pytest.fixture(scope='session')
    def engine():
        eng = create_engine(...)
        yield eng
        eng.dispose()
    
    @pytest.fixture
    def db(engine):
        conn = engine.connect()
        trans = conn.begin()
        yield conn
        trans.rollback()
        conn.close()

Dead Ends

Common approaches that don't work:

  1. 90% fail

    That flag affects collection errors, not fixture teardown errors; tests still error out.

  2. 85% fail

    Swallows the error but leaves the resource closed, so subsequent tests still fail at setup.