python runtime_error ai_generated true

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

ID: python/pytest-mock-not-called

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8 active
3.12 active

Root Cause

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

中文

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

Workarounds

  1. 95% success
    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% success
    Add a print before the call in the source code, or use pdb to step through.

Dead Ends

Common approaches that don't work:

  1. 85% fail

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

  2. 80% fail

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