python
module_error
ai_generated
true
AttributeError: module 'unittest' has no attribute 'mock'
ID: python/unittest-mock-no-attribute
80%Fix Rate
90%Confidence
0Evidence
2024-01-22First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.9 | active | — | — | — |
| 3.11 | active | — | — | — |
| 3.12 | active | — | — | — |
Root Cause
`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.
generic中文
`unittest.mock` 是子模块,必须显式导入。仅写 `import unittest` 后使用 `unittest.mock.patch(...)` 会失败,因为子模块未被加载。
Workarounds
-
98% success
Import the submodule explicitly: from unittest import mock # or import unittest.mock with mock.patch('mymodule.requests.get') as m: ...
Dead Ends
Common approaches that don't work:
-
80% fail
mock has been a submodule since 3.3; version is not the problem, import style is.
-
65% fail
Installing the backport doesn't bind `unittest.mock`; the attribute error persists.