0

I have created a an application in python-django, where it makes some api call to some 3rd party services and then return response, post that I am doing some processing on response data and generating some final document. Below is something I am doing:

def get_processed_data(url, payload, tenant, req_id, timeout=None):
    query_kwargs = HTTPRequestUtils.__get_query_kwargs(timeout)
    query_kwargs['json'] = payload
    response = HTTPRequestUtils.__get_response(url, query_kwargs, requests.post)
    .....
    data=process_response(response)
    return more_processings(data)

Abobe is one of the function , being called during actual execution of code. And response varies with url. Now problem is I have am writing Unit Test , and i have to emulate/mock http call, so that for different url, i may return different mocked response, that will be further processed.

I went through several libraries like responses etc, but what I conclude from them is , i can test just api call and its returned response. But in actual I need to just emulate/mock http call for different and return response back, like we do in patch during mock, so that the response can be further go for processing.

Any library or method by which we can achieve this.

KCS
  • 2,937
  • 4
  • 22
  • 32
  • You should use dependency injection https://stackoverflow.com/questions/130794/what-is-dependency-injection to inject a dependency which makes the http requests. Then you can mock the dependency methods and inject it into your function for testing – Daniel Scott Nov 10 '21 at 17:04

1 Answers1

0

If you have an idea of order in which the API call would take place, you can make use of side-effect func of mock library, so what it does is it will give different response for each time the mock function is called

for eg: mock_api.side_effect = [(resp1),(resp2)]

so when api() will be called for the 1st time => response will be resp1 and for the second time ==> response will be resp2

I think this will solve your problem