Search code examples
pythonunit-testingmockingmagicmock

Mocking Python function according to different input arguments unittest python


I have a utility function that takes the argument case and return the value accordingly

helper.py
def get_sport_associated_value(dictionary, category, case):
    if case == 'type':
        return "soccer"
    else: 
        return 1 #if case = 'id'

I have a main function that use the above function

crud_operations.py
def get_data(category):
    dictionary ={.....}
    id =  get_sport_associated_value(dictionary, category, 'id')
    .....
    .....
    type = get_sport_associated_value(dictionary, category, 'type')
    ....
    return "successful"

Now I am unittesting the get_data() module using the unittest.Mock. I am having trouble passing the values to id and type.

@mock.patch('helper.get_sport_associated_value')
def test_get_data(self, mock_sport):
    with app.app_context():
        mock_sport.side_effect = self.side_effect
        mock_sport.get_sport_associated_value("id")
        mock_sport.get_sport_associated_value("type")
        result = get_queries("Soccer")
        asserEquals(result, "successful")

 def side_effect(*args, **kwargs):
     if args[0] == "type":
         print("Soccer")
         return "Soccer"
     elif args[0] == "id":
         print("1")
         return 1

I tried this using side_effect function and facing problem to mock the get_sport_associated_value() according to the different values of input argument.

Question 2 : Which is the best method to use mock or mock.magicmock in this scenario?

Any help is appreciated with unit testing Thanks


Solution

  • You're incorrectly testing args[0] as a case. The arguments of the side_effect callback function should be the same as the function you want to mock:

    def side_effect(dictionary, category, case):
        if case == "type":
            return "Soccer"
        elif case == "id":
            return 1