python: mock a module

If you’re always accessing the variables in config.py like this:

import config
...
config.VAR1

You can replace the config module imported by whatever module you’re actually trying to test. So, if you’re testing a module called foo, and it imports and uses config, you can say:

from mock import patch
import foo
import config_test
....
with patch('foo.config', new=config_test):
   foo.whatever()

But this isn’t actually replacing the module globally, it’s only replacing it within the foo module’s namespace. So you would need to patch it everywhere it’s imported. It also wouldn’t work if foo does this instead of import config:

from config import VAR1

You can also mess with sys.modules to do this:

import config_test
import sys
sys.modules["config"] = config_test
# import modules that uses "import config" here, and they'll actually get config_test

But generally it’s not a good idea to mess with sys.modules, and I don’t think this case is any different. I would favor all of the other suggestions made over it.

Leave a Comment