python runtime_error ai_generated true

E RuntimeError: database connection still open after teardown E ERROR at teardown of test_create_user

ID: python/pytest-fixture-teardown-error

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

Version Compatibility

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

Root Cause

A fixture's teardown code raised an exception, often because the resource was already closed or the test left it in an inconsistent state.

generic

中文

fixture 的 teardown 代码抛出异常,通常是因为资源已被关闭或测试将其留在不一致状态。

Workarounds

  1. 90% success
    Guard teardown with a check:
    @pytest.fixture
    def db():
        conn = connect()
        yield conn
        if not conn.closed:
            conn.close()
  2. 85% success
    Use `addfinalizer` for ordered cleanup:
    @pytest.fixture
    def resource(request):
        r = acquire()
        request.addfinalizer(r.release)
        return r

Dead Ends

Common approaches that don't work:

  1. 75% fail

    Leaks connections and causes cascading failures in later tests.

  2. 65% fail

    Hides real resource leaks and makes debugging harder.