Skip to content

Instantly share code, notes, and snippets.

@IuryAlves
Last active February 10, 2017 20:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IuryAlves/86903c9251922691ed60f8f4d4d8368c to your computer and use it in GitHub Desktop.
Save IuryAlves/86903c9251922691ed60f8f4d4d8368c to your computer and use it in GitHub Desktop.
Mock something only if condition applies.
# coding: utf-8
import functools
def _mock_condition(condition, *args, **kwargs):
return condition(*args, **kwargs)
def mock_condition(condition):
"""
mock something only if condition applies.
Mocking os.remove only if file_path is /tmp/mocked.png::
import os
from unittest import mock
def condition(*args, **kwargs):
if '/tmp/mocked.png' in args:
return mock.MagicMock() # return a mock object
return os.remove # return original function
mock_with_condition = mock_condition(condition)
mock.patch('os.remove', new=mock_with_condition)
"""
return functools.partial(condition, _mock_condition)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment