python
data_error
ai_generated
true
FAILED tests/test_state.py::test_reads_cache - KeyError: 'user:1' (使用 `pytest -p no:randomly` 通过,随机顺序失败)
FAILED tests/test_state.py::test_reads_cache - KeyError: 'user:1' (Passes with `pytest -p no:randomly`, fails with random order)
ID: python/pytest-random-order-flaky
80%修复率
84%置信度
0证据数
2024-11-02首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
pytest-randomly 每次运行打乱测试顺序;某测试依赖其他测试创建的状态(共享缓存、模块全局、数据库行),因此先运行时失败。
English
pytest-randomly shuffles test order each run; a test depends on state created by another test (shared cache, module global, DB row), so it fails when it runs first.
解决方案
-
93% 成功率
Make the test self-contained with a fixture that seeds the cache: @pytest.fixture def seeded_cache(cache): cache.set('user:1', {'name': 'alice'}) return cache def test_reads_cache(seeded_cache): assert seeded_cache.get('user:1')['name'] == 'alice' -
90% 成功率
Or reset shared state between tests: @pytest.fixture(autouse=True) def clean_cache(cache): cache.flush_all() yield cache.flush_all()
无效尝试
常见但无效的做法:
-
85% 失败
pytest-randomly ignores order markers unless `-p no:randomly` is set; the shuffle still happens.
-
70% 失败
Makes the order deterministic but still hides the inter-test dependency; a different seed on CI breaks it.