responses

0.26.0 · active · verified Sat Mar 28

responses is a utility library designed for mocking out the `requests` Python library, making it easier to test code that performs HTTP requests. It allows developers to register mock responses for specific URLs and HTTP methods, controlling the behavior of `requests` during testing. The library is actively maintained, with frequent releases, and is currently at version 0.26.0.

Warnings

Install

Imports

Quickstart

The quickstart demonstrates mocking a GET request using the `@responses.activate` decorator and `responses.add()` method. It sets up a mock response with a JSON body and then makes a `requests.get()` call, which is intercepted by `responses`. Finally, it asserts the response content and verifies that the mock was called.

import requests
import responses

@responses.activate
def test_example_request():
    responses.add(
        responses.GET,
        'http://example.com/api/test',
        json={'message': 'Hello, World!'},
        status=200,
        content_type='application/json'
    )

    # This request will be intercepted by 'responses'
    resp = requests.get('http://example.com/api/test')

    assert resp.status_code == 200
    assert resp.json() == {'message': 'Hello, World!'}

    # Verify that exactly one request was made to the registered URL
    assert len(responses.calls) == 1
    assert responses.calls[0].request.url == 'http://example.com/api/test'

print("Running test_example_request...")
test_example_request()
print("Test completed successfully.")

view raw JSON →