Skip to content

Instantly share code, notes, and snippets.

@daragh
Created September 10, 2012 15:45
Show Gist options
  • Save daragh/3691654 to your computer and use it in GitHub Desktop.
Save daragh/3691654 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
@posener
Copy link

posener commented Sep 18, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment