Skip to content

Instantly share code, notes, and snippets.

@msabramo
Created September 11, 2015 19:42
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msabramo/dffa53e4f29ec2e3682e to your computer and use it in GitHub Desktop.
Save msabramo/dffa53e4f29ec2e3682e to your computer and use it in GitHub Desktop.
Mock patch multiple targets in Python
@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
@kz159
Copy link

kz159 commented Oct 15, 2021

Thanks!

@banagale
Copy link

Thank you.

@ex10se
Copy link

ex10se commented Feb 16, 2023

thanks!

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