Jonathan Jonathan - 7 months ago 12
Python Question

How to mock an import

Module

A
includes
import B
at its top. However under test conditions I'd like to mock
B
in
A
(mock
A.B
) and completely refrain from importing
B
. In fact,
B
isn't installed in the test environment on purpose.

How could this be done?

Answer

You can assign to sys.modules['B'] before importing A to get what you want:

test.py:

import sys
sys.modules['B'] = __import__('mock_B')
import A

print(A.B.__name__)

A.py:

import B

Note B.py does not exist, but when running test.py no error is returned and print(A.B.__name__) prints mock_B. You still have to create a mock_B.py where you mock B's actual functions/variables/etc. Or you can just assign a Mock() directly:

test.py:

import sys
sys.modules['B'] = Mock()
import A