python config_error ai_generated true

AttributeError: <模块 'app.services'> 没有属性 'send_email'

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

ID: python/pytest-mock-patch-target

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

版本兼容性

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

根因分析

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

English

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

解决方案

  1. 92% 成功率
    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% 成功率
    Verify the actual attribute name:
    
    python -c "import app.services; print([n for n in dir(app.services) if 'email' in n])"

无效尝试

常见但无效的做法:

  1. 85% 失败

    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% 失败

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