Search code examples
pythonpython-3.xunit-testingpytesttestcase

When using monkeypatch in Pytest to pass different arguments to the same function or API call, I am observing different responses


I'm currently working with Pytest and I need to understand how to use the monkeypatch feature to mock a function that includes an API call. Specifically, I want to obtain different responses for the function based on varying inputs within a for loop.

Eg:

value_1 = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
value_2 = {'key11': 'value11', 'key22': 'value22' 'key33': 'value33'}

class MockResponse:

    @staticmethod
    def json():
        return load_data("total_res.json")

class GetEntities:
    

   def mock_res(*args, **kwargs):
      return MockResponse().json()

   monkeypatch.setattr(api_funct, "get_data", mock_res)
   
   #test-function which have api call.

Above eg: always send same json file total_res but i need to get different response like value_1 and value_2 based on my different inputs.

Basically mock_res should send with different json file.

Tried below - Not works:

    class MockResponse:
    
        @staticmethod
        def json(data_entry = "total_res.json"):
            if data_entry == "total_res.json":
                return load_data("total_res.json")
            elif data_entry == "value_1":
                return value_1
            elif data_entry == "value_2":
                return value_2
            else:
                print("There is no such data!")
                return None
    
    class GetEntities:
        
    
       def mock_res(data_entry):
          return MockResponse().json(data_entry)
       data_entry = # Type of response to get

       monkeypatch.setattr(api_funct, "get_data", mock_res(data_entry))
       
       #test-function which have api call.

Solution

  • Define an input argument for the json() static function:

    def json(data_entry = "total_res.json"):
            if data_entry == "total_res.json":
                return load_data("total_res.json")
            elif data_entry == "value_1":
                return value_1
            elif data_entry == "value_2":
                return value_2
            else:
                print("There is no such data!")
                return None