heyitsqi heyitsqi - 6 months ago 18
Python Question

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 have right now.

class EmailChecker():
def is_email_correct(email):
some regex to determine if email is valid, returns either True or False

def my_side_effect(**args):
if args[0] == '1':
return True
else:
return False

myMock = mock.patch.object(EmailChecker, 'is_email_correct', side_effect=my_side_effect)


Yet it doesn't seem to work. What am I missing here?

Answer

Use 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[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 follow:

def my_side_effect(email): 
    return email == '1'
Comments