Skip to content

Instantly share code, notes, and snippets.

@msabramo
Created September 11, 2015 16:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save msabramo/cb545ebdae300d792b48 to your computer and use it in GitHub Desktop.
Save msabramo/cb545ebdae300d792b48 to your computer and use it in GitHub Desktop.
A Python context manager for doing multiple mock.patches
@contextlib.contextmanager
def multiple_mocks(mock_specs):
"""
`mock_specs` is a dict of mock target name => mock patch kwargs
Example usage:
with multiple_mocks(
{'os.path.exists': {'side_effect': mock_path_exists},
'subprocess.Popen': {},
'os.symlink': {}}):
do_stuff()
"""
_mocks = []
for target, mock_patch_kwargs in mock_specs.items():
_mock = mock.patch(target, **mock_patch_kwargs)
_mock.start()
_mocks.append(_mock)
yield
for _mock in _mocks:
_mock.stop()
@theoden-dd
Copy link

We cannot use with multiple_mocks(...) as mocks with that, but nice idea.

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