Fix Python – How to mock an import


Asked By – Jonathan Livni

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.

A is the unit under test. I have to import A with all its functionality. B is the module I need to mock. But how can I mock B within A and stop A from importing the real B, if the first thing A does is import B?

(The reason B isn’t installed is that I use pypy for quick testing and unfortunately B isn’t compatible with pypy yet.)

How could this be done?

Now we will see solution for issue: How to mock an import


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

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


import B

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

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

This question is answered By – Rob Wouters

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0