# ScopeMismatch: 你尝试以会话级请求对象访问函数级 fixture 'tmp_path'，涉及的工厂

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

## 根因

会话级 fixture 依赖函数级 fixture（如 tmp_path 或 monkeypatch），pytest 禁止此行为，因为窄作用域 fixture 无法比宽作用域 fixture 存活更久。

## 版本兼容性

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

## 解决方案

1. **** (95% 成功率)
   ```
   @pytest.fixture(scope='session')
def data_dir(tmp_path_factory):
    d = tmp_path_factory.mktemp('data')
    (d / 'file.txt').write_text('hi')
    return d
   ```
2. **** (85% 成功率)
   ```
   @pytest.fixture(scope='session')
def cache():
    return {}

@pytest.fixture
def resource(cache, tmp_path):
    if 'r' not in cache:
        cache['r'] = build(tmp_path)
    yield cache['r']
   ```

## 无效尝试

- **** — Defeats the purpose of sharing expensive setup; tests slow down dramatically. (50% 失败率)
- **** — Raises the same ScopeMismatch at runtime; getfixturevalue does not change scopes. (85% 失败率)
