0
# Basic Response Mocking
1
2
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.
3
4
## Capabilities
5
6
### Decorator Activation
7
8
The `@responses.activate` decorator automatically starts and stops response mocking for the decorated function, providing the most convenient way to use responses in tests.
9
10
```python { .api }
11
def activate(func=None, *, registry=None, assert_all_requests_are_fired=False):
12
"""
13
Decorator to activate response mocking for a function.
14
15
Parameters:
16
- func: Function to decorate
17
- registry: Custom registry class (default: FirstMatchRegistry)
18
- assert_all_requests_are_fired: Raise error if registered responses aren't used
19
20
Returns:
21
Decorated function with response mocking active
22
"""
23
```
24
25
**Usage Example:**
26
27
```python
28
import responses
29
import requests
30
31
@responses.activate
32
def test_api_call():
33
responses.add(responses.GET, "http://api.example.com/data", json={"key": "value"})
34
35
response = requests.get("http://api.example.com/data")
36
assert response.json() == {"key": "value"}
37
```
38
39
### Response Registration
40
41
Register mock responses that will be returned when matching requests are made. The `add` function is the primary method for registering responses.
42
43
```python { .api }
44
def add(method=None, url=None, body="", adding_headers=None, *args, **kwargs):
45
"""
46
Register a mock response.
47
48
Parameters:
49
- method: HTTP method string or Response object
50
- url: URL pattern (string or regex Pattern)
51
- body: Response body as string or bytes
52
- json: Response body as JSON (mutually exclusive with body)
53
- status: HTTP status code (default: 200)
54
- headers: Response headers as dict or list of tuples
55
- content_type: Content-Type header value
56
- auto_calculate_content_length: Auto-calculate Content-Length header
57
- match: List of matcher functions for advanced request matching
58
- stream: Deprecated, use stream parameter in request instead
59
60
Returns:
61
BaseResponse object representing the registered response
62
"""
63
```
64
65
### HTTP Method Shortcuts
66
67
Convenient shortcut methods for common HTTP methods. These are partial functions that pre-fill the method parameter of the `add` function.
68
69
```python { .api }
70
def get(url, **kwargs):
71
"""Register a GET response. See add() for parameters."""
72
73
def post(url, **kwargs):
74
"""Register a POST response. See add() for parameters."""
75
76
def put(url, **kwargs):
77
"""Register a PUT response. See add() for parameters."""
78
79
def patch(url, **kwargs):
80
"""Register a PATCH response. See add() for parameters."""
81
82
def delete(url, **kwargs):
83
"""Register a DELETE response. See add() for parameters."""
84
85
def head(url, **kwargs):
86
"""Register a HEAD response. See add() for parameters."""
87
88
def options(url, **kwargs):
89
"""Register an OPTIONS response. See add() for parameters."""
90
```
91
92
**Usage Example:**
93
94
```python
95
@responses.activate
96
def test_various_methods():
97
# Using shortcuts
98
responses.get("http://api.example.com/users", json=[{"id": 1, "name": "John"}])
99
responses.post("http://api.example.com/users", json={"id": 2}, status=201)
100
responses.put("http://api.example.com/users/1", json={"id": 1, "name": "Jane"})
101
responses.delete("http://api.example.com/users/1", status=204)
102
103
# Make requests
104
users = requests.get("http://api.example.com/users").json()
105
new_user = requests.post("http://api.example.com/users", json={"name": "Bob"}).json()
106
updated_user = requests.put("http://api.example.com/users/1", json={"name": "Jane"}).json()
107
delete_response = requests.delete("http://api.example.com/users/1")
108
109
assert len(users) == 1
110
assert new_user["id"] == 2
111
assert delete_response.status_code == 204
112
```
113
114
### Response Management
115
116
Functions to manage registered responses including removal, replacement, and upserting (add or replace).
117
118
```python { .api }
119
def remove(method_or_response=None, url=None):
120
"""
121
Remove a registered response.
122
123
Parameters:
124
- method_or_response: HTTP method string or Response object
125
- url: URL pattern (required if method_or_response is a string)
126
127
Returns:
128
List of removed BaseResponse objects
129
"""
130
131
def replace(method_or_response=None, url=None, body="", *args, **kwargs):
132
"""
133
Replace an existing registered response.
134
135
Parameters:
136
Same as add(). The first matching response is replaced.
137
138
Returns:
139
BaseResponse object representing the replacement response
140
"""
141
142
def upsert(method_or_response=None, url=None, body="", *args, **kwargs):
143
"""
144
Add a response or replace if it already exists.
145
146
Parameters:
147
Same as add().
148
149
Returns:
150
BaseResponse object representing the added/replaced response
151
"""
152
153
def _add_from_file(file_path):
154
"""
155
Load response configurations from a YAML file.
156
157
Parameters:
158
- file_path: str or Path to YAML file containing response configurations
159
160
The YAML file should contain a 'responses' key with a list of response
161
configurations. This is commonly used with files generated by the
162
recording functionality.
163
164
YAML format:
165
responses:
166
- response:
167
method: HTTP_METHOD
168
url: URL_PATTERN
169
body: RESPONSE_BODY
170
status: STATUS_CODE
171
headers: HEADERS_DICT
172
content_type: CONTENT_TYPE
173
auto_calculate_content_length: BOOLEAN
174
"""
175
```
176
177
### System Control
178
179
Functions to control the mocking system lifecycle and reset state.
180
181
```python { .api }
182
def start():
183
"""Start response mocking by patching the HTTP adapter."""
184
185
def stop():
186
"""Stop response mocking and restore original HTTP adapter."""
187
188
def reset():
189
"""Clear all registered responses and reset call history."""
190
191
def registered():
192
"""
193
Get list of all registered responses.
194
195
Returns:
196
List of BaseResponse objects
197
"""
198
```
199
200
### Call Inspection
201
202
Access to recorded request/response pairs for test verification.
203
204
```python { .api }
205
@property
206
def calls():
207
"""
208
CallList of all requests made while mocking was active.
209
210
Returns:
211
CallList object containing Call namedtuples with request/response pairs
212
"""
213
214
def assert_call_count(url, count):
215
"""
216
Assert that a specific URL was called a certain number of times.
217
218
Parameters:
219
- url: URL to check
220
- count: Expected number of calls
221
222
Returns:
223
True if assertion passes
224
225
Raises:
226
AssertionError if call count doesn't match
227
"""
228
```
229
230
**Usage Example:**
231
232
```python
233
@responses.activate
234
def test_call_tracking():
235
responses.get("http://api.example.com/data", json={"result": "success"})
236
237
# Make multiple requests
238
requests.get("http://api.example.com/data")
239
requests.get("http://api.example.com/data")
240
241
# Verify calls
242
assert len(responses.calls) == 2
243
assert responses.calls[0].request.url == "http://api.example.com/data"
244
245
# Assert specific call count
246
responses.assert_call_count("http://api.example.com/data", 2)
247
```
248
249
## HTTP Method Constants
250
251
```python { .api }
252
GET: str = "GET"
253
POST: str = "POST"
254
PUT: str = "PUT"
255
PATCH: str = "PATCH"
256
DELETE: str = "DELETE"
257
HEAD: str = "HEAD"
258
OPTIONS: str = "OPTIONS"
259
```