A utility library for mocking out the requests Python library
npx @tessl/cli install tessl/pypi-responses@0.25.00
# Responses
1
2
A 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.
3
4
## Package Information
5
6
- **Package Name**: responses
7
- **Language**: Python
8
- **Installation**: `pip install responses`
9
10
## Core Imports
11
12
```python
13
import responses
14
```
15
16
For direct class usage:
17
18
```python
19
from responses import RequestsMock, Response, CallbackResponse
20
```
21
22
For matchers:
23
24
```python
25
from responses.matchers import json_params_matcher, query_param_matcher
26
```
27
28
For registries:
29
30
```python
31
from responses.registries import FirstMatchRegistry, OrderedRegistry
32
```
33
34
For recording:
35
36
```python
37
from responses import _add_from_file
38
from responses._recorder import Recorder, record
39
```
40
41
## Basic Usage
42
43
```python
44
import responses
45
import requests
46
47
@responses.activate
48
def test_simple():
49
# Register a mock response
50
responses.add(
51
responses.GET,
52
"http://example.com/api/data",
53
json={"message": "success"},
54
status=200
55
)
56
57
# Make request - will hit the mock
58
resp = requests.get("http://example.com/api/data")
59
60
assert resp.json() == {"message": "success"}
61
assert resp.status_code == 200
62
63
# Context manager approach
64
def test_with_context():
65
with responses.RequestsMock() as rsps:
66
rsps.add(
67
responses.POST,
68
"http://example.com/api/submit",
69
json={"result": "created"},
70
status=201
71
)
72
73
resp = requests.post("http://example.com/api/submit", json={"data": "test"})
74
assert resp.status_code == 201
75
```
76
77
## Architecture
78
79
The responses library uses a patching mechanism to intercept `requests.adapters.HTTPAdapter.send` calls. When a request is made, responses:
80
81
1. **Request Matching**: Compares the request against registered mock responses using URL, method, and optional matchers
82
2. **Response Selection**: Uses a registry system (default: FirstMatchRegistry) to find the appropriate response
83
3. **Response Generation**: Creates an HTTPResponse object from the registered response data
84
4. **Call Tracking**: Records all requests and responses for test verification
85
86
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.
87
88
## Capabilities
89
90
### Basic Response Mocking
91
92
Core functionality for registering mock responses and activating the mocking system. Includes decorator-based activation, context manager usage, and HTTP method shortcuts.
93
94
```python { .api }
95
@responses.activate
96
def decorator_function(): ...
97
98
def add(method, url, body="", json=None, status=200, headers=None, **kwargs): ...
99
def get(url, **kwargs): ...
100
def post(url, **kwargs): ...
101
def put(url, **kwargs): ...
102
def patch(url, **kwargs): ...
103
def delete(url, **kwargs): ...
104
def head(url, **kwargs): ...
105
def options(url, **kwargs): ...
106
```
107
108
[Basic Response Mocking](./basic-mocking.md)
109
110
### Request Matchers
111
112
Advanced request matching capabilities for precise control over which requests are intercepted. Includes matchers for JSON payloads, query parameters, headers, and custom matching logic.
113
114
```python { .api }
115
def json_params_matcher(params, *, strict_match=True): ...
116
def query_param_matcher(params, *, strict_match=True): ...
117
def header_matcher(headers, strict_match=False): ...
118
def body_matcher(params, *, allow_blank=False): ...
119
```
120
121
[Request Matchers](./matchers.md)
122
123
### Response Types
124
125
Different types of mock responses including static responses, callback-based dynamic responses, and passthrough responses for selective mocking.
126
127
```python { .api }
128
class Response:
129
def __init__(self, method, url, body="", json=None, status=200, headers=None, **kwargs): ...
130
131
class CallbackResponse:
132
def __init__(self, method, url, callback, **kwargs): ...
133
134
class PassthroughResponse:
135
def __init__(self, *args, **kwargs): ...
136
```
137
138
[Response Types](./response-types.md)
139
140
### RequestsMock Class
141
142
The core RequestsMock class for programmatic control over response mocking, including registry management, call tracking, and advanced configuration options.
143
144
```python { .api }
145
class RequestsMock:
146
def __init__(self, assert_all_requests_are_fired=True, response_callback=None, **kwargs): ...
147
def start(self): ...
148
def stop(self, allow_assert=True): ...
149
def add_passthru(self, prefix): ...
150
def assert_call_count(self, url, count): ...
151
```
152
153
[RequestsMock Class](./requests-mock.md)
154
155
### Request Recording
156
157
Record actual HTTP requests and responses to generate response configurations for future mocking. Enables capturing real API interactions and replaying them in tests.
158
159
```python { .api }
160
@record(file_path="responses.yaml")
161
def function_making_requests(): ...
162
163
class Recorder:
164
def __init__(self, *, target="requests.adapters.HTTPAdapter.send", registry=OrderedRegistry): ...
165
def record(self, *, file_path="response.yaml"): ...
166
def dump_to_file(self, file_path, *, registered=None): ...
167
168
def _add_from_file(file_path): ...
169
```
170
171
[Request Recording](./recording.md)
172
173
### Response Registries
174
175
Registry systems that control how responses are matched and selected, including order-dependent response handling for complex testing scenarios.
176
177
```python { .api }
178
class FirstMatchRegistry:
179
def __init__(self): ...
180
def find(self, request): ...
181
def add(self, response): ...
182
def remove(self, response): ...
183
184
class OrderedRegistry(FirstMatchRegistry):
185
def find(self, request): ...
186
```
187
188
[Response Registries](./registries.md)
189
190
## Types
191
192
```python { .api }
193
# HTTP Method Constants
194
GET: str = "GET"
195
POST: str = "POST"
196
PUT: str = "PUT"
197
PATCH: str = "PATCH"
198
DELETE: str = "DELETE"
199
HEAD: str = "HEAD"
200
OPTIONS: str = "OPTIONS"
201
202
# Call tracking
203
class Call:
204
request: PreparedRequest
205
response: Any
206
207
class CallList:
208
def __len__(self) -> int: ...
209
def __getitem__(self, index) -> Call: ...
210
def reset(self) -> None: ...
211
```