python
runtime_error
ai_generated
true
AttributeError: 'NoneType' 对象没有属性 'get'
AttributeError: 'NoneType' object has no attribute 'get'
ID: python/pytest-patch-stopall-early
80%修复率
85%置信度
0证据数
2025-08-11首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.10 | active | — | — | — |
| 3.12 | active | — | — | — |
根因分析
测试在 `finally` 块中调用 `patch.stopall()`,这会移除同一类中 `setUp` 为后续测试设置的 patch。后续测试看到的是真实对象(或 None),而不是 mock。
English
A test calls `patch.stopall()` in a `finally` block, which removes patches set up by `setUp` for subsequent tests in the same class. Later tests see the real (or None) object instead of the mock.
解决方案
-
95% 成功率
Use context managers or decorators so patches are scoped automatically: @patch('mymod.dep') def test_x(mock_dep): ... -
90% 成功率
Use `addCleanup` to stop patches at the right time: self.addCleanup(patcher.stop)
无效尝试
常见但无效的做法:
-
80% 失败
tearDown runs after each test, so the same problem persists across tests in the class.
-
70% 失败
Hard to detect failure reliably; patches still leak between tests.