python
runtime_error
ai_generated
true
AttributeError: <class 'myapp.models.User'> 没有属性 'save'
AttributeError: <class 'myapp.models.User'> does not have the attribute 'save'
ID: python/unittest-mock-patch-object-not-found
80%修复率
85%置信度
0证据数
2024-06-20首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.12 | active | — | — | — |
根因分析
patch.object 用于修补目标对象上不存在的属性。如果方法是继承的或动态定义的,就会发生这种情况。
English
patch.object is used to patch an attribute that does not exist on the target object. This can happen if the method is inherited or defined dynamically.
解决方案
-
90% 成功率
with patch.object(User, 'save', create=True) as mock_save: ... -
85% 成功率
If save is inherited from BaseModel, patch that: patch.object(BaseModel, 'save')
无效尝试
常见但无效的做法:
-
70% 失败
patch also requires the attribute to exist unless create=True is used.
-
80% 失败
This changes production code to satisfy a test, which is not ideal.