python
runtime_error
ai_generated
true
AttributeError: <class 'myapp.models.User'> does not have the attribute 'save'
ID: python/unittest-mock-patch-object-not-found
80%Fix Rate
85%Confidence
0Evidence
2024-06-20First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.12 | active | — | — | — |
Root Cause
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.
generic中文
patch.object 用于修补目标对象上不存在的属性。如果方法是继承的或动态定义的,就会发生这种情况。
Workarounds
-
90% success
with patch.object(User, 'save', create=True) as mock_save: ... -
85% success
If save is inherited from BaseModel, patch that: patch.object(BaseModel, 'save')
Dead Ends
Common approaches that don't work:
-
70% fail
patch also requires the attribute to exist unless create=True is used.
-
80% fail
This changes production code to satisfy a test, which is not ideal.