When you do an import foo
, if sys.modules['foo']
already exists, the interpreter just returns that instead of doing a fresh import.
So, to fake out module1
's import
statement, just get the value filled in before you load module1
. This is a bit hacky, but very simple. For example:
mytest.py:
import sys
import unittest
import my_fake_module
sys.modules['module_i_want_to_fake'] = my_fake_module
import module1
//test code here
module1.some_method()
//test code here
module1.py:
import module_i_want_to_fake
print(module_i_want_to_fake)
This will print out something like this:
<module 'my_fake_module' from 'my_fake_module.pyc'>
If you need to fake out module1
more thoroughly (even if it tries to introspect the module), you can create a new module (via types.ModuleType
) with the code from my_fake_module
but the name 'module_i_want_to_fake'
, and any other changes you want.
If you need to do this more dynamically than can be accomplished by just renaming modules statically in advance, you can build an import hook, as described in PEP 302. This requires you to reimplement a good chunk of the import mechanism, which is a huge pain in 2.x, but importlib
in 3.1+ makes it a lot easier.
Fortunately, usually, you don't need to do either of these.