# sqlalchemy.exc.UnboundExecutionError: 无法为 Mapper Mapper[User(users)] 或此 Session 定位绑定。

- **ID:** `python/pytest-sqlalchemy-session-not-bound`
- **领域:** python
- **类别:** config_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 2.0.x | active | — | — |

## 解决方案

1. **** (96% 成功率)
   ```
   from sqlalchemy.orm import sessionmaker

@pytest.fixture
def db(engine):
    Session = sessionmaker(bind=engine)
    session = Session()
    yield session
    session.close()
   ```
2. **** (93% 成功率)
   ```
   from sqlalchemy.orm import scoped_session, sessionmaker

@pytest.fixture
def db(engine):
    factory = sessionmaker(bind=engine)
    Session = scoped_session(factory)
    yield Session()
    Session.remove()
   ```

## 无效尝试

- **** — Rebinding after the session has already executed queries or checked out connections raises InvalidRequestError; also fragile with scoped_session. (80% 失败率)
- **** — session.connection() requires a bind in the first place; it raises the same UnboundExecutionError. (92% 失败率)
