python runtime_error ai_generated true

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

ID: python/pytest-mock-patch-not-applied

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

The mock was applied to the wrong namespace or the code under test imports the function directly, bypassing the patch.

generic

中文

mock 应用到了错误的命名空间,或被测代码直接导入函数,绕过了 patch。

Workarounds

  1. 95% success
    If my_module.py does 'from other_module import my_func', patch 'my_module.my_func' instead of 'other_module.my_func'.
  2. 90% success
    def test_my_func(monkeypatch):
        monkeypatch.setattr('my_module.my_func', lambda: None)
        # test code
  3. 85% success
    import my_module; print(my_module.my_func.__module__) to see where it's defined, then patch accordingly.

Dead Ends

Common approaches that don't work:

  1. 95% fail

    The test then passes but does not verify the intended behavior; the mock is still not applied.

  2. 90% fail

    If the target is incorrect, patch.object fails similarly.