python runtime_error ai_generated true

test_create_user 的 teardown 出错 File ".../conftest.py", 行 42, 在 db conn.close() psycopg2.OperationalError: 服务器意外关闭了连接

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

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

版本兼容性

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

根因分析

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

English

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

解决方案

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

无效尝试

常见但无效的做法:

  1. 70% 失败

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

  2. 60% 失败

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