python
config_error
ai_generated
true
类型错误:无法模拟 'module' 对象的属性 'requests';请改用 patch.object()
TypeError: cannot mock attribute 'requests' of 'module' object; use patch.object() instead
ID: python/unittest-mock-patch-import-order
80%修复率
85%置信度
0证据数
2025-02-14首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.9 | active | — | — | — |
根因分析
当 'requests' 是模块级导入而不是模块对象的属性时,使用 @patch('module.requests'),通常是由于导入顺序或命名空间问题。
English
Using @patch('module.requests') when 'requests' is a module-level import and not an attribute of the module object, often due to import order or namespace issues.
解决方案
-
90% 成功率
Use patch.object(module, 'requests') to mock the attribute directly on the module object.
-
85% 成功率
Patch the module where it is used: e.g., patch('module.requests.get') if you want to mock a specific method.
无效尝试
常见但无效的做法:
-
50% 失败
Changing the import to 'from module import requests' and patching 'module.requests' may still fail if the import is inside a function.
-
60% 失败
Using patch('requests') instead of 'module.requests' patches the global requests module, which may affect other tests.