Python Patch Object With A Side_effect
I'm trying to have a Mock object return certain values based on the input given. I looked up a few examples on SO and for some reason I still can't get it to work. Here's what I ha
Solution 1:
Use patch.object
as a decorator or context manager, as in the following code:
>>> class EmailChecker():
... def is_email_correct(self, email):
... pass
...
>>> def my_side_effect(*args):
... if args[0] == '1':
... return True
... else:
... return False
...
>>> with mock.patch.object(EmailChecker, 'is_email_correct', side_effect=my_side_effect):
... checker = EmailChecker()
... print(checker.is_email_correct('1'))
... print(checker.is_email_correct('2'))
...
True
False
NOTE: Replaced **args
with *args
. Added missing self
argument to is_email_correct
method.
my_side_effect
could be simplified as follows:
def my_side_effect(email):
return email == '1'
Post a Comment for "Python Patch Object With A Side_effect"