python config_error ai_generated true

AttributeError: <module 'app.services' from '/app/services.py'> does not have the attribute 'send_email'

ID: python/pytest-mock-patch-target

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-05-08First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8 active — — —
3.12 active — — —

Root Cause

patch() targets a name that does not exist in the module at patch time, usually because the function is imported under a different name, lives in another module, or the import happens at call time.

generic

中文

patch() 在打补丁时指向了模块中不存在的名称,通常因为函数以不同名称导入、位于另一个模块或调用时才导入。

Workarounds

  1. 92% success
    Patch where the name is looked up (the consumer module):
    
    with patch('app.notifications.send_email') as m:
        notify_user()
        m.assert_called_once()
  2. 88% success
    Verify the actual attribute name:
    
    python -c "import app.services; print([n for n in dir(app.services) if 'email' in n])"

Dead Ends

Common approaches that don't work:

  1. 85% fail

    create=True adds the attribute for the mock but does not change the code under test, so the real function is still called.

  2. 80% fail

    If the consumer did `from x import send_email`, patching x.send_email does not affect the local reference.