# FAILED tests/test_state.py::test_second_run - AssertionError：assert 2 == 1
# 单独运行通过，在 tests/test_state.py::test_first_run 之后运行则失败

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

## 根因

测试隔离被破坏：模块级可变对象（缓存、全局变量、类属性或数据库行）被较早的测试修改且未重置。Pytest 的默认收集顺序暴露了这种泄漏。

## 版本兼容性

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

## 解决方案

1. **** (95% 成功率)
   ```
   @pytest.fixture(autouse=True)
def reset_cache():
    from myapp import cache
    cache.clear()
    yield
    cache.clear()
   ```
2. **** (85% 成功率)
   ```
   pip install pytest-forked
pytest --forked tests/test_state.py
   ```
3. **** (90% 成功率)
   ```
   pytest --stepwise tests/test_state.py
# or:
pytest tests/test_state.py::test_first_run tests/test_state.py::test_second_run -v
   ```

## 无效尝试

- **** — Shuffling changes which test fails, not whether tests are isolated; flakiness moves around instead of disappearing. (80% 失败率)
- **** — Reruns the same broken state; if the first run mutated global state, retries still see the mutated value. (85% 失败率)
