python
module_error
ai_generated
true
AttributeError: module 'unittest' has no attribute 'mock'
ID: python/attributeerror-unittest-no-mock
80%Fix Rate
87%Confidence
0Evidence
2024-03-10First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.2 | active | — | — | — |
| 3.3 | active | — | — | — |
| 3.4 | active | — | — | — |
Root Cause
In Python 3.2 and earlier, mock is not part of unittest; must import mock separately or use unittest.mock in Python 3.3+.
generic中文
在 Python 3.2 及更早版本中,mock 不是 unittest 的一部分;必须单独导入 mock 或在 Python 3.3+ 中使用 unittest.mock。
Workarounds
-
95% success Import mock from unittest for Python 3.3+
from unittest.mock import Mock, patch
-
90% success Use backport mock for older Python
pip install mock; then from mock import Mock, patch
Dead Ends
Common approaches that don't work:
-
Installing mock via pip
60% fail
mock is available as a backport but not integrated into unittest; import path is different.
-
Using unittest.mock without importing
80% fail
If Python version is < 3.3, unittest.mock does not exist.