If you want to delve into the Python import system, I highly recommend David Bezley's talk .
As for your specific question, here is an example that checks a module when its dependency is missing.
bar.py - the module you want to check when my_bogus_module is missing
from my_bogus_module import foo def bar(x): return foo(x) + 1
mock_bogus.py - file with your tests that will load the mock module
from mock import Mock import sys import types module_name = 'my_bogus_module' bogus_module = types.ModuleType(module_name) sys.modules[module_name] = bogus_module bogus_module.foo = Mock(name=module_name+'.foo')
test_bar.py - tests bar.py when my_bogus_module unavailable
import unittest from mock_bogus import bogus_module
You should probably make this a little safer by setting that my_bogus_module is not actually available when you run the test. You can also look at the pydoc.locate() method, which will try to import something, and return None if it does not work. Apparently this is a public method, but it is not documented.
source share