A utility library for mocking out the requests Python library
—
Core functionality for registering mock responses and activating the mocking system. This includes the primary decorator-based activation approach, context manager usage, and convenient HTTP method shortcuts for common testing scenarios.
The @responses.activate decorator automatically starts and stops response mocking for the decorated function, providing the most convenient way to use responses in tests.
def activate(func=None, *, registry=None, assert_all_requests_are_fired=False):
"""
Decorator to activate response mocking for a function.
Parameters:
- func: Function to decorate
- registry: Custom registry class (default: FirstMatchRegistry)
- assert_all_requests_are_fired: Raise error if registered responses aren't used
Returns:
Decorated function with response mocking active
"""Usage Example:
import responses
import requests
@responses.activate
def test_api_call():
responses.add(responses.GET, "http://api.example.com/data", json={"key": "value"})
response = requests.get("http://api.example.com/data")
assert response.json() == {"key": "value"}Register mock responses that will be returned when matching requests are made. The add function is the primary method for registering responses.
def add(method=None, url=None, body="", adding_headers=None, *args, **kwargs):
"""
Register a mock response.
Parameters:
- method: HTTP method string or Response object
- url: URL pattern (string or regex Pattern)
- body: Response body as string or bytes
- json: Response body as JSON (mutually exclusive with body)
- status: HTTP status code (default: 200)
- headers: Response headers as dict or list of tuples
- content_type: Content-Type header value
- auto_calculate_content_length: Auto-calculate Content-Length header
- match: List of matcher functions for advanced request matching
- stream: Deprecated, use stream parameter in request instead
Returns:
BaseResponse object representing the registered response
"""Convenient shortcut methods for common HTTP methods. These are partial functions that pre-fill the method parameter of the add function.
def get(url, **kwargs):
"""Register a GET response. See add() for parameters."""
def post(url, **kwargs):
"""Register a POST response. See add() for parameters."""
def put(url, **kwargs):
"""Register a PUT response. See add() for parameters."""
def patch(url, **kwargs):
"""Register a PATCH response. See add() for parameters."""
def delete(url, **kwargs):
"""Register a DELETE response. See add() for parameters."""
def head(url, **kwargs):
"""Register a HEAD response. See add() for parameters."""
def options(url, **kwargs):
"""Register an OPTIONS response. See add() for parameters."""Usage Example:
@responses.activate
def test_various_methods():
# Using shortcuts
responses.get("http://api.example.com/users", json=[{"id": 1, "name": "John"}])
responses.post("http://api.example.com/users", json={"id": 2}, status=201)
responses.put("http://api.example.com/users/1", json={"id": 1, "name": "Jane"})
responses.delete("http://api.example.com/users/1", status=204)
# Make requests
users = requests.get("http://api.example.com/users").json()
new_user = requests.post("http://api.example.com/users", json={"name": "Bob"}).json()
updated_user = requests.put("http://api.example.com/users/1", json={"name": "Jane"}).json()
delete_response = requests.delete("http://api.example.com/users/1")
assert len(users) == 1
assert new_user["id"] == 2
assert delete_response.status_code == 204Functions to manage registered responses including removal, replacement, and upserting (add or replace).
def remove(method_or_response=None, url=None):
"""
Remove a registered response.
Parameters:
- method_or_response: HTTP method string or Response object
- url: URL pattern (required if method_or_response is a string)
Returns:
List of removed BaseResponse objects
"""
def replace(method_or_response=None, url=None, body="", *args, **kwargs):
"""
Replace an existing registered response.
Parameters:
Same as add(). The first matching response is replaced.
Returns:
BaseResponse object representing the replacement response
"""
def upsert(method_or_response=None, url=None, body="", *args, **kwargs):
"""
Add a response or replace if it already exists.
Parameters:
Same as add().
Returns:
BaseResponse object representing the added/replaced response
"""
def _add_from_file(file_path):
"""
Load response configurations from a YAML file.
Parameters:
- file_path: str or Path to YAML file containing response configurations
The YAML file should contain a 'responses' key with a list of response
configurations. This is commonly used with files generated by the
recording functionality.
YAML format:
responses:
- response:
method: HTTP_METHOD
url: URL_PATTERN
body: RESPONSE_BODY
status: STATUS_CODE
headers: HEADERS_DICT
content_type: CONTENT_TYPE
auto_calculate_content_length: BOOLEAN
"""Functions to control the mocking system lifecycle and reset state.
def start():
"""Start response mocking by patching the HTTP adapter."""
def stop():
"""Stop response mocking and restore original HTTP adapter."""
def reset():
"""Clear all registered responses and reset call history."""
def registered():
"""
Get list of all registered responses.
Returns:
List of BaseResponse objects
"""Access to recorded request/response pairs for test verification.
@property
def calls():
"""
CallList of all requests made while mocking was active.
Returns:
CallList object containing Call namedtuples with request/response pairs
"""
def assert_call_count(url, count):
"""
Assert that a specific URL was called a certain number of times.
Parameters:
- url: URL to check
- count: Expected number of calls
Returns:
True if assertion passes
Raises:
AssertionError if call count doesn't match
"""Usage Example:
@responses.activate
def test_call_tracking():
responses.get("http://api.example.com/data", json={"result": "success"})
# Make multiple requests
requests.get("http://api.example.com/data")
requests.get("http://api.example.com/data")
# Verify calls
assert len(responses.calls) == 2
assert responses.calls[0].request.url == "http://api.example.com/data"
# Assert specific call count
responses.assert_call_count("http://api.example.com/data", 2)GET: str = "GET"
POST: str = "POST"
PUT: str = "PUT"
PATCH: str = "PATCH"
DELETE: str = "DELETE"
HEAD: str = "HEAD"
OPTIONS: str = "OPTIONS"Install with Tessl CLI
npx tessl i tessl/pypi-responses