python runtime_error ai_generated true

AttributeError: 'NoneType' 对象没有属性 'get'

AttributeError: 'NoneType' object has no attribute 'get'

ID: python/pytest-patch-stopall-early

其他格式: JSON · Markdown 中文 · English
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.

generic

解决方案

  1. 95% 成功率
    Use context managers or decorators so patches are scoped automatically:
    
    @patch('mymod.dep')
    def test_x(mock_dep):
        ...
  2. 90% 成功率
    Use `addCleanup` to stop patches at the right time:
    
    self.addCleanup(patcher.stop)

无效尝试

常见但无效的做法:

  1. 80% 失败

    tearDown runs after each test, so the same problem persists across tests in the class.

  2. 70% 失败

    Hard to detect failure reliably; patches still leak between tests.