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

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

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

## 根因

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

## 版本兼容性

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

## 解决方案

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

## 无效尝试

- **** — That flag affects collection errors, not fixture teardown errors; tests still error out. (90% 失败率)
- **** — Swallows the error but leaves the resource closed, so subsequent tests still fail at setup. (85% 失败率)
