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

- **ID:** `python/pytest-mock-patch-wrong-target`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.10 | active | — | — |
| 3.12 | active | — | — |

## 解决方案

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')
   ```

## 无效尝试

- **** — The module under test already bound the name at import time; patching the definition site does not affect the bound reference. (80% 失败率)
- **** — Creates a fake attribute on the module, but the code under test still calls the original binding, so the mock is never invoked. (75% 失败率)
