python runtime_error ai_generated true

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

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

Version Compatibility

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

Root Cause

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.

generic

中文

基于生成器的 fixture 在裸 except 或抛异常的 finally 中吞掉了 GeneratorExit/异常,阻止了正确的 teardown。pytest 随后报告 teardown 错误,掩盖了真正的测试结果。

Workarounds

  1. 95% success
    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()
  2. 90% success
    Use addfinalizer for complex cleanup:
      @pytest.fixture
      def res(request):
          r = acquire()
          request.addfinalizer(r.close)
          return r

Dead Ends

Common approaches that don't work:

  1. 80% fail

    If the except swallows GeneratorExit, the 'generator didn't stop' error persists.

  2. 70% fail

    Loses cleanup; resources leak across tests.