How to write a unit test code for functions which make API requests to web?

Viewed 709

I am writing unit-test code with pytest for my python functions. Those functions work with requests module that allows us to easily talk to the web servers. The thing is that the web server to which the functions communicate don't return same value. For example, the functions communicate to www.toolmarket.com to ask how much Tommy drill is. But sometimes, Tommy drill is not in the list of the web shop. In this case, My test code returns f. How can I write test code for this kind of function of code?


Edit : added test code

def test_get_data():
    assert Info(None, None, None).get_data("Tommy drill") == (
        "id" : "KRG552100411"
    )

I want to do test like above. Tommy drill is just one of items in the shop. But the thing is sometimes, the item disappears from the list. So test returns f

1 Answers

The above code snippet looks like unit testing. And, since you are using requests module in the actual code, it is better you MOCK the API calls while writing the unit-tests.

It doesn't make an API call from the test function because we use a python mock. With mock, we use @patch and specify python where we are actually making an API call so that it knows what to mock.

It is validating the code if it can process the response. As a reason why, we don't want to make an API call to an external service every time we do unit testing.

To summarise -

When you make the actual API call, you're not doing unit testing, that's more like integration testing

When you want to do unit testing, you're testing if your code can accept and process the expected API call response without actually making the call. You do this by using a mocking library (for example the 'responses' library, which injects mock responses to calls made by requests.

If this helps, I would be happy to help on Python Mocking of API requests too.

Related