Reputation: 3163
I have an import in the format:
from a.b.c.d import x
in foo.py. I am testing bla.py, which does not import foo.py directly, but indirectly in one of its methods. Something like:
bla.m1() --> bla2.m2() --> foo.m3()
In my test environment, package "a" is not available and I'd like to mock it so that the import does not fail during the test. According to How to mock an import, I could do it using:
import sys
from unittest.mock import Mock
sys.modules['a.b.c.d'] = Mock()
The import works in the test code if I'm using Python 3, but it fails when I use Python 2.7 (and the external mock library). Why? How can I make it work in Python 2.7?
Upvotes: 3
Views: 1660
Reputation: 11060
For Python 2.7 you need to explicitly create each level of the mocked module as something 'truthy' - as python check that the object exists (even if it doesn't actually do anything with it.
The easiest option is to also make them Mock
methods, in case you ever want to test them:
import sys
from mock import Mock
sys.modules['a'] = Mock()
sys.modules['a.b'] = Mock()
sys.modules['a.b.c'] = Mock()
from a.b.c import d
print(d)
<Mock name='mock.d' id='140035843407120'>
However the following is also perfectly valid:
import sys
from mock import Mock
sys.modules['a'] = 'cat'
sys.modules['a.b'] = 1
sys.modules['a.b.c'] = Mock()
from a.b.c import d
print(d)
<Mock name='mock.d' id='1402443407120'>
Upvotes: 2