# test_example 的 teardown 阶段出错

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

## 根因

夹具或测试的清理阶段抛出异常。这通常发生在清理代码（关闭连接、删除文件）因先前测试失败或资源泄漏而失败时。

## 版本兼容性

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

## 解决方案

1. **** (85% 成功率)
   ```
   @pytest.fixture
def resource():
    r = acquire()
    yield r
    try:
        r.release()
    except Exception as e:
        logging.warning(f'Teardown failed: {e}')
   ```
2. **** (88% 成功率)
   ```
   @pytest.fixture
def resource(request):
    r = acquire()
    def cleanup():
        try:
            r.release()
        except Exception:
            pass
    request.addfinalizer(cleanup)
    return r
   ```

## 无效尝试

- **** — This flag only affects collection errors, not teardown errors. The teardown failure will still be reported. (90% 失败率)
- **** — This leaves resources open, causing cascading failures in subsequent tests (e.g., database locks, port conflicts). (95% 失败率)
