ImportError: No module named mock ImportError: No module named mock python python

ImportError: No module named mock


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 sysif sys.version_info >= (3, 3):    from unittest.mock import MagicMockelse:    from mock import MagicMock

or, if you don't want to import sys

try:    from unittest.mock import MagicMockexcept ImportError:    from mock import MagicMock