Backend Development 6 min read

Using requests-mock to Simulate HTTP Requests in Python Unit Tests

This guide introduces the Python requests‑mock library, explains how to install it, and provides ten detailed code examples demonstrating how to mock GET, POST, status codes, regex URLs, multiple responses, JSON payloads, HEAD requests, exceptions, query parameters, and redirects for reliable unit testing.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Using requests-mock to Simulate HTTP Requests in Python Unit Tests

requests-mock is a Python library that allows you to mock HTTP requests made with the requests library, making unit and integration tests faster and more reliable by avoiding real external API calls.

Install the library via pip:

pip install requests-mock

1. Simple GET request mock

import requests
import requests_mock

def test_simple_get():
    with requests_mock.Mocker() as m:
        m.get('http://test.com/api/v1/users', text='{"users":[]}')
        response = requests.get('http://test.com/api/v1/users')
        assert response.text == '{"users":[]}'

test_simple_get()

2. POST request mock and verify request body

def test_post_request():
    with requests_mock.Mocker() as m:
        m.post('http://test.com/api/v1/users', text='User created', status_code=201)
        response = requests.post('http://test.com/api/v1/users', json={'username': 'testuser'})
        assert m.last_request.json() == {'username': 'testuser'}
        assert response.text == 'User created'

test_post_request()

3. Mock different status code response

def test_status_code():
    with requests_mock.Mocker() as m:
        m.get('http://test.com/api/v1/resource', status_code=404)
        response = requests.get('http://test.com/api/v1/resource')
        assert response.status_code == 404

test_status_code()

4. Use regular expression to match URLs

import re

def test_regex_url():
    with requests_mock.Mocker() as m:
        m.get(re.compile(r'http://test.com/api/v1/users/\d+'), text='User details')
        response = requests.get('http://test.com/api/v1/users/123')
        assert response.text == 'User details'

test_regex_url()

5. Multiple calls with different responses

def test_multiple_responses():
    with requests_mock.Mocker() as m:
        m.get('http://test.com/api/v1/toggle', [{'text': 'On'}, {'text': 'Off'}])
        response1 = requests.get('http://test.com/api/v1/toggle')
        response2 = requests.get('http://test.com/api/v1/toggle')
        assert response1.text == 'On'
        assert response2.text == 'Off'

test_multiple_responses()

6. Mock JSON response

def test_json_response():
    with requests_mock.Mocker() as m:
        m.get('http://test.com/api/v1/config', json={'key': 'value'})
        response = requests.get('http://test.com/api/v1/config')
        assert response.json()['key'] == 'value'

test_json_response()

7. Handle HEAD request

def test_head_request():
    with requests_mock.Mocker() as m:
        m.head('http://test.com/api/v1/check', headers={'ETag': '123abc'})
        response = requests.head('http://test.com/api/v1/check')
        assert response.headers['ETag'] == '123abc'

test_head_request()

8. Simulate exceptions

def test_exception():
    with requests_mock.Mocker() as m:
        m.get('http://test.com/api/v1/error', exc=requests.exceptions.HTTPError)
        try:
            requests.get('http://test.com/api/v1/error')
        except requests.exceptions.HTTPError:
            assert True
        else:
            assert False

test_exception()

9. Mock request with query parameters

def test_query_params():
    with requests_mock.Mocker() as m:
        m.get('http://test.com/api/v1/search', text='Search results', params={'query': 'python'})
        response = requests.get('http://test.com/api/v1/search', params={'query': 'python'})
        assert response.text == 'Search results'

test_query_params()

10. Mock redirect response

def test_redirect():
    with requests_mock.Mocker() as m:
        m.get('http://test.com/api/v1/redirect', status_code=302, headers={'Location': 'http://test.com/api/v1/newpath'})
        response = requests.get('http://test.com/api/v1/redirect', allow_redirects=True)
        assert response.url.endswith('/api/v1/newpath')

test_redirect()
backendUnit TestingHTTP Mockingrequests-mock
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.