ImportError when attempting to mock a module
mocking, python, unit-testing
Solution
Alright, I think I've figured it out. It appears that in the statement:
from parent_module import unavailable_module
Python looks for an attribute of `parent_module` called `unavailable_module`. Therefore, the following set up code fully replaces `unavailable_module` within `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 the four import idioms of which I am aware:
import parent_module
import parent_module.unavailable_module
import parent_module.unavailable_module as unavailabe_module
from parent_module import unavailable_module
and each worked with the above set up code.
Problem
I have a module that I am testing that depends on another module that won't be available at the time of 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 as long as `module_under_test` is doing one of the following `import parent_module`, `import parent_module.unavailable_module`. However, the following code generates a traceback: ``` >>> from parent_module import unavailable_module ImportError: cannot import name unavailable_module ``` What's up with this? What can I do in my test code (without changing the import statement) to avoid this error?