File: api.md

package info (click to toggle)
python-respx 0.21.1-2~bpo12%2B1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-backports
  • size: 872 kB
  • sloc: python: 4,378; makefile: 17
file content (435 lines) | stat: -rw-r--r-- 13,240 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
# API Reference

## Router

### Configuration

Creates a mock `Router` instance, ready to be used as decorator/manager for activation.

> <code>respx.<strong>mock</strong>(assert_all_mocked=True, *assert_all_called=True, base_url=None*)</strong></code>
>
> **Parameters:**
>
> * **assert_all_mocked** - *(optional) bool - default: `True`*  
>   Asserts that all sent and captured `HTTPX` requests are routed and mocked.  
>   If disabled, all non-routed requests will be auto mocked with status code `200`.  
> * **assert_all_called** - *(optional) bool - default: `True`*  
>   Asserts that all added and mocked routes were called when exiting context.  
> * **base_url** - *(optional) str*  
>   Base URL to match, on top of each route specific pattern *and/or* side effect.
>
> **Returns:** `Router`

!!! note "NOTE"
    When using the *default* mock router `respx.mock`, *without settings*, `assert_all_called` is **disabled**.

!!! tip "pytest"
    Use the `@pytest.mark.respx(...)` marker with these parameters to configure the `respx_mock` [pytest fixture](examples.md#built-in-marker).


### .route()

Adds a new, *optionally named*, `Route` with given [patterns](#patterns) *and/or* [lookups](#lookups) combined, using the [AND](#and) operator.

> <code>respx.<strong>route</strong>(*\*patterns, name=None, \*\*lookups*)</strong></code>
>
> **Parameters:**
>
> * **patterns** - *(optional) args*  
>   One or more [pattern](#patterns) objects.
> * **lookups** - *(optional) kwargs*  
>   One or more [pattern](#patterns) keyword [lookups](#lookups), given as `<pattern>__<lookup>=value`.
> * **name** - *(optional) str*  
>   Name this route.
>
> **Returns:** `Route`

### .get(), .post(), ...

HTTP method helpers to add routes, mimicking the [HTTPX Helper Functions](https://www.python-httpx.org/api/#helper-functions).

> <code>respx.<strong>get</strong>(*url, name=None, \*\*lookups*)</strong></code>

> <code>respx.<strong>options</strong>(...)</strong></code>

> <code>respx.<strong>head</strong>(...)</strong></code>

> <code>respx.<strong>post</strong>(...)</strong></code>

> <code>respx.<strong>put</strong>(...)</strong></code>

> <code>respx.<strong>patch</strong>(...)</strong></code>

> <code>respx.<strong>delete</strong>(...)</strong></code>
>
> **Parameters:**
>
> * **url** - *(optional) str | compiled regex | tuple (httpcore) | httpx.URL*  
>   Request URL to match, *full or partial*, turned into a [URL](#url) pattern.
> * **name** - *(optional) str*  
>   Name this route.
> * **lookups** - *(optional) kwargs*  
>   One or more [pattern](#patterns) keyword [lookups](#lookups), given as `<pattern>__<lookup>=value`.
>
> **Returns:** `Route`
``` python
respx.get("https://example.org/", params={"foo": "bar"}, ...)
```

### .request()

> <code>respx.<strong>request</strong>(*method, url, name=None, \*\*lookups*)</strong></code>
>
> **Parameters:**
>
> * **method** - *str*  
>   Request HTTP method to match.
> * **url** - *(optional) str | compiled regex | tuple (httpcore) | httpx.URL*  
>   Request URL to match, *full or partial*, turned into a [URL](#url) pattern.
> * **name** - *(optional) str*  
>   Name this route.
> * **lookups** - *(optional) kwargs*  
>   One or more [pattern](#patterns) keyword [lookups](#lookups), given as `<pattern>__<lookup>=value`.
>
> **Returns:** `Route`
``` python
respx.request("GET", "https://example.org/", params={"foo": "bar"}, ...)
```

---

## Route

### .mock()

Mock a route's response or side effect.

> <code>route.<strong>mock</strong>(*return_value=None, side_effect=None*)</strong></code>
>
> **Parameters:**
>
> * **return_value** - *(optional) [Response](#response)*  
>   HTTPX Response to mock and return.
> * **side_effect** - *(optional) Callable | Exception | Iterable of httpx.Response/Exception*  
>   [Side effect](guide.md#mock-with-a-side-effect) to call, exception to raise or stacked responses to respond with in order.
>
> **Returns:** `Route`

### .return_value

Setter for the `HTTPX` [Response](#response) to return.

> <code>route.**return_value** = Response(204)</code>

### .side_effect

Setter for the [side effect](guide.md#mock-with-a-side-effect) to trigger.

> <code>route.**side_effect** = ...</code>
>
> See [route.mock()](#mock) for valid side effect types.

### .respond()

Shortcut for creating and mocking a `HTTPX` [Response](#response).

> <code>route.<strong>respond</strong>(*status_code=200, headers=None, cookies=None, content=None, text=None, html=None, json=None, stream=None, content_type=None*)</strong></code>
>
> **Parameters:**
>
> * **status_code** - *(optional) int - default: `200`*  
>   Response status code to mock.
> * **headers** - *(optional) dict | Sequence[tuple[str, str]]*  
>   Response headers to mock.
> * **cookies** - *(optional) dict | Sequence[tuple[str, str]] | Sequence[SetCookie]*  
>   Response cookies to mock as `Set-Cookie` headers. See [SetCookie](#setcookie).
> * **content** - *(optional) bytes | str | Iterable[bytes]*  
>   Response raw content to mock.
> * **text** - *(optional) str*  
>   Response *text* content to mock, with automatic content-type header added.
> * **html** - *(optional) str*  
>   Response *HTML* content to mock, with automatic content-type header added.
> * **json** - *(optional) str | list | dict*  
>   Response *JSON* content to mock, with automatic content-type header added.
> * **stream** - *(optional) Iterable[bytes]*  
>   Response *stream* to mock.
> * **content_type** - *(optional) str*  
>   Response `Content-Type` header to mock.
>
> **Returns:** `Route`

### .pass_through()

> <code>route.<strong>pass_through</strong>(*value=True*)</strong></code>
>
> **Parameters:**
>
> * **value** - *(optional) bool - default: `True`*  
>   Mark route to pass through, sending matched requests to real server, *e.g. don't mock*.
>
> **Returns:** `Route`

---

## Response

!!! note "NOTE"
    This is a partial reference for how to the instantiate the **HTTPX** `Response`class, e.g. *not* a RESPX class.

> <code>httpx.<strong>Response</strong>(*status_code, headers=None, content=None, text=None, html=None, json=None, stream=None*)</strong></code>
>
> **Parameters:**
>
> * **status_code** - *int*  
>   HTTP status code.
> * **headers** - *(optional) dict | httpx.Headers*  
>   HTTP headers.
> * **content** - *(optional) bytes | str | Iterable[bytes]*  
>   Raw content.
> * **text** - *(optional) str*  
>   Text content, with automatic content-type header added.
> * **html** - *(optional) str*  
>   HTML content, with automatic content-type header added.
> * **json** - *(optional) str | list | dict*  
>   JSON content, with automatic content-type header added.
> * **stream** - *(optional) Iterable[bytes]*  
>   Content *stream*.

!!! tip "Cookies"
    Use [respx.SetCookie(...)](#setcookie) to produce `Set-Cookie` headers.

---

## SetCookie

A utility to render a `("Set-Cookie", <cookie header value>)` tuple. See route [respond](#respond) shortcut for alternative use.

> <code>respx.<strong>SetCookie</strong>(*name, value, path=None, domain=None, expires=None, max_age=None, http_only=False, same_site=None, secure=False, partitioned=False*)</strong></code>

``` python
import respx
respx.post("https://example.org/").mock(
    return_value=httpx.Response(200, headers=[SetCookie("foo", "bar")])
)
```

---

## Patterns

### M()

Creates a reusable pattern, combining multiple arguments using the [AND](#and) operator.

> <code><strong>M</strong>(*\*patterns, \*\*lookups*)</strong></code>
>
> **Parameters:**
>
> * **patterns** - *(optional) args*  
>   One or more [pattern](#patterns) objects.
> * **lookups** - *(optional) kwargs*  
>   One or more [pattern](#patterns) keyword [lookups](#lookups), given as `<pattern>__<lookup>=value`.
>
> **Returns:** `Pattern`
``` python
import respx
from respx.patterns import M
pattern = M(host="example.org")
respx.route(pattern)
```
> See [operators](#operators) for advanced usage.



### Method
Matches request *HTTP method*, using <code>[eq](#eq)</code> as default lookup.
> Key: `method`  
> Lookups: [eq](#eq), [in](#in)
``` python
respx.route(method="GET")
respx.route(method__in=["PUT", "PATCH"])
```

### Scheme
Matches request *URL scheme*, using <code>[eq](#eq)</code> as default lookup.
> Key: `scheme`  
> Lookups: [eq](#eq), [in](#in)
``` python
respx.route(scheme="https")
respx.route(scheme__in=["http", "https"])
```

### Host
Matches request *URL host*, using <code>[eq](#eq)</code> as default lookup.
> Key: `host`  
> Lookups: [eq](#eq), [regex](#regex), [in](#in)
``` python
respx.route(host="example.org")
respx.route(host__regex=r"example\.(org|com)")
respx.route(host__in=["example.org", "example.com"])
```

### Port
Matches request *URL port*, using <code>[eq](#eq)</code> as default lookup.
> Key: `port`  
> Lookups: [eq](#eq), [in](#in)

``` python
respx.route(port=8000)
respx.route(port__in=[2375, 2376])
```

### Path
Matches request *URL path*, using <code>[eq](#eq)</code> as default lookup.
> Key: `path`  
> Lookups: [eq](#eq), [regex](#regex), [startswith](#startswith), [in](#in)
``` python
respx.route(path="/api/foobar/")
respx.route(path__regex=r"^/api/(?P<slug>\w+)/")
respx.route(path__startswith="/api/")
respx.route(path__in=["/api/v1/foo/", "/api/v2/foo/"])
```

### Params
Matches request *URL query params*, using <code>[contains](#contains)</code> as default lookup.
> Key: `params`  
> Lookups: [contains](#contains), [eq](#eq)
``` python
respx.route(params={"foo": "bar", "ham": "spam"})
respx.route(params=[("foo", "bar"), ("ham", "spam")])
respx.route(params=(("foo", "bar"), ("ham", "spam")))
respx.route(params="foo=bar&ham=spam")
```

!!! note "NOTE"
    A request querystring with multiple parameters of the same name is treated as an ordered list when matching.
!!! tip "ANY value"
    Use `mock.ANY` as value to only match on parameter presence, e.g. `respx.route(params={"foo": ANY})`.

### URL
Matches request *URL*.

When no *lookup* is given, `url` works as a *shorthand* pattern, combining individual request *URL* parts, using the [AND](#and) operator.
> Key: `url`  
> Lookups: [eq](#eq), [regex](#regex), [startswith](#startswith)
``` python
respx.get("//example.org/foo/")  # == M(host="example.org", path="/foo/")
respx.get(url__eq="https://example.org:8080/foobar/?ham=spam")
respx.get(url__regex=r"https://example.org/(?P<slug>\w+)/")
respx.get(url__startswith="https://example.org/api/")
respx.get("all://*.example.org/foo/")
```

### Content
Matches request raw *content*, using [eq](#eq) as default lookup.
> Key: `content`  
> Lookups: [eq](#eq), [contains](#contains)
``` python
respx.post("https://example.org/", content="foobar")
respx.post("https://example.org/", content=b"foobar")
respx.post("https://example.org/", content__contains="bar")
```

### Data
Matches request *form data*, excluding files, using [eq](#eq) as default lookup.
> Key: `data`  
> Lookups: [eq](#eq), [contains](#contains)
``` python
respx.post("https://example.org/", data={"foo": "bar"})
```

### Files
Matches files within request *form data*, using [contains](#contains) as default lookup.
> Key: `files`  
> Lookups: [contains](#contains), [eq](#eq)
``` python
respx.post("https://example.org/", files={"some_file": b"..."})
respx.post("https://example.org/", files={"some_file": ANY})
respx.post("https://example.org/", files={"some_file": ("filename.txt", b"...")})
respx.post("https://example.org/", files={"some_file": ("filename.txt", ANY)})
```

### JSON
Matches request *json* content, using [eq](#eq) as default lookup.
> Key: `json`  
> Lookups: [eq](#eq)
``` python
respx.post("https://example.org/", json={"foo": "bar"})
```
The `json` pattern also supports path traversing, *i.e.* `json__<path>=<value>`.
``` python
respx.post("https://example.org/", json__foobar__0__ham="spam")
httpx.post("https://example.org/", json={"foobar": [{"ham": "spam"}]})
```

### Headers
Matches request *headers*, using [contains](#contains) as default lookup.
> Key: `headers`  
> Lookups: [contains](#contains), [eq](#eq)
``` python
respx.route(headers={"foo": "bar", "ham": "spam"})
respx.route(headers=[("foo", "bar"), ("ham", "spam")])
```

### Cookies
Matches request *cookie header*, using [contains](#contains) as default lookup.
> Key: `cookies`  
> Lookups: [contains](#contains), [eq](#eq)
``` python
respx.route(cookies={"foo": "bar", "ham": "spam"})
respx.route(cookies=[("foo", "bar"), ("ham", "spam")])
```

## Lookups

### eq

``` python
M(path="/foo/bar/")
M(path__eq="/foo/bar/")
```

### contains
Case-sensitive containment test.
``` python
M(params__contains={"id": "123"})
```

### in
Case-sensitive within test.
``` python
M(method__in=["PUT", "PATCH"])
```

### regex
``` python
M(path__regex=r"^/api/(?P<slug>\w+)/")
```

### startswith
Case-sensitive starts-with.
``` python
M(path__startswith="/api/")
```

## Operators

Patterns can be combined using bitwise operators, creating new patterns.

### AND (&)
Combines two `Pattern`s using `and` operator.
``` python
M(scheme="http") & M(host="example.org")
```

### OR (&)
Combines two `Pattern`s using `or` operator.
``` python
M(method="PUT") | M(method="PATCH")
```

### INVERT (~)
Inverts a `Pattern` match.
``` python
~M(params={"foo": "bar"})
```