python runtime_error ai_generated true

ERROR at teardown of test_x RuntimeError: generator didn't stop after throw()

ID: python/pytest-fixture-yield-teardown-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2024-08-30First Seen

Version Compatibility

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

Root Cause

A yield fixture's teardown raised an exception that was swallowed, or the generator caught GeneratorExit and continued yielding.

generic

中文

yield fixture 的拆卸引发了被吞掉的异常,或生成器捕获了 GeneratorExit 并继续 yield。

Workarounds

  1. 95% success
    @pytest.fixture
    def resource():
        r = acquire()
        try:
            yield r
        finally:
            r.close()
  2. 92% success
    import contextlib
    
    @contextlib.contextmanager
    def resource_cm():
        r = acquire()
        try:
            yield r
        finally:
            r.close()
    
    @pytest.fixture
    def resource():
        with resource_cm() as r:
            yield r

Dead Ends

Common approaches that don't work:

  1. 90% fail

    Hides the original error and can leak resources.

  2. 85% fail

    Loses teardown entirely; resources leak.

  3. 95% fail

    Unrelated to generator teardown.