python config_error ai_generated true

sqlalchemy.exc.UnboundExecutionError: Could not locate a bind configured on mapper Mapper[User(users)] or this Session.

ID: python/pytest-sqlalchemy-session-not-bound

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.0.x active — — —

Root Cause

A SQLAlchemy Session was created without an engine (or sessionmaker bound to engine) and the test fixture yields a session that is later used against an unbound mapper.

generic

中文

创建 SQLAlchemy Session 时未传入 engine(或未将 sessionmaker 绑定到 engine),测试 fixture 产出的 session 在之后对未绑定的 mapper 使用时抛出异常。

Workarounds

  1. 96% success
    from sqlalchemy.orm import sessionmaker
    
    @pytest.fixture
    def db(engine):
        Session = sessionmaker(bind=engine)
        session = Session()
        yield session
        session.close()
  2. 93% success
    from sqlalchemy.orm import scoped_session, sessionmaker
    
    @pytest.fixture
    def db(engine):
        factory = sessionmaker(bind=engine)
        Session = scoped_session(factory)
        yield Session()
        Session.remove()

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Rebinding after the session has already executed queries or checked out connections raises InvalidRequestError; also fragile with scoped_session.

  2. 92% fail

    session.connection() requires a bind in the first place; it raises the same UnboundExecutionError.