A utility library for mocking out the requests Python library
—
The core RequestsMock class provides programmatic control over response mocking, including registry management, call tracking, and advanced configuration options. This is the underlying implementation used by the decorator and module-level functions.
Create RequestsMock instances with custom configuration for advanced mocking scenarios.
class RequestsMock:
def __init__(
self,
assert_all_requests_are_fired=True,
response_callback=None,
passthru_prefixes=(),
target="requests.adapters.HTTPAdapter.send",
registry=FirstMatchRegistry,
*,
real_adapter_send=None
):
"""
Create a RequestsMock instance.
Parameters:
- assert_all_requests_are_fired: bool, raise error if registered responses unused
- response_callback: function to modify all responses before returning
- passthru_prefixes: tuple of URL prefixes to pass through to real servers
- target: string path to the method being patched
- registry: registry class for managing response matching order
- real_adapter_send: custom real HTTP adapter function
The RequestsMock instance can be used as a context manager or manually
controlled with start()/stop() methods.
"""Use RequestsMock as a context manager for automatic lifecycle management.
Usage Example:
def test_context_manager():
with responses.RequestsMock() as rsps:
rsps.add(
responses.GET,
"http://api.example.com/data",
json={"context": "manager"}
)
response = requests.get("http://api.example.com/data")
assert response.json()["context"] == "manager"
# Outside context manager, real requests would work normallyManually start and stop mocking for fine-grained control over when mocking is active.
def start(self):
"""
Start response mocking by patching the HTTP adapter.
Patches the target method to intercept HTTP requests.
Can be called multiple times safely - subsequent calls are ignored.
"""
def stop(self, allow_assert=True):
"""
Stop response mocking and restore original HTTP adapter.
Parameters:
- allow_assert: bool, whether to run assertion checks on unused responses
If assert_all_requests_are_fired is True and allow_assert is True,
raises AssertionError for any registered responses that weren't used.
"""Usage Example:
def test_manual_control():
mock = responses.RequestsMock()
try:
mock.start()
mock.add(responses.GET, "http://api.example.com/manual", json={"manual": True})
response = requests.get("http://api.example.com/manual")
assert response.json()["manual"] is True
finally:
mock.stop()The RequestsMock instance provides the same response registration methods as the module-level functions.
def add(self, method=None, url=None, body="", adding_headers=None, *args, **kwargs):
"""Add a response. Same interface as module-level add() function."""
def add_callback(self, method, url, callback, match_querystring=False, content_type="text/plain", match=()):
"""Add a callback response. Same interface as module-level add_callback() function."""
# HTTP method shortcuts
def get(self, url, **kwargs): ...
def post(self, url, **kwargs): ...
def put(self, url, **kwargs): ...
def patch(self, url, **kwargs): ...
def delete(self, url, **kwargs): ...
def head(self, url, **kwargs): ...
def options(self, url, **kwargs): ...Methods for managing registered responses and mock state.
def remove(self, method_or_response=None, url=None):
"""Remove registered responses. Same interface as module-level function."""
def replace(self, method_or_response=None, url=None, body="", *args, **kwargs):
"""Replace existing response. Same interface as module-level function."""
def upsert(self, method_or_response=None, url=None, body="", *args, **kwargs):
"""Add or replace response. Same interface as module-level function."""
def reset(self):
"""Clear all registered responses and reset call history."""
def registered(self):
"""
Get list of all registered responses.
Returns:
List of BaseResponse objects currently registered
"""Configure URLs that should pass through to real servers instead of being mocked.
def add_passthru(self, prefix):
"""
Register URL prefix or regex pattern for passthrough to real servers.
Parameters:
- prefix: str or compiled regex Pattern
URL prefix that should pass through to real servers
Requests matching these prefixes bypass mocking and hit real endpoints.
"""
@property
def passthru_prefixes(self):
"""
Tuple of URL prefixes configured for passthrough.
Returns:
Tuple of strings and/or regex Patterns
"""Usage Example:
def test_passthrough():
with responses.RequestsMock() as rsps:
# Mock some endpoints
rsps.add(responses.GET, "http://api.example.com/mock", json={"mocked": True})
# Allow real requests to external service
rsps.add_passthru("http://httpbin.org")
# This hits the mock
mock_resp = requests.get("http://api.example.com/mock")
assert mock_resp.json()["mocked"] is True
# This would hit the real server (if network available)
# real_resp = requests.get("http://httpbin.org/get")Access recorded requests and verify call patterns.
@property
def calls(self):
"""
CallList of all requests made while mocking was active.
Returns:
CallList object containing Call namedtuples with request/response pairs
"""
def assert_call_count(self, url, count):
"""
Assert that a URL was called a specific number of times.
Parameters:
- url: str, URL to check
- count: int, expected number of calls
Returns:
True if assertion passes
Raises:
AssertionError if actual call count doesn't match expected count
"""
@property
def assert_all_requests_are_fired(self):
"""
Whether to assert all registered responses were used.
Returns:
bool: Current setting for assertion checking
"""Control how responses are matched and selected using different registry strategies.
def get_registry(self):
"""
Get the current response registry instance.
Returns:
Registry instance (typically FirstMatchRegistry or OrderedRegistry)
"""
def _set_registry(self, new_registry):
"""
Replace the current registry with a new one.
Parameters:
- new_registry: Registry class (not instance)
Raises:
AttributeError if current registry has registered responses
Must call reset() first to clear responses before changing registry
"""Usage Example:
from responses.registries import OrderedRegistry
def test_ordered_responses():
with responses.RequestsMock() as rsps:
# Switch to ordered registry
rsps.reset() # Clear any existing responses
rsps._set_registry(OrderedRegistry)
# Add responses in specific order
rsps.add(responses.GET, "http://api.example.com/data", json={"response": 1})
rsps.add(responses.GET, "http://api.example.com/data", json={"response": 2})
# Responses will be returned in registration order
resp1 = requests.get("http://api.example.com/data")
resp2 = requests.get("http://api.example.com/data")
assert resp1.json()["response"] == 1
assert resp2.json()["response"] == 2Configure a callback that processes all responses before they're returned.
@property
def response_callback(self):
"""
Global callback function applied to all responses.
Returns:
Function that takes a response and returns a modified response, or None
"""
@response_callback.setter
def response_callback(self, callback):
"""
Set global response callback.
Parameters:
- callback: function(response) -> response, or None to disable
The callback receives the generated response and can modify it
before it's returned to the requesting code.
"""Usage Example:
def response_modifier(response):
# Add custom header to all responses
response.headers["X-Mock-Modified"] = "true"
return response
def test_global_callback():
with responses.RequestsMock(response_callback=response_modifier) as rsps:
rsps.add(responses.GET, "http://api.example.com/test", json={"test": True})
response = requests.get("http://api.example.com/test")
assert response.headers["X-Mock-Modified"] == "true"
assert response.json()["test"] is TrueLoad response configurations from YAML files for complex test scenarios.
def _add_from_file(self, file_path):
"""
Load responses from a YAML configuration file.
Parameters:
- file_path: str or Path object to YAML file
The YAML file should contain a 'responses' key with a list of response
configurations matching the add() method parameters.
Example YAML format:
responses:
- response:
method: GET
url: http://api.example.com/data
body: '{"key": "value"}'
status: 200
headers:
Content-Type: application/json
content_type: application/json
auto_calculate_content_length: false
"""The RequestsMock class provides HTTP method constants for use in response registration.
# Class attributes available on RequestsMock instances
GET: str = "GET"
POST: str = "POST"
PUT: str = "PUT"
PATCH: str = "PATCH"
DELETE: str = "DELETE"
HEAD: str = "HEAD"
OPTIONS: str = "OPTIONS"
# Reference to Response class
Response: Type[Response] = Response
# Reference to matchers module
matchers = responses.matchersUsage Example:
def test_instance_constants():
with responses.RequestsMock() as rsps:
# Use constants from the instance
rsps.add(rsps.GET, "http://api.example.com/get", json={"method": "GET"})
rsps.add(rsps.POST, "http://api.example.com/post", json={"method": "POST"})
get_resp = requests.get("http://api.example.com/get")
post_resp = requests.post("http://api.example.com/post")
assert get_resp.json()["method"] == "GET"
assert post_resp.json()["method"] == "POST"Install with Tessl CLI
npx tessl i tessl/pypi-responses