python module_error ai_generated true

属性错误:模块 'module_name' 没有属性 'function_name'

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

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

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

版本兼容性

版本状态引入弃用备注
3.x active

根因分析

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

English

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

generic

解决方案

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

无效尝试

常见但无效的做法:

  1. 80% 失败

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

  2. 70% 失败

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