# FAILED tests/test_b.py::test_uses_cache - KeyError: 'user:42'
# 单独运行时通过: pytest tests/test_b.py::test_uses_cache

- **ID:** `python/pytest-flaky-ordering-dependency`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

test_b 依赖 test_a 写入的状态（模块级缓存、全局变量或共享数据库行），pytest 默认按文件顺序运行；单独运行或使用 -p 随机排序会改变顺序。

## 版本兼容性

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

## 解决方案

1. **** (95% 成功率)
   ```
   @pytest.fixture
def seeded_cache(cache):
    cache['user:42'] = {'name': 'Alice'}
    return cache

def test_uses_cache(seeded_cache):
    assert seeded_cache['user:42']['name'] == 'Alice'
   ```
2. **** (85% 成功率)
   ```
   # pyproject.toml
[tool.pytest.ini_options]
addopts = "-p no:randomly"  # only in local dev

# CI:
pytest -p randomly --randomly-seed=random -x
# Then refactor tests that fail only under reordering
   ```

## 无效尝试

- **** — A fixed seed gives the same order locally but CI may use a different seed; the inter-test dependency remains a latent bug. (80% 失败率)
- **** — Couples tests by name and breaks under -p no:randomly or when parallelized with xdist. (75% 失败率)
