python module_error ai_generated true

AttributeError: <module 'unittest' from '.../unittest/__init__.py'> 没有属性 'mock'

AttributeError: <module 'unittest' from '.../unittest/__init__.py'> has no attribute 'mock'

ID: python/unittest-mock-not-callable-import

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

版本兼容性

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

根因分析

测试使用 `import unittest` 后调用 `unittest.mock.patch`,但 `unittest.mock` 不会自动作为属性导入,必须显式导入。

English

The test uses `import unittest` and then `unittest.mock.patch`, but `unittest.mock` is not automatically imported as an attribute. It must be imported explicitly.

generic

解决方案

  1. 97% 成功率
    Import mock explicitly:
    
    import unittest
    from unittest import mock
    
    class TestX(unittest.TestCase):
        @mock.patch('mymodule.func')
        def test_it(self, m):
            ...
  2. 97% 成功率
    Or import the submodule directly:
    
    from unittest.mock import patch, MagicMock

无效尝试

常见但无效的做法:

  1. 95% 失败

    unittest is part of the standard library; installing a PyPI package named 'unittest' either fails or installs an unrelated shim that shadows the stdlib.

  2. 90% 失败

    Modifying the stdlib is fragile and the change is overwritten on interpreter upgrade.