python runtime_error ai_generated true

ERROR at teardown of test_create_user File "tests/conftest.py", line 40, in db_session session.rollback() sqlalchemy.exc.PendingRollbackError: This Session's transaction has been rolled back due to a previous exception during flush.

ID: python/pytest-teardown-error-masked

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.0 active — — —

Root Cause

The test left the SQLAlchemy session in a failed state (unhandled exception during flush); the fixture teardown then calls rollback/close on a session that is already invalid, producing a teardown ERROR that masks the original failure.

generic

中文

测试使 SQLAlchemy session 处于失败状态(flush 期间未处理异常);fixture 清理时对已失效的 session 调用 rollback/close,产生 teardown ERROR 掩盖了原始失败。

Workarounds

  1. 90% success
    Use a nested transaction + savepoint pattern and always roll back cleanly:
    @pytest.fixture
    def db_session(engine):
        conn = engine.connect()
        trans = conn.begin()
        session = Session(bind=conn)
        try:
            yield session
        finally:
            session.close()
            trans.rollback()
            conn.close()
  2. 85% success
    Or use `session.begin_nested()` and explicitly rollback the savepoint:
    @pytest.fixture
    def db_session(engine):
        session = Session(bind=engine)
        session.begin_nested()
        yield session
        session.rollback()
        session.close()

Dead Ends

Common approaches that don't work:

  1. 85% fail

    Hides the real error and leaves the session dirty, cascading failures into later tests.

  2. 70% fail

    Does not clear the failed transaction state; rollback still raises.