python
runtime_error
ai_generated
true
test_x 的 teardown 期间出错 RuntimeError: 生成器在 throw() 之后未停止 处理上述异常时又出现另一个异常: ValueError: 对已关闭文件进行 I/O 操作
ERROR at teardown of test_x RuntimeError: generator didn't stop after throw() During handling of the above exception, another exception occurred: ValueError: I/O operation on closed file
ID: python/pytest-fixture-finalizer-exception
80%修复率
86%置信度
0证据数
2024-10-04首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
根因分析
基于生成器的 fixture 在裸 except 或抛异常的 finally 中吞掉了 GeneratorExit/异常,阻止了正确的 teardown。pytest 随后报告 teardown 错误,掩盖了真正的测试结果。
English
A generator-based fixture swallowed the GeneratorExit/exception in a bare except or a finally that raised, preventing proper teardown. pytest then reports teardown errors that mask the real test result.
解决方案
-
95% 成功率
Never catch BaseException or bare except in a yield fixture. Use try/finally: @pytest.fixture def res(): r = acquire() try: yield r finally: r.close() -
90% 成功率
Use addfinalizer for complex cleanup: @pytest.fixture def res(request): r = acquire() request.addfinalizer(r.close) return r
无效尝试
常见但无效的做法:
-
80% 失败
If the except swallows GeneratorExit, the 'generator didn't stop' error persists.
-
70% 失败
Loses cleanup; resources leak across tests.