A utility library for mocking out the requests Python library
npx @tessl/cli install tessl/pypi-responses@0.25.0A utility library for mocking out the requests Python library. Responses enables developers to create isolated unit tests without making actual HTTP calls by intercepting HTTP requests and returning predefined responses. It provides a decorator-based approach supporting all major HTTP methods with customizable status codes, headers, and response bodies.
pip install responsesimport responsesFor direct class usage:
from responses import RequestsMock, Response, CallbackResponseFor matchers:
from responses.matchers import json_params_matcher, query_param_matcherFor registries:
from responses.registries import FirstMatchRegistry, OrderedRegistryFor recording:
from responses import _add_from_file
from responses._recorder import Recorder, recordimport responses
import requests
@responses.activate
def test_simple():
# Register a mock response
responses.add(
responses.GET,
"http://example.com/api/data",
json={"message": "success"},
status=200
)
# Make request - will hit the mock
resp = requests.get("http://example.com/api/data")
assert resp.json() == {"message": "success"}
assert resp.status_code == 200
# Context manager approach
def test_with_context():
with responses.RequestsMock() as rsps:
rsps.add(
responses.POST,
"http://example.com/api/submit",
json={"result": "created"},
status=201
)
resp = requests.post("http://example.com/api/submit", json={"data": "test"})
assert resp.status_code == 201The responses library uses a patching mechanism to intercept requests.adapters.HTTPAdapter.send calls. When a request is made, responses:
The flexible matcher system allows precise control over which requests are intercepted, while the registry system supports different response selection strategies for complex testing scenarios.
Core functionality for registering mock responses and activating the mocking system. Includes decorator-based activation, context manager usage, and HTTP method shortcuts.
@responses.activate
def decorator_function(): ...
def add(method, url, body="", json=None, status=200, headers=None, **kwargs): ...
def get(url, **kwargs): ...
def post(url, **kwargs): ...
def put(url, **kwargs): ...
def patch(url, **kwargs): ...
def delete(url, **kwargs): ...
def head(url, **kwargs): ...
def options(url, **kwargs): ...Advanced request matching capabilities for precise control over which requests are intercepted. Includes matchers for JSON payloads, query parameters, headers, and custom matching logic.
def json_params_matcher(params, *, strict_match=True): ...
def query_param_matcher(params, *, strict_match=True): ...
def header_matcher(headers, strict_match=False): ...
def body_matcher(params, *, allow_blank=False): ...Different types of mock responses including static responses, callback-based dynamic responses, and passthrough responses for selective mocking.
class Response:
def __init__(self, method, url, body="", json=None, status=200, headers=None, **kwargs): ...
class CallbackResponse:
def __init__(self, method, url, callback, **kwargs): ...
class PassthroughResponse:
def __init__(self, *args, **kwargs): ...The core RequestsMock class for programmatic control over response mocking, including registry management, call tracking, and advanced configuration options.
class RequestsMock:
def __init__(self, assert_all_requests_are_fired=True, response_callback=None, **kwargs): ...
def start(self): ...
def stop(self, allow_assert=True): ...
def add_passthru(self, prefix): ...
def assert_call_count(self, url, count): ...Record actual HTTP requests and responses to generate response configurations for future mocking. Enables capturing real API interactions and replaying them in tests.
@record(file_path="responses.yaml")
def function_making_requests(): ...
class Recorder:
def __init__(self, *, target="requests.adapters.HTTPAdapter.send", registry=OrderedRegistry): ...
def record(self, *, file_path="response.yaml"): ...
def dump_to_file(self, file_path, *, registered=None): ...
def _add_from_file(file_path): ...Registry systems that control how responses are matched and selected, including order-dependent response handling for complex testing scenarios.
class FirstMatchRegistry:
def __init__(self): ...
def find(self, request): ...
def add(self, response): ...
def remove(self, response): ...
class OrderedRegistry(FirstMatchRegistry):
def find(self, request): ...# HTTP Method Constants
GET: str = "GET"
POST: str = "POST"
PUT: str = "PUT"
PATCH: str = "PATCH"
DELETE: str = "DELETE"
HEAD: str = "HEAD"
OPTIONS: str = "OPTIONS"
# Call tracking
class Call:
request: PreparedRequest
response: Any
class CallList:
def __len__(self) -> int: ...
def __getitem__(self, index) -> Call: ...
def reset(self) -> None: ...