python runtime_error ai_generated true

AttributeError: <module 'app.services.user'> 没有属性 'send_email'

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

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

其他格式: JSON · Markdown 中文 · English
80%修复率
90%置信度
0证据数
2024-04-03首次发现

版本兼容性

版本状态引入弃用备注
3.10 active — — —
3.12 active — — —

根因分析

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

English

`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

解决方案

  1. 95% 成功率
    Patch where the name is used:
    
    from unittest.mock import patch
    
    @patch('app.services.user.send_email')
    def test_signup(mock_send):
        ...
  2. 85% 成功率
    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')

无效尝试

常见但无效的做法:

  1. 80% 失败

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

  2. 75% 失败

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