Skip to content

Instantly share code, notes, and snippets.

@ludwig
Forked from daragh/module_mocking.py
Created December 15, 2015 11:13
Show Gist options
  • Save ludwig/d6676b88f938c6cd1aa1 to your computer and use it in GitHub Desktop.
Save ludwig/d6676b88f938c6cd1aa1 to your computer and use it in GitHub Desktop.
Example code for mocking a module in Python
'''
Example code to show how it is possible to mock an entire module by patching
the sys.modules dict using mock ( http://www.voidspace.org.uk/python/mock/ ).
'''
from mock import patch, MagicMock
def test_import_patching():
module_mock = MagicMock()
with patch.dict('sys.modules', **{
'unimportable_module': module_mock,
'unimportable_module.submodule': module_mock,
}):
import unimportable_module.submodule
assert unimportable_module.submodule == module_mock.submodule
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment