Reputation: 427
I want to patch get_age()
method I have, based on the argument passed.
Let's say I have get_age.py
where I am using multiple times the same get_age()
method.
get_age("Anna")
...
get_age("Ben")
and then in test I want to do:
@patch('get_ages.get_age') <-- mock getting age of Ben
@patch('get_ages.get_age') <-- mock getting age of Anna
def test_get_ages(self, age_A, age_B):
How can I do the mocking of the same method based on the name passed? Thanks!
Upvotes: 2
Views: 1425
Reputation: 11070
This can be achieved using the side_effect
param to patch.object
to call a function which returns a different result depending on the input. For example:
def find_ages(*args):
if args[0] == 'Anna':
# Return Anna's data
return 18
elif args[0] == ' Ben':
# Return Ben's data
return 45
@patch.object(get_ages, 'get_age', side_effect=find_ages)
def test_get_ages(self, get_age):
Upvotes: 2