python
attribute_error
ai_generated
true
属性错误:<module 'myapp' from '...'> 没有属性 'config'
AttributeError: <module 'myapp' from '...'> does not have attribute 'config'
ID: python/unittest-mock-patch-object-attribute
80%修复率
86%置信度
0证据数
2025-10-12首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.9 | active | — | — | — |
| 3.10 | active | — | — | — |
根因分析
在 patch.object 中指定了不存在的属性,或模块被错误导入。
English
在 patch.object 中指定了不存在的属性,或模块被错误导入。
解决方案
-
90% 成功率
在测试前 `hasattr(myapp, 'config')`,确保存在再 patch。
-
85% 成功率
`patch('myapp.config')` 如果属性在模块级别。
无效尝试
常见但无效的做法:
-
70% 失败
修改生产代码,且可能不需要。
-
60% 失败
patch 需要字符串路径,可能同样出错。