Mocking Responses in Python Requests

Lately, we’ve been trying to improve our testing structure around testing our API calls without actually having to make them. To do this we of course use the excellent mocking library for python.

We commonly don’t just return the raw data from calls but rather wrap them, usually converting them to pure python objects for easier consumption by our applications. Because of this we really need to have the ability to mock the raw response and then test that against what we think the wrapper will do with the data.

Since we use python requests to make all our outbound calls, this is somewhat easy.

{% highlight python %} @mock.patch(‘requests.Session.request’) def test_get_wid_mocked(self, mock_method): data = test_data.IDM # Test data mock_response = mock.Mock() mock_response.json.return_value = data # Sets response.json() mock_method.return_value = mock_response

self.assertEqual(self.api.get_wid(eid='example'), '09078645')

{% endhighlight %}

The one caveat is that we must mock the return value of the .json attribute of the request class. This isn’t immediately obvious, but once discovered this opened up our ability to test deeper within the codebase.