python runtime_error ai_generated true

E RuntimeError: teardown 后数据库连接仍未关闭 E test_create_user 的 teardown 出错

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

ID: python/pytest-fixture-teardown-error

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

版本兼容性

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

根因分析

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

English

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

解决方案

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

无效尝试

常见但无效的做法:

  1. 75% 失败

    Leaks connections and causes cascading failures in later tests.

  2. 65% 失败

    Hides real resource leaks and makes debugging harder.