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

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

## 根因

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

## 版本兼容性

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

## 解决方案

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

## 无效尝试

- **** — Leaks connections and causes cascading failures in later tests. (75% 失败率)
- **** — Hides real resource leaks and makes debugging harder. (65% 失败率)
