ImportError when trying to mock a module

I have a module that I am testing, which depends on another module that will not be available during testing. To get around this, I wrote (essentially):

import mock import sys sys.modules['parent_module.unavailable_module'] = mock.MagicMock() import module_under_test 

This works fine while module_under_test does one of the following import parent_module , import parent_module.unavailable_module . However, the following code generates a trace:

 >>> from parent_module import unavailable_module ImportError: cannot import name unavailable_module 

What's up with that? What can I do in my test code (without changing the import statement) to avoid this error?

+4
source share
1 answer

Ok, I think I figured it out. It seems that in the statement:

 from parent_module import unavailable_module 

Python is looking for the parent_module attribute called unavailable_module . Therefore, the following installation code completely replaces unavailable_module inside parent_module :

 import mock import sys fake_module = mock.MagicMock() sys.modules['parent_module.unavailable_module'] = fake_module setattr(parent_module, 'unavailable_module', fake_module) 

I tested four import idioms that I know of:

 import parent_module import parent_module.unavailable_module import parent_module.unavailable_module as unavailabe_module from parent_module import unavailable_module 

and each of them worked with the above code.

+2
source

All Articles