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
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 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.
解决方案
-
92% 成功率
@pytest.fixture def db(): conn = connect() try: yield conn finally: if not conn.closed: conn.close() -
88% 成功率
def test_query(db): with db.cursor() as cur: cur.execute('SELECT 1') # do not call db.close() here; the fixture owns it
无效尝试
常见但无效的做法:
-
70% 失败
Hides teardown failures but leaves leaked connections and masks real resource bugs.
-
60% 失败
Changes lifecycle and can cause cross-test contamination; the teardown error may still occur.