python runtime_error ai_generated true

ERROR at teardown of test_create_user File ".../conftest.py", line 42, in db conn.close() psycopg2.OperationalError: server closed the connection unexpectedly

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-10-30First Seen

Version Compatibility

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

Root Cause

A fixture's teardown code (after yield) raises because the resource it cleans up (DB connection, temp server) was already closed by the test or by an earlier fixture. pytest reports this as a teardown ERROR, which can mask the original test result.

generic

中文

fixture 的清理代码(yield 之后)抛出异常,因为它清理的资源(数据库连接、临时服务器)已被测试或更早的 fixture 关闭。pytest 将其报告为 teardown ERROR,可能掩盖原始测试结果。

Workarounds

  1. 92% success
    @pytest.fixture
    def db():
        conn = connect()
        try:
            yield conn
        finally:
            if not conn.closed:
                conn.close()
  2. 88% success
    def test_query(db):
        with db.cursor() as cur:
            cur.execute('SELECT 1')
        # do not call db.close() here; the fixture owns it

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Hides teardown failures but leaves leaked connections and masks real resource bugs.

  2. 60% fail

    Changes lifecycle and can cause cross-test contamination; the teardown error may still occur.