python
runtime_error
ai_generated
true
AttributeError: 'NoneType' object has no attribute 'get'
ID: python/pytest-patch-stopall-early
80%Fix Rate
85%Confidence
0Evidence
2025-08-11First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.10 | active | — | — | — |
| 3.12 | active | — | — | — |
Root Cause
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.
generic中文
测试在 `finally` 块中调用 `patch.stopall()`,这会移除同一类中 `setUp` 为后续测试设置的 patch。后续测试看到的是真实对象(或 None),而不是 mock。
Workarounds
-
95% success
Use context managers or decorators so patches are scoped automatically: @patch('mymod.dep') def test_x(mock_dep): ... -
90% success
Use `addCleanup` to stop patches at the right time: self.addCleanup(patcher.stop)
Dead Ends
Common approaches that don't work:
-
80% fail
tearDown runs after each test, so the same problem persists across tests in the class.
-
70% fail
Hard to detect failure reliably; patches still leak between tests.