ImportError: No module named mock
So I am trying to use unittest.mock to mock some of my methods in my unit tests. I do:
from unittest.mock import MagicMock
f = open("data/static/mock_ffprobe_response")
subprocess.check_output = MagicMock(return_value=f.read())
f.close()
But I am getting:
ImportError: No module named mock
I tried:
pip install mock
It's still not working.
unittest
is a built-in module; mock
is an external library (pre-3.3 betas, anyway). After installing mock
via pip install
, you import it not by using
from unittest.mock import MagicMock
but
from mock import MagicMock
Edit: mock
has been included in the unittest
module (since Python3.3), and can be imported by import unittest.mock
.
For Python 2.7:
Install mock:
pip install mock
Then in the test code, use this import:
from mock import patch, MagicMock
If you want to support both, Python 2 and Python 3, you can also use following:
import sys
if sys.version_info >= (3, 3):
from unittest.mock import MagicMock
else:
from mock import MagicMock
or, if you don't want to import sys
try:
from unittest.mock import MagicMock
except ImportError:
from mock import MagicMock
If you're using Python 3.3+, change
import mock
to
from unittest import mock
On older versions of Python, don't change anything in the code and run this shell command instead:
pip install mock
This import error happens because unittest.mock
was added in Python 3.3, and there is a backport on PyPI for older Python versions. So if your code used to be Python 2, it's probably trying to import the backport.
pyupgrade
is a tool you can run on your code to rewrite those imports and remove other no-longer-useful leftovers from Python 2.