0
# RequestsMock Class
1
2
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.
3
4
## Capabilities
5
6
### RequestsMock Instantiation
7
8
Create RequestsMock instances with custom configuration for advanced mocking scenarios.
9
10
```python { .api }
11
class RequestsMock:
12
def __init__(
13
self,
14
assert_all_requests_are_fired=True,
15
response_callback=None,
16
passthru_prefixes=(),
17
target="requests.adapters.HTTPAdapter.send",
18
registry=FirstMatchRegistry,
19
*,
20
real_adapter_send=None
21
):
22
"""
23
Create a RequestsMock instance.
24
25
Parameters:
26
- assert_all_requests_are_fired: bool, raise error if registered responses unused
27
- response_callback: function to modify all responses before returning
28
- passthru_prefixes: tuple of URL prefixes to pass through to real servers
29
- target: string path to the method being patched
30
- registry: registry class for managing response matching order
31
- real_adapter_send: custom real HTTP adapter function
32
33
The RequestsMock instance can be used as a context manager or manually
34
controlled with start()/stop() methods.
35
"""
36
```
37
38
### Context Manager Usage
39
40
Use RequestsMock as a context manager for automatic lifecycle management.
41
42
**Usage Example:**
43
44
```python
45
def test_context_manager():
46
with responses.RequestsMock() as rsps:
47
rsps.add(
48
responses.GET,
49
"http://api.example.com/data",
50
json={"context": "manager"}
51
)
52
53
response = requests.get("http://api.example.com/data")
54
assert response.json()["context"] == "manager"
55
56
# Outside context manager, real requests would work normally
57
```
58
59
### Manual Lifecycle Control
60
61
Manually start and stop mocking for fine-grained control over when mocking is active.
62
63
```python { .api }
64
def start(self):
65
"""
66
Start response mocking by patching the HTTP adapter.
67
68
Patches the target method to intercept HTTP requests.
69
Can be called multiple times safely - subsequent calls are ignored.
70
"""
71
72
def stop(self, allow_assert=True):
73
"""
74
Stop response mocking and restore original HTTP adapter.
75
76
Parameters:
77
- allow_assert: bool, whether to run assertion checks on unused responses
78
79
If assert_all_requests_are_fired is True and allow_assert is True,
80
raises AssertionError for any registered responses that weren't used.
81
"""
82
```
83
84
**Usage Example:**
85
86
```python
87
def test_manual_control():
88
mock = responses.RequestsMock()
89
90
try:
91
mock.start()
92
mock.add(responses.GET, "http://api.example.com/manual", json={"manual": True})
93
94
response = requests.get("http://api.example.com/manual")
95
assert response.json()["manual"] is True
96
97
finally:
98
mock.stop()
99
```
100
101
### Response Registration Methods
102
103
The RequestsMock instance provides the same response registration methods as the module-level functions.
104
105
```python { .api }
106
def add(self, method=None, url=None, body="", adding_headers=None, *args, **kwargs):
107
"""Add a response. Same interface as module-level add() function."""
108
109
def add_callback(self, method, url, callback, match_querystring=False, content_type="text/plain", match=()):
110
"""Add a callback response. Same interface as module-level add_callback() function."""
111
112
# HTTP method shortcuts
113
def get(self, url, **kwargs): ...
114
def post(self, url, **kwargs): ...
115
def put(self, url, **kwargs): ...
116
def patch(self, url, **kwargs): ...
117
def delete(self, url, **kwargs): ...
118
def head(self, url, **kwargs): ...
119
def options(self, url, **kwargs): ...
120
```
121
122
### Response Management
123
124
Methods for managing registered responses and mock state.
125
126
```python { .api }
127
def remove(self, method_or_response=None, url=None):
128
"""Remove registered responses. Same interface as module-level function."""
129
130
def replace(self, method_or_response=None, url=None, body="", *args, **kwargs):
131
"""Replace existing response. Same interface as module-level function."""
132
133
def upsert(self, method_or_response=None, url=None, body="", *args, **kwargs):
134
"""Add or replace response. Same interface as module-level function."""
135
136
def reset(self):
137
"""Clear all registered responses and reset call history."""
138
139
def registered(self):
140
"""
141
Get list of all registered responses.
142
143
Returns:
144
List of BaseResponse objects currently registered
145
"""
146
```
147
148
### Passthrough Configuration
149
150
Configure URLs that should pass through to real servers instead of being mocked.
151
152
```python { .api }
153
def add_passthru(self, prefix):
154
"""
155
Register URL prefix or regex pattern for passthrough to real servers.
156
157
Parameters:
158
- prefix: str or compiled regex Pattern
159
URL prefix that should pass through to real servers
160
161
Requests matching these prefixes bypass mocking and hit real endpoints.
162
"""
163
164
@property
165
def passthru_prefixes(self):
166
"""
167
Tuple of URL prefixes configured for passthrough.
168
169
Returns:
170
Tuple of strings and/or regex Patterns
171
"""
172
```
173
174
**Usage Example:**
175
176
```python
177
def test_passthrough():
178
with responses.RequestsMock() as rsps:
179
# Mock some endpoints
180
rsps.add(responses.GET, "http://api.example.com/mock", json={"mocked": True})
181
182
# Allow real requests to external service
183
rsps.add_passthru("http://httpbin.org")
184
185
# This hits the mock
186
mock_resp = requests.get("http://api.example.com/mock")
187
assert mock_resp.json()["mocked"] is True
188
189
# This would hit the real server (if network available)
190
# real_resp = requests.get("http://httpbin.org/get")
191
```
192
193
### Call Tracking and Assertions
194
195
Access recorded requests and verify call patterns.
196
197
```python { .api }
198
@property
199
def calls(self):
200
"""
201
CallList of all requests made while mocking was active.
202
203
Returns:
204
CallList object containing Call namedtuples with request/response pairs
205
"""
206
207
def assert_call_count(self, url, count):
208
"""
209
Assert that a URL was called a specific number of times.
210
211
Parameters:
212
- url: str, URL to check
213
- count: int, expected number of calls
214
215
Returns:
216
True if assertion passes
217
218
Raises:
219
AssertionError if actual call count doesn't match expected count
220
"""
221
222
@property
223
def assert_all_requests_are_fired(self):
224
"""
225
Whether to assert all registered responses were used.
226
227
Returns:
228
bool: Current setting for assertion checking
229
"""
230
```
231
232
### Registry Management
233
234
Control how responses are matched and selected using different registry strategies.
235
236
```python { .api }
237
def get_registry(self):
238
"""
239
Get the current response registry instance.
240
241
Returns:
242
Registry instance (typically FirstMatchRegistry or OrderedRegistry)
243
"""
244
245
def _set_registry(self, new_registry):
246
"""
247
Replace the current registry with a new one.
248
249
Parameters:
250
- new_registry: Registry class (not instance)
251
252
Raises:
253
AttributeError if current registry has registered responses
254
Must call reset() first to clear responses before changing registry
255
"""
256
```
257
258
**Usage Example:**
259
260
```python
261
from responses.registries import OrderedRegistry
262
263
def test_ordered_responses():
264
with responses.RequestsMock() as rsps:
265
# Switch to ordered registry
266
rsps.reset() # Clear any existing responses
267
rsps._set_registry(OrderedRegistry)
268
269
# Add responses in specific order
270
rsps.add(responses.GET, "http://api.example.com/data", json={"response": 1})
271
rsps.add(responses.GET, "http://api.example.com/data", json={"response": 2})
272
273
# Responses will be returned in registration order
274
resp1 = requests.get("http://api.example.com/data")
275
resp2 = requests.get("http://api.example.com/data")
276
277
assert resp1.json()["response"] == 1
278
assert resp2.json()["response"] == 2
279
```
280
281
### Global Response Callback
282
283
Configure a callback that processes all responses before they're returned.
284
285
```python { .api }
286
@property
287
def response_callback(self):
288
"""
289
Global callback function applied to all responses.
290
291
Returns:
292
Function that takes a response and returns a modified response, or None
293
"""
294
295
@response_callback.setter
296
def response_callback(self, callback):
297
"""
298
Set global response callback.
299
300
Parameters:
301
- callback: function(response) -> response, or None to disable
302
303
The callback receives the generated response and can modify it
304
before it's returned to the requesting code.
305
"""
306
```
307
308
**Usage Example:**
309
310
```python
311
def response_modifier(response):
312
# Add custom header to all responses
313
response.headers["X-Mock-Modified"] = "true"
314
return response
315
316
def test_global_callback():
317
with responses.RequestsMock(response_callback=response_modifier) as rsps:
318
rsps.add(responses.GET, "http://api.example.com/test", json={"test": True})
319
320
response = requests.get("http://api.example.com/test")
321
322
assert response.headers["X-Mock-Modified"] == "true"
323
assert response.json()["test"] is True
324
```
325
326
### File-Based Response Configuration
327
328
Load response configurations from YAML files for complex test scenarios.
329
330
```python { .api }
331
def _add_from_file(self, file_path):
332
"""
333
Load responses from a YAML configuration file.
334
335
Parameters:
336
- file_path: str or Path object to YAML file
337
338
The YAML file should contain a 'responses' key with a list of response
339
configurations matching the add() method parameters.
340
341
Example YAML format:
342
responses:
343
- response:
344
method: GET
345
url: http://api.example.com/data
346
body: '{"key": "value"}'
347
status: 200
348
headers:
349
Content-Type: application/json
350
content_type: application/json
351
auto_calculate_content_length: false
352
"""
353
```
354
355
### HTTP Method Constants
356
357
The RequestsMock class provides HTTP method constants for use in response registration.
358
359
```python { .api }
360
# Class attributes available on RequestsMock instances
361
GET: str = "GET"
362
POST: str = "POST"
363
PUT: str = "PUT"
364
PATCH: str = "PATCH"
365
DELETE: str = "DELETE"
366
HEAD: str = "HEAD"
367
OPTIONS: str = "OPTIONS"
368
369
# Reference to Response class
370
Response: Type[Response] = Response
371
372
# Reference to matchers module
373
matchers = responses.matchers
374
```
375
376
**Usage Example:**
377
378
```python
379
def test_instance_constants():
380
with responses.RequestsMock() as rsps:
381
# Use constants from the instance
382
rsps.add(rsps.GET, "http://api.example.com/get", json={"method": "GET"})
383
rsps.add(rsps.POST, "http://api.example.com/post", json={"method": "POST"})
384
385
get_resp = requests.get("http://api.example.com/get")
386
post_resp = requests.post("http://api.example.com/post")
387
388
assert get_resp.json()["method"] == "GET"
389
assert post_resp.json()["method"] == "POST"
390
```