python runtime_error ai_generated partial

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
82%Confidence
0Evidence
2024-12-06First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
7.x active — — —
8.x active — — —

Root Cause

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

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 75% fail

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

  2. 60% fail

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