python runtime_error ai_generated true

ERROR at teardown of test_create_user File "...", line ..., in db_session session.close() RuntimeError: generator didn't stop after throw()

ID: python/pytest-teardown-error-generator

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

A yield-based fixture raised or yielded again after the test injected an exception. Typically caused by a `try/finally` that yields inside `finally`, or a generator fixture that catches exceptions and yields again.

generic

中文

基于 yield 的 fixture 在测试注入异常后再次 yield 或抛出异常。通常由在 `finally` 内 yield 的 `try/finally`,或捕获异常后再次 yield 的生成器 fixture 引起。

Workarounds

  1. 95% success
    import pytest
    
    @pytest.fixture
    def db_session():
        session = SessionLocal()
        try:
            yield session
        finally:
            session.close()  # no yield here
  2. 90% success
    import contextlib
    
    @contextlib.contextmanager
    def db_session():
        s = SessionLocal()
        try:
            yield s
        finally:
            s.close()
    
    # then in fixture
    @pytest.fixture
    def db():
        with db_session() as s:
            yield s

Dead Ends

Common approaches that don't work:

  1. 85% fail

    pytest requires the generator to stop after the exception is thrown; a second yield triggers the same error.

  2. 70% fail

    Loses teardown entirely; DB session/resources are never closed, causing connection leaks.