python
module_error
ai_generated
true
AttributeError: 模块 'unittest' 没有属性 'mock'
AttributeError: module 'unittest' has no attribute 'mock'
ID: python/unittest-module-has-no-attribute-mock
80%修复率
87%置信度
0证据数
2024-01-20首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.11 | active | — | — | — |
| 3.12 | active | — | — | — |
根因分析
unittest.mock 是一个子模块,必须显式导入;仅 `import unittest` 不会暴露 `unittest.mock`,且在某些环境中名为 unittest.py 的本地文件会遮蔽标准库。
English
unittest.mock is a submodule that must be imported explicitly; `import unittest` alone does not expose `unittest.mock`, and in some environments a local file named unittest.py shadows the stdlib.
解决方案
-
98% 成功率
from unittest import mock # or from unittest.mock import patch, MagicMock with patch('module.func') as m: m.return_value = 42 -
90% 成功率
python -c "import unittest; print(unittest.__file__)" # If it prints a path inside your project, rename that file (e.g. unittest_local.py).
无效尝试
常见但无效的做法:
-
50% 失败
If a local unittest.py shadows the stdlib, this imports the local file and still lacks .mock.
-
80% 失败
Star import does not import submodules and is discouraged; mock is still not bound.