responses
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
- breaking In version 0.26.0, the behavior of `assert_all_requests_are_fired=True` (the default when using `responses.activate` as a context manager or decorator) changed. Assertions about unfired requests are now raised even if an exception occurs within the context manager or decorated function. Previously, these assertions were suppressed, which could hide uncalled mocks.
- deprecated Direct access to `assert_all_requests_are_fired`, `passthru_prefixes`, and `target` from the top-level `responses` module (e.g., `responses.assert_all_requests_are_fired`) is deprecated.
- deprecated The `match_querystring` argument in `Response` and `CallbackResponse` is deprecated.
- gotcha By default, `responses.add` assumes a mock should be consumed once. If `assert_all_requests_are_fired=True` (the default) is active, calling the same URL multiple times with a single `responses.add` definition will cause an `AssertionError` after the first call.
- gotcha Prior to version 0.25.0, `matchers.header_matcher` did not correctly fail if a header specified in the matcher was entirely missing from the request; it only validated the value of present headers.
- gotcha When using `responses` alongside other network mocking libraries (e.g., `httpretty`, `moto`) or attempting to make actual network calls within the same test context, conflicts can arise as `responses` extensively patches the `requests` library.
Install
-
pip install responses
Imports
- responses
import responses
- activate
from responses import activate
- matchers
from responses import matchers
Quickstart
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.")