Shubham Shekhar
Shubham Shekhar

Reputation: 199

Mocking API Call in Unit Testing Python 3

I have been given the task to write unit-tests for a function which eventually makes a requests.post API call. I have been asked to use mocking in Python. I am fairly new to it and have been reading lot of articles related to it. I have also written the unit test following the document. But, I do have a few questions which none of the documents I have come across answered-

  1. In unit test function too, I am making a call to the original function which is making the API call. And for now, I am mocking the response using mock.return_value. So, eventually does this make an API call too from the unit-test function?? If it does, then it fails my use-case where I am not supposed to make API calls regularly to third party server.

  2. If it not making an API call, what exactly is it validating? I myself have fed the response and let's say status code of the API call. So, without making the API call, how can these two be validated?

@patch('post.requests.get')
def test_api_function(self, mock_incident):
    mock_incident.return_value.json.return_value = [{'mock':'json'}]
    mock_incident.return_value.status_code = 200
    response = api_fucntion()

    assert response.status_code == 200

If you see, I am still making that call to the function(api_response). How does this serve my purpose of unit testing with mocking?? And, how does it verify 200 response without making an actual API call if it doesn't make one ??

Upvotes: 1

Views: 1718

Answers (1)

Shubham Shekhar
Shubham Shekhar

Reputation: 199

So, looks like I did find answers to the question.

  1. 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.

  2. 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 summarize -

  • 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.

Upvotes: 2

Related Questions