python
module_error
ai_generated
true
AttributeError: 模块 'unittest' 没有属性 'mock'
AttributeError: module 'unittest' has no attribute 'mock'
ID: python/unittest-mock-no-attribute
80%修复率
90%置信度
0证据数
2024-01-22首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.9 | active | — | — | — |
| 3.11 | active | — | — | — |
| 3.12 | active | — | — | — |
根因分析
`unittest.mock` 是子模块,必须显式导入。仅写 `import unittest` 后使用 `unittest.mock.patch(...)` 会失败,因为子模块未被加载。
English
`unittest.mock` is a submodule that must be imported explicitly. Writing `import unittest` then `unittest.mock.patch(...)` fails because the submodule isn't loaded until imported.
解决方案
-
98% 成功率
Import the submodule explicitly: from unittest import mock # or import unittest.mock with mock.patch('mymodule.requests.get') as m: ...
无效尝试
常见但无效的做法:
-
80% 失败
mock has been a submodule since 3.3; version is not the problem, import style is.
-
65% 失败
Installing the backport doesn't bind `unittest.mock`; the attribute error persists.