Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.