python runtime_error ai_generated partial

test_x 的 teardown 出错 RuntimeError: generator didn't stop after throw() # 或: ERROR: test_x - Exception: teardown error swallowed

ERROR at teardown of test_x RuntimeError: generator didn't stop after throw() # or: ERROR: test_x - Exception: teardown error swallowed

ID: python/pytest-fixture-finalizer-exception-masked

其他格式: JSON · Markdown 中文 · English
80%修复率
82%置信度
0证据数
2024-12-06首次发现

版本兼容性

版本状态引入弃用备注
7.x active — — —
8.x active — — —

根因分析

yield fixture 的 teardown 抛出异常,掩盖了原始测试失败,或生成器在 yield 后被重新进入,导致 pytest 报告 teardown 错误。

English

A yield fixture's teardown raises an exception that masks the original test failure, or the generator is re-entered after yielding, causing pytest to report a teardown error.

generic

解决方案

  1. 90% 成功率
    @pytest.fixture
    def resource(request):
        r = acquire()
        request.addfinalizer(r.close)
        return r
  2. 85% 成功率
    @pytest.fixture
    def resource():
        r = acquire()
        yield r
        try:
            r.close()
        except Exception:
            import logging
            logging.exception('teardown failed')
            raise

无效尝试

常见但无效的做法:

  1. 75% 失败

    Swallows real cleanup errors; resources may remain locked and subsequent tests fail.

  2. 60% 失败

    Delays teardown to the end of the run but does not prevent the exception from masking failures.