Created
September 11, 2015 19:42
-
-
Save msabramo/dffa53e4f29ec2e3682e to your computer and use it in GitHub Desktop.
Mock patch multiple targets in Python
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_targets(mock_patches): | |
""" | |
`mock_patches` is a list (or iterable) of mock.patch objects | |
Example usage: | |
with mock.patch.multiple_targets([ | |
mock.patch('os.path.exists', side_effect=mock_path_exists), | |
mock.patch('subprocess.Popen'), | |
mock.patch('os.mkdir'), | |
mock.patch('os.symlink')]): | |
do_stuff() | |
Or if you need to do stuff with the mock objects: | |
with mock.patch.multiple_targets([ | |
mock.patch('os.path.exists', side_effect=mock_path_exists), | |
mock.patch('subprocess.Popen'), | |
mock.patch('os.mkdir'), | |
mock.patch('os.symlink')]) as (mpe, msp, mom, mos): | |
""" | |
mocks = [] | |
for mock_patch in mock_patches: | |
_mock = mock_patch.start() | |
mocks.append(_mock) | |
yield mocks | |
for mock_patch in mock_patches: | |
mock_patch.stop() | |
mock.patch.multiple_targets = multiple_targets |
Thank you.
thanks!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!