python runtime_error ai_generated true

ERROR 在 test_create_user 的 teardown 处 E RuntimeError: 数据库连接已关闭 ERROR 在 test_create_user 的 setup 处 E RuntimeError: 数据库连接已关闭

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

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

版本兼容性

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

根因分析

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

English

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

解决方案

  1. 95% 成功率
    @pytest.fixture
    def db():
        conn = connect()
        yield conn
        conn.close()
    # each test gets a fresh connection
  2. 90% 成功率
    @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()

无效尝试

常见但无效的做法:

  1. 90% 失败

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

  2. 85% 失败

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