# ScopeMismatch: 你试图在会话作用域的请求对象中访问函数作用域的 fixture db_session

- **ID:** `python/pytest-session-fixture-scope-mismatch`
- **领域:** python
- **类别:** config_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

会话作用域的 fixture 依赖函数作用域的 fixture，pytest 禁止这样做，因为生命周期较短的 fixture 无法存活于其作用域之外。

## 版本兼容性

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

## 解决方案

1. **** (90% 成功率)
   ```
   Align the dependent fixture's scope to session, or restructure so the session fixture does not depend on a function fixture:

@pytest.fixture(scope='session')
def engine():
    ...

@pytest.fixture
def db_session(engine):
    ...
   ```
2. **** (85% 成功率)
   ```
   Use a factory fixture to create per-test objects from a session resource.
   ```

## 无效尝试

- **** — The error is about the fixture dependency graph, not the test; the mismatch persists. (85% 失败率)
- **** — Autouse does not change scope; the ScopeMismatch still occurs. (80% 失败率)
