python runtime_error ai_generated true

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

ID: python/pytest-session-fixture-finalizer-error

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
7.x active
8.x active

Root Cause

A yield-based fixture raised an exception inside its teardown after the yield, and the generator did not catch it, so pytest's finalizer machinery reports the generator as still running.

generic

中文

基于 yield 的 fixture 在 yield 之后的 teardown 中引发异常,生成器未捕获,pytest 的 finalizer 机制报告生成器仍在运行。

Workarounds

  1. 92% success
    @pytest.fixture
    def client():
        c = connect()
        try:
            yield c
        finally:
            try:
                c.close()
            except Exception as e:
                log.warning('close failed: %s', e)
  2. 90% success
    @pytest.fixture
    def client(request):
        c = connect()
        request.addfinalizer(c.close)
        return c

Dead Ends

Common approaches that don't work:

  1. 80% fail

    The error occurs during fixture teardown, outside the test body, so the test's try/except never sees it.

  2. 70% fail

    Loses teardown entirely; resources are never released and the error is replaced by a leak.