python runtime_error ai_generated true

AssertionError: 预期 'send_email' 被调用一次。实际调用 0 次。

AssertionError: Expected 'send_email' to have been called once. Called 0 times.

ID: python/pytest-mock-not-called

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

版本兼容性

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

根因分析

被 mock 的函数未被调用,因为被测代码使用了不同的引用(例如直接导入),或者测试逻辑没有到达调用点。

English

The mocked function was not called because the code under test uses a different reference (e.g., imported directly) or the test logic does not reach the call.

generic

解决方案

  1. 95% 成功率
    If myapp/service.py has 'from myapp.utils import send_email', patch 'myapp.service.send_email'.
    If it has 'import myapp.utils', patch 'myapp.utils.send_email'.
  2. 90% 成功率
    Add a print before the call in the source code, or use pdb to step through.

无效尝试

常见但无效的做法:

  1. 85% 失败

    The patch must target where the function is looked up, not where it's defined.

  2. 80% 失败

    May not work if the code uses a module-level import.