how to mock python requests

Mocking Python Requests

If you are working with Python and want to test your code that involves making HTTP requests, you might want to mock those requests instead of actually making them. This can be useful for several reasons:

  • Testing your code won't depend on external services being available or working correctly.
  • You can simulate different responses from the server to test different scenarios.
  • Your tests will run faster since you don't have to wait for network requests to complete.

Using the unittest.mock Library

One way to mock requests in Python is to use the unittest.mock library. Here's an example:


import unittest.mock as mock
import requests

def test_my_function():
    with mock.patch.object(requests, 'get') as mock_get:
        mock_get.return_value.status_code = 200
        mock_get.return_value.text = 'OK'
        
        result = my_function()
        
        assert result == 'OK'
        mock_get.assert_called_once()

In this example, we are testing a function called my_function which makes an HTTP request using the requests.get method. Instead of actually making the request, we use the mock.patch.object method to replace the requests.get method with a mock object. We then set some attributes on the mock object to simulate a successful response. Finally, we call our function and assert that it returns the expected result and that our mock object was called once.

Using the responses Library

Another way to mock requests in Python is to use the responses library. Here's an example:


import responses
import requests

@responses.activate
def test_my_function():
    responses.add(responses.GET, 'http://example.com', status=200, body='OK')
    
    result = my_function()
    
    assert result == 'OK'
    assert len(responses.calls) == 1

In this example, we use a decorator from the responses library to activate its mocking capabilities. We then use the responses.add method to define a mock response for a specific URL and HTTP method. Finally, we call our function and assert that it returns the expected result and that our mock response was called once.

Conclusion

Mocking requests in Python can be very useful when testing code that makes HTTP requests. The unittest.mock library and the responses library are two popular options for achieving this. Try them out and see which one works best for your needs.