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

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-06-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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

  1. 90% success
    with patch.object(User, 'save', create=True) as mock_save:
        ...
  2. 85% success
    If save is inherited from BaseModel, patch that: patch.object(BaseModel, 'save')

Dead Ends

Common approaches that don't work:

  1. 70% fail

    patch also requires the attribute to exist unless create=True is used.

  2. 80% fail

    This changes production code to satisfy a test, which is not ideal.