python module_error ai_generated true

AttributeError: <module 'module_name' from '/path/to/module.py'> does not have the attribute 'function_name'

ID: python/unittest-mock-patch-wrong-target

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

Mock patch target is incorrect; patching the module path instead of the location where the function is used.

generic

中文

Mock patch 目标错误;修补了模块路径,而不是函数被使用的位置。

Workarounds

  1. 95% success
    @patch('module_where_used.function_name')
    def test_something(mock_func):
        ...
  2. 90% success
    @patch('module_name.function_name', create=True)

Dead Ends

Common approaches that don't work:

  1. 80% fail

    If the function is imported into another module, patching the original module doesn't affect the imported reference.

  2. 70% fail

    patch.object requires an existing attribute; if the attribute doesn't exist, it raises AttributeError.