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

- **ID:** `python/pytest-fixture-finalizer-error-masked`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 7.x | active | — | — |
| 8.x | active | — | — |

## 解决方案

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
   ```

## 无效尝试

- **** — Hides teardown failures but leaves leaked connections and masks real resource bugs. (70% 失败率)
- **** — Changes lifecycle and can cause cross-test contamination; the teardown error may still occur. (60% 失败率)
