Last active
February 10, 2017 20:20
-
-
Save IuryAlves/86903c9251922691ed60f8f4d4d8368c to your computer and use it in GitHub Desktop.
Mock something only if condition applies.
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
# 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