python runtime_error ai_generated true

AttributeError: <module 'app.services.user'> does not have the attribute 'send_email'

ID: python/pytest-mock-patch-wrong-target

Also available as: JSON · Markdown · 中文
80%Fix Rate
90%Confidence
0Evidence
2024-04-03First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.10 active — — —
3.12 active — — —

Root Cause

`patch('app.services.user.send_email')` fails when the name is imported into the module under test from elsewhere. Patch must target the name *where it is looked up* (the consumer module), not where it is defined.

generic

中文

当被测模块通过 `from x import send_email` 导入名称时,`patch('app.services.user.send_email')` 会失败。patch 必须指向名称被查找的位置(使用方模块),而不是定义它的位置。

Workarounds

  1. 95% success
    Patch where the name is used:
    
    from unittest.mock import patch
    
    @patch('app.services.user.send_email')
    def test_signup(mock_send):
        ...
  2. 85% success
    Change the import in the production module to a module-level reference and patch the module:
    
    # app/services/user.py
    from app import notifications
    notifications.send_email(...)
    
    # test
    patch('app.services.user.notifications.send_email')

Dead Ends

Common approaches that don't work:

  1. 80% fail

    The module under test already bound the name at import time; patching the definition site does not affect the bound reference.

  2. 75% fail

    Creates a fake attribute on the module, but the code under test still calls the original binding, so the mock is never invoked.