Created
September 11, 2015 16:12
-
-
Save msabramo/cb545ebdae300d792b48 to your computer and use it in GitHub Desktop.
A Python context manager for doing multiple mock.patches
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We cannot use
with multiple_mocks(...) as mocks
with that, but nice idea.