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 have right now.
some regex to determine if email is valid, returns either True or False
if args == '1':
myMock = mock.patch.object(EmailChecker, 'is_email_correct', side_effect=my_side_effect)
patch.object as decorator or context manager as following code.
>>> class EmailChecker(): ... def is_email_correct(self, email): ... pass ... >>> def my_side_effect(*args): ... if args == '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
*args. added missing
self argument to
my_side_effect could be simplified as follow:
def my_side_effect(email): return email == '1'