httpx2-pytest 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- httpx2_pytest-1.0.0.dist-info/METADATA +1051 -0
- httpx2_pytest-1.0.0.dist-info/RECORD +14 -0
- httpx2_pytest-1.0.0.dist-info/WHEEL +5 -0
- httpx2_pytest-1.0.0.dist-info/entry_points.txt +2 -0
- httpx2_pytest-1.0.0.dist-info/licenses/LICENSE.txt +21 -0
- httpx2_pytest-1.0.0.dist-info/top_level.txt +1 -0
- pytest_httpx2/__init__.py +96 -0
- pytest_httpx2/_httpx_internals.py +60 -0
- pytest_httpx2/_httpx_mock.py +372 -0
- pytest_httpx2/_options.py +18 -0
- pytest_httpx2/_pretty_print.py +72 -0
- pytest_httpx2/_request_matcher.py +293 -0
- pytest_httpx2/py.typed +0 -0
- pytest_httpx2/version.py +6 -0
|
@@ -0,0 +1,1051 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: httpx2-pytest
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Send responses to httpx2.
|
|
5
|
+
Author-email: Colin Bounouar <github.coping055@passinbox.com>, angryfoxx <omarfarukkorkmazz@gmail.com>
|
|
6
|
+
Maintainer-email: Colin Bounouar <github.coping055@passinbox.com>, angryfoxx <omarfarukkorkmazz@gmail.com>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
Project-URL: Changelog, https://github.com/angryfoxx/pytest_httpx2/blob/master/CHANGELOG.md
|
|
9
|
+
Project-URL: Documentation, https://github.com/angryfoxx/pytest_httpx2#readme
|
|
10
|
+
Project-URL: Homepage, https://github.com/angryfoxx/pytest_httpx2
|
|
11
|
+
Project-URL: Issues, https://github.com/angryfoxx/pytest_httpx2/issues
|
|
12
|
+
Project-URL: Repository, https://github.com/angryfoxx/pytest_httpx2
|
|
13
|
+
Keywords: httpx2,pytest,testing
|
|
14
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
15
|
+
Classifier: Framework :: Pytest
|
|
16
|
+
Classifier: Intended Audience :: Developers
|
|
17
|
+
Classifier: Natural Language :: English
|
|
18
|
+
Classifier: Programming Language :: Python
|
|
19
|
+
Classifier: Programming Language :: Python :: 3
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
25
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
26
|
+
Classifier: Topic :: Software Development :: Build Tools
|
|
27
|
+
Classifier: Typing :: Typed
|
|
28
|
+
Requires-Python: >=3.10
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
License-File: LICENSE.txt
|
|
31
|
+
Requires-Dist: httpx2==2.*
|
|
32
|
+
Requires-Dist: pytest==9.*
|
|
33
|
+
Provides-Extra: testing
|
|
34
|
+
Requires-Dist: pytest-cov==7.*; extra == "testing"
|
|
35
|
+
Requires-Dist: pytest-asyncio==1.*; extra == "testing"
|
|
36
|
+
Dynamic: license-file
|
|
37
|
+
|
|
38
|
+
<h2 align="center">Send responses to HTTPX2 using pytest</h2>
|
|
39
|
+
|
|
40
|
+
<p align="center">
|
|
41
|
+
<a href="https://pypi.org/project/httpx2-pytest/"><img alt="pypi version" src="https://img.shields.io/pypi/v/httpx2-pytest"></a>
|
|
42
|
+
<a href="https://github.com/angryfoxx/pytest_httpx2/actions"><img alt="Build status" src="https://github.com/angryfoxx/pytest_httpx2/actions/workflows/Test/badge.svg"></a>
|
|
43
|
+
<a href="https://codecov.io/gh/angryfoxx/pytest_httpx2"><img alt="Coverage" src="https://codecov.io/gh/angryfoxx/pytest_httpx2/branch/master/graph/badge.svg"/></a>
|
|
44
|
+
<a href="https://github.com/angryfoxx/pytest_httpx2"><img alt="Number of tests" src="https://img.shields.io/badge/tests-338 passed-blue"></a>
|
|
45
|
+
<a href="https://pypi.org/project/httpx2-pytest/"><img alt="Number of downloads" src="https://img.shields.io/pypi/dm/httpx2-pytest"></a>
|
|
46
|
+
</p>
|
|
47
|
+
|
|
48
|
+
## HTTPX2 mocking options
|
|
49
|
+
|
|
50
|
+
**httpx2-pytest** (this project) builds on the design and API of **[pytest-httpx](https://github.com/Colin-b/pytest_httpx)** by [Colin Bounouar](https://github.com/Colin-b) — the established pytest plugin for mocking [HTTPX](https://www.python-httpx.org). That project defined the `httpx_mock` fixture and request-matching model many test suites already rely on. This fork carries that approach forward for [HTTPX2](https://github.com/pydantic/httpx2) and aims to stay compatible with pytest-httpx: same fixture names, markers, and `httpx_mock.add_response` / `add_callback` patterns so you can migrate from HTTPX with minimal test changes.
|
|
51
|
+
|
|
52
|
+
**[pytest-httpx2](https://github.com/lundberg/pytest-httpx2)** by [Erik Lundberg](https://github.com/lundberg) is another HTTPX2 option, built on [respx](https://github.com/lundberg/respx). It is **not** a drop-in replacement for pytest-httpx — the API and configuration differ from Colin’s plugin. Choose it if you prefer respx-style routing; choose **httpx2-pytest** if you want pytest-httpx–like behavior on HTTPX2.
|
|
53
|
+
|
|
54
|
+
## About HTTPX2
|
|
55
|
+
|
|
56
|
+
This project mocks **[HTTPX2](https://github.com/pydantic/httpx2)** — a next-generation HTTP client for Python maintained by [Pydantic](https://pydantic.dev). HTTPX2 continues the work started by the HTTPX community: a requests-compatible API with sync and async clients, HTTP/1.1 and HTTP/2 support, strict timeouts, and full type annotations.
|
|
57
|
+
|
|
58
|
+
HTTPX2 is the reliably maintained path forward for applications that depended on HTTPX, including timely security updates for a library in the critical path of many production systems. Documentation lives at [httpx2.pydantic.dev](https://httpx2.pydantic.dev/).
|
|
59
|
+
|
|
60
|
+
```shell
|
|
61
|
+
pip install httpx2
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
import httpx2
|
|
66
|
+
|
|
67
|
+
response = httpx2.get("https://www.example.org/")
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
**httpx2-pytest** patches HTTPX2 transports so your tests never hit the network unless you opt out. Use `import httpx2` in your application and test code; the `httpx_mock` fixture intercepts `httpx2.Client` and `httpx2.AsyncClient` requests the same way pytest-httpx did for HTTPX.
|
|
71
|
+
|
|
72
|
+
```shell
|
|
73
|
+
pip install httpx2-pytest
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
> [!NOTE]
|
|
77
|
+
> This project targets [HTTPX2](https://github.com/pydantic/httpx2) instead of HTTPX, in the spirit of [pytest-httpx](https://github.com/Colin-b/pytest_httpx). The mocking API and `httpx_mock` fixture name are unchanged for compatibility with existing test suites.
|
|
78
|
+
|
|
79
|
+
Once installed, the `httpx_mock` or `httpx2_mock` [`pytest`](https://docs.pytest.org/en/latest/) fixture will make sure every [`httpx2`](https://httpx2.pydantic.dev) request will be replied to with user provided responses ([unless some hosts are explicitly skipped](#do-not-mock-some-requests)). Both fixtures share the same implementation.
|
|
80
|
+
|
|
81
|
+
- [Add responses](#add-responses)
|
|
82
|
+
- [JSON body](#add-json-response)
|
|
83
|
+
- [Custom body](#reply-with-custom-body)
|
|
84
|
+
- [Multipart body (files, ...)](#add-multipart-response)
|
|
85
|
+
- [HTTP status code](#add-non-200-response)
|
|
86
|
+
- [HTTP headers](#reply-with-custom-headers)
|
|
87
|
+
- [HTTP/2.0](#add-http/2.0-response)
|
|
88
|
+
- [Add dynamic responses](#dynamic-responses)
|
|
89
|
+
- [Raising exceptions](#raising-exceptions)
|
|
90
|
+
- [Check requests](#check-sent-requests)
|
|
91
|
+
- [Configuration](#configuring-httpx_mock)
|
|
92
|
+
- [Register more responses than requested](#allow-to-register-more-responses-than-what-will-be-requested)
|
|
93
|
+
- [Register less responses than requested](#allow-to-not-register-responses-for-every-request)
|
|
94
|
+
- [Allow to register a response for more than one request](#allow-to-register-a-response-for-more-than-one-request)
|
|
95
|
+
- [Do not mock some requests](#do-not-mock-some-requests)
|
|
96
|
+
- [Migrating](#migrating-to-httpx2-pytest)
|
|
97
|
+
- [responses](#from-responses)
|
|
98
|
+
- [aioresponses](#from-aioresponses)
|
|
99
|
+
|
|
100
|
+
## Add responses
|
|
101
|
+
|
|
102
|
+
You can register responses for both sync and async [`HTTPX2`](https://httpx2.pydantic.dev) requests.
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
import pytest
|
|
106
|
+
import httpx2
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def test_something(httpx_mock):
|
|
110
|
+
httpx_mock.add_response()
|
|
111
|
+
|
|
112
|
+
with httpx2.Client() as client:
|
|
113
|
+
response = client.get("https://test_url")
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@pytest.mark.asyncio
|
|
117
|
+
async def test_something_async(httpx_mock):
|
|
118
|
+
httpx_mock.add_response()
|
|
119
|
+
|
|
120
|
+
async with httpx2.AsyncClient() as client:
|
|
121
|
+
response = await client.get("https://test_url")
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
If all registered responses are not sent back during test execution, the test case will fail at teardown [(unless you turned `assert_all_responses_were_requested` option off)](#allow-to-register-more-responses-than-what-will-be-requested).
|
|
125
|
+
|
|
126
|
+
Default response is a `HTTP/1.1` `200 (OK)` without any body.
|
|
127
|
+
|
|
128
|
+
### How response is selected
|
|
129
|
+
|
|
130
|
+
In case more than one response match request, the first one not yet sent (according to the registration order) will be sent.
|
|
131
|
+
|
|
132
|
+
In case all matching responses have been sent once, the request will [not be considered as matched](#in-case-no-response-can-be-found) [(unless you turned `can_send_already_matched_responses` option on)](#allow-to-register-a-response-for-more-than-one-request).
|
|
133
|
+
|
|
134
|
+
You can add criteria so that response will be sent only in case of a more specific matching.
|
|
135
|
+
|
|
136
|
+
#### Matching on URL
|
|
137
|
+
|
|
138
|
+
`url` parameter can either be a string, a python [re.Pattern](https://docs.python.org/3/library/re.html) instance or a [httpx2.URL](https://httpx2.pydantic.dev/api/#url) instance.
|
|
139
|
+
|
|
140
|
+
Matching is performed on the full URL, query parameters included.
|
|
141
|
+
|
|
142
|
+
Order of parameters in the query string does not matter, however order of values do matter if the same parameter is provided more than once.
|
|
143
|
+
|
|
144
|
+
```python
|
|
145
|
+
import httpx2
|
|
146
|
+
import re
|
|
147
|
+
from pytest_httpx2 import HTTPXMock
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def test_url(httpx_mock: HTTPXMock):
|
|
151
|
+
httpx_mock.add_response(url="https://test_url?a=1&b=2")
|
|
152
|
+
|
|
153
|
+
with httpx2.Client() as client:
|
|
154
|
+
response1 = client.delete("https://test_url?a=1&b=2")
|
|
155
|
+
response2 = client.get("https://test_url?b=2&a=1")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def test_url_as_pattern(httpx_mock: HTTPXMock):
|
|
159
|
+
httpx_mock.add_response(url=re.compile(".*test.*"))
|
|
160
|
+
|
|
161
|
+
with httpx2.Client() as client:
|
|
162
|
+
response = client.get("https://test_url")
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def test_url_as_httpx2_url(httpx_mock: HTTPXMock):
|
|
166
|
+
httpx_mock.add_response(url=httpx2.URL("https://test_url", params={"a": "1", "b": "2"}))
|
|
167
|
+
|
|
168
|
+
with httpx2.Client() as client:
|
|
169
|
+
response = client.get("https://test_url?a=1&b=2")
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
##### Ignoring query parameters
|
|
173
|
+
|
|
174
|
+
Use a python [re.Pattern](https://docs.python.org/3/library/re.html) instance to ignore query parameters while matching on the URL.
|
|
175
|
+
|
|
176
|
+
```python
|
|
177
|
+
import httpx2
|
|
178
|
+
import re
|
|
179
|
+
from pytest_httpx2 import HTTPXMock
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def test_url_as_pattern_ignoring_query_parameters(httpx_mock: HTTPXMock):
|
|
183
|
+
httpx_mock.add_response(url=re.compile("https://test_url/something.*"))
|
|
184
|
+
|
|
185
|
+
with httpx2.Client() as client:
|
|
186
|
+
response = client.get("https://test_url/something?a=1&b=2")
|
|
187
|
+
assert response.content == b""
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
#### Matching on query parameters
|
|
191
|
+
|
|
192
|
+
Use `match_params` to partially match query parameters without having to provide a regular expression as `url`.
|
|
193
|
+
|
|
194
|
+
If this parameter is provided, `url` parameter must not contain any query parameter.
|
|
195
|
+
|
|
196
|
+
All query parameters have to be provided. You can however use `unittest.mock.ANY` to do partial matching.
|
|
197
|
+
|
|
198
|
+
```python
|
|
199
|
+
import httpx2
|
|
200
|
+
from pytest_httpx2 import HTTPXMock
|
|
201
|
+
from unittest.mock import ANY
|
|
202
|
+
|
|
203
|
+
def test_partial_params_matching(httpx_mock: HTTPXMock):
|
|
204
|
+
httpx_mock.add_response(url="https://test_url", match_params={"a": 1, "b": ANY})
|
|
205
|
+
|
|
206
|
+
with httpx2.Client() as client:
|
|
207
|
+
response = client.get("https://test_url?a=1&b=2")
|
|
208
|
+
|
|
209
|
+
def test_partial_multi_params_matching(httpx_mock: HTTPXMock):
|
|
210
|
+
httpx_mock.add_response(url="https://test_url", match_params={"a": ["1", 3], "b": ["2", ANY]})
|
|
211
|
+
|
|
212
|
+
with httpx2.Client() as client:
|
|
213
|
+
response = client.get("https://test_url?a=1&b=2&a=3&b=4")
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
#### Matching on HTTP method
|
|
217
|
+
|
|
218
|
+
Use `method` parameter to specify the HTTP method (POST, PUT, DELETE, PATCH, HEAD) to reply to.
|
|
219
|
+
|
|
220
|
+
`method` parameter must be a string. It will be upper-cased, so it can be provided lower cased.
|
|
221
|
+
|
|
222
|
+
Matching is performed on equality.
|
|
223
|
+
|
|
224
|
+
```python
|
|
225
|
+
import httpx2
|
|
226
|
+
from pytest_httpx2 import HTTPXMock
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def test_post(httpx_mock: HTTPXMock):
|
|
230
|
+
httpx_mock.add_response(method="POST")
|
|
231
|
+
|
|
232
|
+
with httpx2.Client() as client:
|
|
233
|
+
response = client.post("https://test_url")
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def test_put(httpx_mock: HTTPXMock):
|
|
237
|
+
httpx_mock.add_response(method="PUT")
|
|
238
|
+
|
|
239
|
+
with httpx2.Client() as client:
|
|
240
|
+
response = client.put("https://test_url")
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def test_delete(httpx_mock: HTTPXMock):
|
|
244
|
+
httpx_mock.add_response(method="DELETE")
|
|
245
|
+
|
|
246
|
+
with httpx2.Client() as client:
|
|
247
|
+
response = client.delete("https://test_url")
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def test_patch(httpx_mock: HTTPXMock):
|
|
251
|
+
httpx_mock.add_response(method="PATCH")
|
|
252
|
+
|
|
253
|
+
with httpx2.Client() as client:
|
|
254
|
+
response = client.patch("https://test_url")
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def test_head(httpx_mock: HTTPXMock):
|
|
258
|
+
httpx_mock.add_response(method="HEAD")
|
|
259
|
+
|
|
260
|
+
with httpx2.Client() as client:
|
|
261
|
+
response = client.head("https://test_url")
|
|
262
|
+
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
#### Matching on proxy URL
|
|
266
|
+
|
|
267
|
+
`proxy_url` parameter can either be a string, a python [re.Pattern](https://docs.python.org/3/library/re.html) instance or a [httpx2.URL](https://httpx2.pydantic.dev/api/#url) instance.
|
|
268
|
+
|
|
269
|
+
Matching is performed on the full proxy URL, query parameters included.
|
|
270
|
+
|
|
271
|
+
Order of parameters in the query string does not matter, however order of values do matter if the same parameter is provided more than once.
|
|
272
|
+
|
|
273
|
+
```python
|
|
274
|
+
import httpx2
|
|
275
|
+
from pytest_httpx2 import HTTPXMock
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def test_proxy_url(httpx_mock: HTTPXMock):
|
|
279
|
+
httpx_mock.add_response(proxy_url="http://test_proxy_url?b=1&a=2")
|
|
280
|
+
|
|
281
|
+
with httpx2.Client(proxy="http://test_proxy_url?a=2&b=1") as client:
|
|
282
|
+
response = client.get("https://test_url")
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
#### Matching on HTTP headers
|
|
286
|
+
|
|
287
|
+
Use `match_headers` parameter to specify the HTTP headers (as a dict) to reply to.
|
|
288
|
+
|
|
289
|
+
Matching is performed on equality for each provided header.
|
|
290
|
+
|
|
291
|
+
```python
|
|
292
|
+
import httpx2
|
|
293
|
+
from pytest_httpx2 import HTTPXMock
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def test_headers_matching(httpx_mock: HTTPXMock):
|
|
297
|
+
httpx_mock.add_response(match_headers={'User-Agent': 'python-httpx2/2.2.0'})
|
|
298
|
+
|
|
299
|
+
with httpx2.Client() as client:
|
|
300
|
+
response = client.get("https://test_url")
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
#### Matching on HTTP body
|
|
304
|
+
|
|
305
|
+
Use `match_content` parameter to specify the full HTTP body (as bytes) to reply to.
|
|
306
|
+
|
|
307
|
+
Matching is performed on equality.
|
|
308
|
+
|
|
309
|
+
```python
|
|
310
|
+
import httpx2
|
|
311
|
+
from pytest_httpx2 import HTTPXMock
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def test_content_matching(httpx_mock: HTTPXMock):
|
|
315
|
+
httpx_mock.add_response(match_content=b"This is the body")
|
|
316
|
+
|
|
317
|
+
with httpx2.Client() as client:
|
|
318
|
+
response = client.post("https://test_url", content=b"This is the body")
|
|
319
|
+
```
|
|
320
|
+
|
|
321
|
+
##### Matching on HTTP JSON body
|
|
322
|
+
|
|
323
|
+
Use `match_json` parameter to specify the JSON decoded HTTP body to reply to.
|
|
324
|
+
|
|
325
|
+
Matching is performed on equality. You can however use `unittest.mock.ANY` to do partial matching.
|
|
326
|
+
|
|
327
|
+
```python
|
|
328
|
+
import httpx2
|
|
329
|
+
from pytest_httpx2 import HTTPXMock
|
|
330
|
+
from unittest.mock import ANY
|
|
331
|
+
|
|
332
|
+
def test_json_matching(httpx_mock: HTTPXMock):
|
|
333
|
+
httpx_mock.add_response(match_json={"a": "json", "b": 2})
|
|
334
|
+
|
|
335
|
+
with httpx2.Client() as client:
|
|
336
|
+
response = client.post("https://test_url", json={"a": "json", "b": 2})
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def test_partial_json_matching(httpx_mock: HTTPXMock):
|
|
340
|
+
httpx_mock.add_response(match_json={"a": "json", "b": ANY})
|
|
341
|
+
|
|
342
|
+
with httpx2.Client() as client:
|
|
343
|
+
response = client.post("https://test_url", json={"a": "json", "b": 2})
|
|
344
|
+
```
|
|
345
|
+
|
|
346
|
+
Note that `match_content` or `match_files` cannot be provided if `match_json` is also provided.
|
|
347
|
+
|
|
348
|
+
##### Matching on HTTP multipart body
|
|
349
|
+
|
|
350
|
+
Use `match_files` and `match_data` parameters to specify the full multipart body to reply to.
|
|
351
|
+
|
|
352
|
+
Matching is performed on equality.
|
|
353
|
+
|
|
354
|
+
```python
|
|
355
|
+
import httpx2
|
|
356
|
+
from pytest_httpx2 import HTTPXMock
|
|
357
|
+
|
|
358
|
+
def test_multipart_matching(httpx_mock: HTTPXMock):
|
|
359
|
+
httpx_mock.add_response(match_files={"name": ("file_name", b"File content")}, match_data={"field": "value"})
|
|
360
|
+
|
|
361
|
+
with httpx2.Client() as client:
|
|
362
|
+
response = client.post("https://test_url", files={"name": ("file_name", b"File content")}, data={"field": "value"})
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
Note that `match_content` or `match_json` cannot be provided if `match_files` is also provided.
|
|
366
|
+
|
|
367
|
+
#### Matching on extensions
|
|
368
|
+
|
|
369
|
+
Use `match_extensions` parameter to specify the extensions (as a dict) to reply to.
|
|
370
|
+
|
|
371
|
+
Matching is performed on equality for each provided extension.
|
|
372
|
+
|
|
373
|
+
```python
|
|
374
|
+
import httpx2
|
|
375
|
+
from pytest_httpx2 import HTTPXMock
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def test_extensions_matching(httpx_mock: HTTPXMock):
|
|
379
|
+
httpx_mock.add_response(match_extensions={'test': 'value'})
|
|
380
|
+
|
|
381
|
+
with httpx2.Client() as client:
|
|
382
|
+
response = client.get("https://test_url", extensions={"test": "value"})
|
|
383
|
+
```
|
|
384
|
+
|
|
385
|
+
##### Matching on HTTP timeout(s)
|
|
386
|
+
|
|
387
|
+
Use `match_extensions` parameter to specify the timeouts (as a dict) to reply to.
|
|
388
|
+
|
|
389
|
+
Matching is performed on the full timeout dict equality.
|
|
390
|
+
|
|
391
|
+
```python
|
|
392
|
+
import httpx2
|
|
393
|
+
from pytest_httpx2 import HTTPXMock
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def test_timeout_matching(httpx_mock: HTTPXMock):
|
|
397
|
+
httpx_mock.add_response(match_extensions={'timeout': {'connect': 10, 'read': 10, 'write': 10, 'pool': 10}})
|
|
398
|
+
|
|
399
|
+
with httpx2.Client() as client:
|
|
400
|
+
response = client.get("https://test_url", timeout=10)
|
|
401
|
+
```
|
|
402
|
+
|
|
403
|
+
### Add JSON response
|
|
404
|
+
|
|
405
|
+
Use `json` parameter to add a JSON response using python values.
|
|
406
|
+
|
|
407
|
+
```python
|
|
408
|
+
import httpx2
|
|
409
|
+
from pytest_httpx2 import HTTPXMock
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def test_json(httpx_mock: HTTPXMock):
|
|
413
|
+
httpx_mock.add_response(json=[{"key1": "value1", "key2": "value2"}])
|
|
414
|
+
|
|
415
|
+
with httpx2.Client() as client:
|
|
416
|
+
assert client.get("https://test_url").json() == [{"key1": "value1", "key2": "value2"}]
|
|
417
|
+
|
|
418
|
+
```
|
|
419
|
+
|
|
420
|
+
Note that the `content-type` header will be set to `application/json` by default in the response.
|
|
421
|
+
|
|
422
|
+
### Reply with custom body
|
|
423
|
+
|
|
424
|
+
Use `text` parameter to reply with a custom body by providing UTF-8 encoded string.
|
|
425
|
+
|
|
426
|
+
```python
|
|
427
|
+
import httpx2
|
|
428
|
+
from pytest_httpx2 import HTTPXMock
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def test_str_body(httpx_mock: HTTPXMock):
|
|
432
|
+
httpx_mock.add_response(text="This is my UTF-8 content")
|
|
433
|
+
|
|
434
|
+
with httpx2.Client() as client:
|
|
435
|
+
assert client.get("https://test_url").text == "This is my UTF-8 content"
|
|
436
|
+
|
|
437
|
+
```
|
|
438
|
+
|
|
439
|
+
Use `content` parameter to reply with a custom body by providing bytes.
|
|
440
|
+
|
|
441
|
+
```python
|
|
442
|
+
import httpx2
|
|
443
|
+
from pytest_httpx2 import HTTPXMock
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def test_bytes_body(httpx_mock: HTTPXMock):
|
|
447
|
+
httpx_mock.add_response(content=b"This is my bytes content")
|
|
448
|
+
|
|
449
|
+
with httpx2.Client() as client:
|
|
450
|
+
assert client.get("https://test_url").content == b"This is my bytes content"
|
|
451
|
+
|
|
452
|
+
```
|
|
453
|
+
|
|
454
|
+
Use `html` parameter to reply with a custom body by providing UTF-8 encoded string.
|
|
455
|
+
|
|
456
|
+
```python
|
|
457
|
+
import httpx2
|
|
458
|
+
from pytest_httpx2 import HTTPXMock
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def test_html_body(httpx_mock: HTTPXMock):
|
|
462
|
+
httpx_mock.add_response(html="<body>This is <p> HTML content</body>")
|
|
463
|
+
|
|
464
|
+
with httpx2.Client() as client:
|
|
465
|
+
assert client.get("https://test_url").text == "<body>This is <p> HTML content</body>"
|
|
466
|
+
|
|
467
|
+
```
|
|
468
|
+
|
|
469
|
+
### Reply by streaming chunks
|
|
470
|
+
|
|
471
|
+
Use `stream` parameter (as `httpx2.SyncByteStream` or `httpx2.AsyncByteStream`) to stream chunks that you specify.
|
|
472
|
+
|
|
473
|
+
Note that `pytest_httpx2.IteratorStream` can be used to provide an iterable.
|
|
474
|
+
|
|
475
|
+
```python
|
|
476
|
+
import httpx2
|
|
477
|
+
import pytest
|
|
478
|
+
from pytest_httpx2 import HTTPXMock, IteratorStream
|
|
479
|
+
|
|
480
|
+
def test_sync_streaming(httpx_mock: HTTPXMock):
|
|
481
|
+
httpx_mock.add_response(stream=IteratorStream([b"part 1", b"part 2"]))
|
|
482
|
+
|
|
483
|
+
with httpx2.Client() as client:
|
|
484
|
+
with client.stream(method="GET", url="https://test_url") as response:
|
|
485
|
+
assert list(response.iter_raw()) == [b"part 1", b"part 2"]
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
@pytest.mark.asyncio
|
|
489
|
+
async def test_async_streaming(httpx_mock: HTTPXMock):
|
|
490
|
+
httpx_mock.add_response(stream=IteratorStream([b"part 1", b"part 2"]))
|
|
491
|
+
|
|
492
|
+
async with httpx2.AsyncClient() as client:
|
|
493
|
+
async with client.stream(method="GET", url="https://test_url") as response:
|
|
494
|
+
assert [part async for part in response.aiter_raw()] == [b"part 1", b"part 2"]
|
|
495
|
+
|
|
496
|
+
```
|
|
497
|
+
|
|
498
|
+
### Add multipart response
|
|
499
|
+
|
|
500
|
+
Use the httpx2 `MultipartStream` via the `stream` parameter to send a multipart response.
|
|
501
|
+
|
|
502
|
+
Reach out to `httpx2` developers if you need this publicly exposed as [this is not a standard use case](https://github.com/pydantic/httpx2/issues#issuecomment-633584819).
|
|
503
|
+
|
|
504
|
+
```python
|
|
505
|
+
import httpx2
|
|
506
|
+
from httpx2._multipart import MultipartStream
|
|
507
|
+
from pytest_httpx2 import HTTPXMock
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def test_multipart_body(httpx_mock: HTTPXMock):
|
|
511
|
+
httpx_mock.add_response(stream=MultipartStream(data={"key1": "value1"}, files={"file1": b"content of file 1"}, boundary=b"2256d3a36d2a61a1eba35a22bee5c74a"))
|
|
512
|
+
|
|
513
|
+
with httpx2.Client() as client:
|
|
514
|
+
assert client.get("https://test_url").text == '''--2256d3a36d2a61a1eba35a22bee5c74a\r
|
|
515
|
+
Content-Disposition: form-data; name="key1"\r
|
|
516
|
+
\r
|
|
517
|
+
value1\r
|
|
518
|
+
--2256d3a36d2a61a1eba35a22bee5c74a\r
|
|
519
|
+
Content-Disposition: form-data; name="file1"; filename="upload"\r
|
|
520
|
+
Content-Type: application/octet-stream\r
|
|
521
|
+
\r
|
|
522
|
+
content of file 1\r
|
|
523
|
+
--2256d3a36d2a61a1eba35a22bee5c74a--\r
|
|
524
|
+
'''
|
|
525
|
+
|
|
526
|
+
```
|
|
527
|
+
|
|
528
|
+
### Add non 200 response
|
|
529
|
+
|
|
530
|
+
Use `status_code` parameter to specify the HTTP status code (as an int) of the response.
|
|
531
|
+
|
|
532
|
+
```python
|
|
533
|
+
import httpx2
|
|
534
|
+
from pytest_httpx2 import HTTPXMock
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def test_status_code(httpx_mock: HTTPXMock):
|
|
538
|
+
httpx_mock.add_response(status_code=404)
|
|
539
|
+
|
|
540
|
+
with httpx2.Client() as client:
|
|
541
|
+
assert client.get("https://test_url").status_code == 404
|
|
542
|
+
|
|
543
|
+
```
|
|
544
|
+
|
|
545
|
+
### Reply with custom headers
|
|
546
|
+
|
|
547
|
+
Use `headers` parameter to specify the extra headers of the response.
|
|
548
|
+
|
|
549
|
+
Any valid httpx2 headers type is supported, you can submit headers as a dict (str or bytes), a list of 2-tuples (str or bytes) or a [`httpx2.Headers`](https://httpx2.pydantic.dev/api/#headers) instance.
|
|
550
|
+
|
|
551
|
+
```python
|
|
552
|
+
import httpx2
|
|
553
|
+
from pytest_httpx2 import HTTPXMock
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
def test_headers_as_str_dict(httpx_mock: HTTPXMock):
|
|
557
|
+
httpx_mock.add_response(headers={"X-Header1": "Test value"})
|
|
558
|
+
|
|
559
|
+
with httpx2.Client() as client:
|
|
560
|
+
assert client.get("https://test_url").headers["x-header1"] == "Test value"
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def test_headers_as_str_tuple_list(httpx_mock: HTTPXMock):
|
|
564
|
+
httpx_mock.add_response(headers=[("X-Header1", "Test value")])
|
|
565
|
+
|
|
566
|
+
with httpx2.Client() as client:
|
|
567
|
+
assert client.get("https://test_url").headers["x-header1"] == "Test value"
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def test_headers_as_httpx2_headers(httpx_mock: HTTPXMock):
|
|
571
|
+
httpx_mock.add_response(headers=httpx2.Headers({b"X-Header1": b"Test value"}))
|
|
572
|
+
|
|
573
|
+
with httpx2.Client() as client:
|
|
574
|
+
assert client.get("https://test_url").headers["x-header1"] == "Test value"
|
|
575
|
+
|
|
576
|
+
```
|
|
577
|
+
|
|
578
|
+
#### Reply with cookies
|
|
579
|
+
|
|
580
|
+
Cookies are sent in the `set-cookie` HTTP header.
|
|
581
|
+
|
|
582
|
+
You can then send cookies in the response by setting the `set-cookie` header with [the value following key=value format](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie).
|
|
583
|
+
|
|
584
|
+
```python
|
|
585
|
+
import httpx2
|
|
586
|
+
from pytest_httpx2 import HTTPXMock
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
def test_cookie(httpx_mock: HTTPXMock):
|
|
590
|
+
httpx_mock.add_response(headers={"set-cookie": "key=value"})
|
|
591
|
+
|
|
592
|
+
with httpx2.Client() as client:
|
|
593
|
+
response = client.get("https://test_url")
|
|
594
|
+
assert dict(response.cookies) == {"key": "value"}
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
def test_cookies(httpx_mock: HTTPXMock):
|
|
598
|
+
httpx_mock.add_response(headers=[("set-cookie", "key=value"), ("set-cookie", "key2=value2")])
|
|
599
|
+
|
|
600
|
+
with httpx2.Client() as client:
|
|
601
|
+
response = client.get("https://test_url")
|
|
602
|
+
assert dict(response.cookies) == {"key": "value", "key2": "value2"}
|
|
603
|
+
|
|
604
|
+
```
|
|
605
|
+
|
|
606
|
+
|
|
607
|
+
### Add HTTP/2.0 response
|
|
608
|
+
|
|
609
|
+
Use `http_version` parameter to specify the HTTP protocol version (as a string) of the response.
|
|
610
|
+
|
|
611
|
+
```python
|
|
612
|
+
import httpx2
|
|
613
|
+
from pytest_httpx2 import HTTPXMock
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
def test_http_version(httpx_mock: HTTPXMock):
|
|
617
|
+
httpx_mock.add_response(http_version="HTTP/2.0")
|
|
618
|
+
|
|
619
|
+
with httpx2.Client() as client:
|
|
620
|
+
assert client.get("https://test_url").http_version == "HTTP/2.0"
|
|
621
|
+
|
|
622
|
+
```
|
|
623
|
+
|
|
624
|
+
## Add callbacks
|
|
625
|
+
|
|
626
|
+
You can perform custom manipulation upon request reception by registering callbacks.
|
|
627
|
+
|
|
628
|
+
Callback should expect one parameter, the received [`httpx2.Request`](https://httpx2.pydantic.dev/api/#request).
|
|
629
|
+
|
|
630
|
+
If all callbacks are not executed during test execution, the test case will fail at teardown [(unless you turned `assert_all_responses_were_requested` option off)](#allow-to-register-more-responses-than-what-will-be-requested).
|
|
631
|
+
|
|
632
|
+
Note that callbacks are considered as responses, and thus are [selected the same way](#how-response-is-selected).
|
|
633
|
+
Meaning that you can transpose `httpx_mock.add_response` calls in the related examples into `httpx_mock.add_callback`.
|
|
634
|
+
|
|
635
|
+
### Dynamic responses
|
|
636
|
+
|
|
637
|
+
Callback should return a [`httpx2.Response`](https://httpx2.pydantic.dev/api/#response) instance.
|
|
638
|
+
|
|
639
|
+
```python
|
|
640
|
+
import httpx2
|
|
641
|
+
from pytest_httpx2 import HTTPXMock
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
def test_dynamic_response(httpx_mock: HTTPXMock):
|
|
645
|
+
def custom_response(request: httpx2.Request):
|
|
646
|
+
return httpx2.Response(
|
|
647
|
+
status_code=200, json={"url": str(request.url)},
|
|
648
|
+
)
|
|
649
|
+
|
|
650
|
+
httpx_mock.add_callback(custom_response)
|
|
651
|
+
|
|
652
|
+
with httpx2.Client() as client:
|
|
653
|
+
response = client.get("https://test_url")
|
|
654
|
+
assert response.json() == {"url": "https://test_url"}
|
|
655
|
+
|
|
656
|
+
```
|
|
657
|
+
|
|
658
|
+
Alternatively, callbacks can also be asynchronous.
|
|
659
|
+
|
|
660
|
+
As in the following sample simulating network latency on some responses only.
|
|
661
|
+
|
|
662
|
+
```python
|
|
663
|
+
import asyncio
|
|
664
|
+
import httpx2
|
|
665
|
+
import pytest
|
|
666
|
+
from pytest_httpx2 import HTTPXMock
|
|
667
|
+
|
|
668
|
+
|
|
669
|
+
@pytest.mark.asyncio
|
|
670
|
+
async def test_dynamic_async_response(httpx_mock: HTTPXMock):
|
|
671
|
+
async def simulate_network_latency(request: httpx2.Request):
|
|
672
|
+
await asyncio.sleep(1)
|
|
673
|
+
return httpx2.Response(
|
|
674
|
+
status_code=200, json={"url": str(request.url)},
|
|
675
|
+
)
|
|
676
|
+
|
|
677
|
+
httpx_mock.add_callback(simulate_network_latency)
|
|
678
|
+
httpx_mock.add_response()
|
|
679
|
+
|
|
680
|
+
async with httpx2.AsyncClient() as client:
|
|
681
|
+
responses = await asyncio.gather(
|
|
682
|
+
# Response will be received after one second
|
|
683
|
+
client.get("https://test_url"),
|
|
684
|
+
# Response will instantly be received (1 second before the first request)
|
|
685
|
+
client.get("https://test_url")
|
|
686
|
+
)
|
|
687
|
+
|
|
688
|
+
```
|
|
689
|
+
|
|
690
|
+
### Raising exceptions
|
|
691
|
+
|
|
692
|
+
You can simulate HTTPX2 exception throwing by raising an exception in your callback or use `httpx_mock.add_exception` with the exception instance.
|
|
693
|
+
|
|
694
|
+
This can be useful if you want to assert that your code handles HTTPX2 exceptions properly.
|
|
695
|
+
|
|
696
|
+
```python
|
|
697
|
+
import httpx2
|
|
698
|
+
import pytest
|
|
699
|
+
from pytest_httpx2 import HTTPXMock
|
|
700
|
+
|
|
701
|
+
|
|
702
|
+
def test_exception_raising(httpx_mock: HTTPXMock):
|
|
703
|
+
httpx_mock.add_exception(httpx2.ReadTimeout("Unable to read within timeout"))
|
|
704
|
+
|
|
705
|
+
with httpx2.Client() as client:
|
|
706
|
+
with pytest.raises(httpx2.ReadTimeout):
|
|
707
|
+
client.get("https://test_url")
|
|
708
|
+
|
|
709
|
+
```
|
|
710
|
+
|
|
711
|
+
#### In case no response can be found
|
|
712
|
+
|
|
713
|
+
The default behavior is to instantly raise a [`httpx2.TimeoutException`](https://httpx2.pydantic.dev/advanced/timeouts/) in case no matching response can be found.
|
|
714
|
+
|
|
715
|
+
The exception message will display the request and every registered responses to help you identify any possible mismatch.
|
|
716
|
+
|
|
717
|
+
```python
|
|
718
|
+
import httpx2
|
|
719
|
+
import pytest
|
|
720
|
+
from pytest_httpx2 import HTTPXMock
|
|
721
|
+
|
|
722
|
+
|
|
723
|
+
@pytest.mark.httpx_mock(assert_all_requests_were_expected=False)
|
|
724
|
+
def test_timeout(httpx_mock: HTTPXMock):
|
|
725
|
+
with httpx2.Client() as client:
|
|
726
|
+
with pytest.raises(httpx2.TimeoutException):
|
|
727
|
+
client.get("https://test_url")
|
|
728
|
+
|
|
729
|
+
```
|
|
730
|
+
|
|
731
|
+
## Check sent requests
|
|
732
|
+
|
|
733
|
+
The best way to ensure the content of your requests is still to use the `match_headers` and / or `match_content` parameters when adding a response.
|
|
734
|
+
In the same spirit, ensuring that no request was issued does not necessarily require any code [(unless you turned `assert_all_requests_were_expected` option off)](#allow-to-not-register-responses-for-every-request).
|
|
735
|
+
|
|
736
|
+
In any case, you always have the ability to retrieve the requests that were issued.
|
|
737
|
+
|
|
738
|
+
As in the following samples:
|
|
739
|
+
|
|
740
|
+
```python
|
|
741
|
+
import httpx2
|
|
742
|
+
from pytest_httpx2 import HTTPXMock
|
|
743
|
+
|
|
744
|
+
|
|
745
|
+
def test_many_requests(httpx_mock: HTTPXMock):
|
|
746
|
+
httpx_mock.add_response()
|
|
747
|
+
|
|
748
|
+
with httpx2.Client() as client:
|
|
749
|
+
response1 = client.get("https://test_url")
|
|
750
|
+
response2 = client.get("https://test_url")
|
|
751
|
+
|
|
752
|
+
requests = httpx_mock.get_requests()
|
|
753
|
+
|
|
754
|
+
|
|
755
|
+
def test_single_request(httpx_mock: HTTPXMock):
|
|
756
|
+
httpx_mock.add_response()
|
|
757
|
+
|
|
758
|
+
with httpx2.Client() as client:
|
|
759
|
+
response = client.get("https://test_url")
|
|
760
|
+
|
|
761
|
+
request = httpx_mock.get_request()
|
|
762
|
+
|
|
763
|
+
|
|
764
|
+
def test_no_request(httpx_mock: HTTPXMock):
|
|
765
|
+
assert not httpx_mock.get_request()
|
|
766
|
+
```
|
|
767
|
+
|
|
768
|
+
### How requests are selected
|
|
769
|
+
|
|
770
|
+
You can add criteria so that requests will be returned only in case of a more specific matching.
|
|
771
|
+
|
|
772
|
+
Note that requests are [selected the same way as responses](#how-response-is-selected).
|
|
773
|
+
Meaning that you can transpose `httpx_mock.add_response` calls in the related examples into `httpx_mock.get_requests` or `httpx_mock.get_request`.
|
|
774
|
+
|
|
775
|
+
## Configuring httpx_mock
|
|
776
|
+
|
|
777
|
+
The `httpx_mock` marker is available and can be used to change the default behavior of the `httpx_mock` fixture.
|
|
778
|
+
|
|
779
|
+
Refer to [available options](#available-options) for an exhaustive list of options that can be set [per test](#per-test), [per module](#per-module) or even [on the whole test suite](#for-the-whole-test-suite).
|
|
780
|
+
|
|
781
|
+
### Per test
|
|
782
|
+
|
|
783
|
+
```python
|
|
784
|
+
import pytest
|
|
785
|
+
|
|
786
|
+
@pytest.mark.httpx_mock(assert_all_responses_were_requested=False)
|
|
787
|
+
def test_something(httpx_mock):
|
|
788
|
+
...
|
|
789
|
+
```
|
|
790
|
+
|
|
791
|
+
### Per module
|
|
792
|
+
|
|
793
|
+
```python
|
|
794
|
+
import pytest
|
|
795
|
+
|
|
796
|
+
pytestmark = pytest.mark.httpx_mock(assert_all_responses_were_requested=False)
|
|
797
|
+
```
|
|
798
|
+
|
|
799
|
+
### For the whole test suite
|
|
800
|
+
|
|
801
|
+
This should be set in the root `conftest.py` file.
|
|
802
|
+
```python
|
|
803
|
+
import pytest
|
|
804
|
+
|
|
805
|
+
def pytest_collection_modifyitems(session, config, items):
|
|
806
|
+
for item in items:
|
|
807
|
+
item.add_marker(pytest.mark.httpx_mock(assert_all_responses_were_requested=False))
|
|
808
|
+
```
|
|
809
|
+
|
|
810
|
+
> [!IMPORTANT]
|
|
811
|
+
> Note that [there currently is a bug in pytest](https://github.com/pytest-dev/pytest/issues/10406) where `pytest_collection_modifyitems` will actually add the marker AFTER its `module` and `class` registration.
|
|
812
|
+
>
|
|
813
|
+
> Meaning the order is currently:
|
|
814
|
+
> module -> class -> test suite -> test
|
|
815
|
+
>
|
|
816
|
+
> instead of:
|
|
817
|
+
> test suite -> module -> class -> test
|
|
818
|
+
|
|
819
|
+
### Available options
|
|
820
|
+
|
|
821
|
+
#### Allow to register more responses than what will be requested
|
|
822
|
+
|
|
823
|
+
By default, `httpx2-pytest` will ensure that every response was requested during test execution.
|
|
824
|
+
|
|
825
|
+
If you want to add an optional response, you can use the `is_optional` parameter when [registering a response](#add-responses) or [a callback](#add-callbacks).
|
|
826
|
+
|
|
827
|
+
```python
|
|
828
|
+
def test_fewer_requests_than_expected(httpx_mock):
|
|
829
|
+
# Even if this response never received a corresponding request, the test will not fail at teardown
|
|
830
|
+
httpx_mock.add_response(is_optional=True)
|
|
831
|
+
```
|
|
832
|
+
|
|
833
|
+
If you don't have control over the response registration process (shared fixtures),
|
|
834
|
+
and you want to allow fewer requests than what you registered responses for,
|
|
835
|
+
you can use the `httpx_mock` marker `assert_all_responses_were_requested` option.
|
|
836
|
+
|
|
837
|
+
> [!CAUTION]
|
|
838
|
+
> Use this option at your own risk of not spotting regression (requests not sent) in your code base!
|
|
839
|
+
|
|
840
|
+
```python
|
|
841
|
+
import pytest
|
|
842
|
+
|
|
843
|
+
@pytest.mark.httpx_mock(assert_all_responses_were_requested=False)
|
|
844
|
+
def test_fewer_requests_than_expected(httpx_mock):
|
|
845
|
+
# Even if this response never received a corresponding request, the test will not fail at teardown
|
|
846
|
+
httpx_mock.add_response()
|
|
847
|
+
```
|
|
848
|
+
|
|
849
|
+
Note that the `is_optional` parameter will take precedence over the `assert_all_responses_were_requested` option.
|
|
850
|
+
Meaning you can still register a response that will be checked for execution at teardown even if `assert_all_responses_were_requested` was set to `False`.
|
|
851
|
+
|
|
852
|
+
```python
|
|
853
|
+
import pytest
|
|
854
|
+
|
|
855
|
+
@pytest.mark.httpx_mock(assert_all_responses_were_requested=False)
|
|
856
|
+
def test_force_expected_request(httpx_mock):
|
|
857
|
+
# Even if the assert_all_responses_were_requested option is set, the test will fail at teardown if this is not matched
|
|
858
|
+
httpx_mock.add_response(is_optional=False)
|
|
859
|
+
```
|
|
860
|
+
|
|
861
|
+
#### Allow to not register responses for every request
|
|
862
|
+
|
|
863
|
+
By default, `httpx2-pytest` will ensure that every request that was issued was expected.
|
|
864
|
+
|
|
865
|
+
You can use the `httpx_mock` marker `assert_all_requests_were_expected` option to allow more requests than what you registered responses for.
|
|
866
|
+
|
|
867
|
+
> [!CAUTION]
|
|
868
|
+
> Use this option at your own risk of not spotting regression (unexpected requests) in your code base!
|
|
869
|
+
|
|
870
|
+
```python
|
|
871
|
+
import pytest
|
|
872
|
+
import httpx2
|
|
873
|
+
|
|
874
|
+
@pytest.mark.httpx_mock(assert_all_requests_were_expected=False)
|
|
875
|
+
def test_more_requests_than_expected(httpx_mock):
|
|
876
|
+
with httpx2.Client() as client:
|
|
877
|
+
# Even if this request was not expected, the test will not fail at teardown
|
|
878
|
+
with pytest.raises(httpx2.TimeoutException):
|
|
879
|
+
client.get("https://test_url")
|
|
880
|
+
```
|
|
881
|
+
|
|
882
|
+
#### Allow to register a response for more than one request
|
|
883
|
+
|
|
884
|
+
By default, `httpx2-pytest` will ensure that every request that was issued was expected.
|
|
885
|
+
|
|
886
|
+
If you want to add a response once, while allowing it to match more than once, you can use the `is_reusable` parameter when [registering a response](#add-responses) or [a callback](#add-callbacks).
|
|
887
|
+
|
|
888
|
+
```python
|
|
889
|
+
import httpx2
|
|
890
|
+
|
|
891
|
+
def test_more_requests_than_responses(httpx_mock):
|
|
892
|
+
httpx_mock.add_response(is_reusable=True)
|
|
893
|
+
with httpx2.Client() as client:
|
|
894
|
+
client.get("https://test_url")
|
|
895
|
+
# Even if only one response was registered, the test will not fail at teardown as this request will also be matched
|
|
896
|
+
client.get("https://test_url")
|
|
897
|
+
```
|
|
898
|
+
|
|
899
|
+
If you don't have control over the response registration process (shared fixtures),
|
|
900
|
+
and you want to allow multiple requests to match the same registered response,
|
|
901
|
+
you can use the `httpx_mock` marker `can_send_already_matched_responses` option.
|
|
902
|
+
|
|
903
|
+
With this option, in case all matching responses have been sent at least once, the last one (according to the registration order) will be sent.
|
|
904
|
+
|
|
905
|
+
> [!CAUTION]
|
|
906
|
+
> Use this option at your own risk of not spotting regression (requests issued more than the expected number of times) in your code base!
|
|
907
|
+
|
|
908
|
+
```python
|
|
909
|
+
import pytest
|
|
910
|
+
import httpx2
|
|
911
|
+
|
|
912
|
+
@pytest.mark.httpx_mock(can_send_already_matched_responses=True)
|
|
913
|
+
def test_more_requests_than_responses(httpx_mock):
|
|
914
|
+
httpx_mock.add_response()
|
|
915
|
+
with httpx2.Client() as client:
|
|
916
|
+
client.get("https://test_url")
|
|
917
|
+
# Even if only one response was registered, the test will not fail at teardown as this request will also be matched
|
|
918
|
+
client.get("https://test_url")
|
|
919
|
+
```
|
|
920
|
+
|
|
921
|
+
#### Do not mock some requests
|
|
922
|
+
|
|
923
|
+
By default, `httpx2-pytest` will mock every request.
|
|
924
|
+
|
|
925
|
+
But, for instance, in case you want to write integration tests with other servers, you might want to let some requests go through.
|
|
926
|
+
|
|
927
|
+
To do so, you can use the `httpx_mock` marker `should_mock` option and provide a callable expecting the [`httpx2.Request`](https://httpx2.pydantic.dev/api/#request) as parameter and returning a boolean.
|
|
928
|
+
|
|
929
|
+
Returning `True` will ensure that the request is handled by `httpx2-pytest` (mocked), `False` will let the request pass through (not mocked).
|
|
930
|
+
|
|
931
|
+
```python
|
|
932
|
+
import pytest
|
|
933
|
+
import httpx2
|
|
934
|
+
|
|
935
|
+
@pytest.mark.httpx_mock(should_mock=lambda request: request.url.host != "www.my_local_test_host")
|
|
936
|
+
def test_partial_mock(httpx_mock):
|
|
937
|
+
httpx_mock.add_response()
|
|
938
|
+
|
|
939
|
+
with httpx2.Client() as client:
|
|
940
|
+
# This request will NOT be mocked
|
|
941
|
+
response1 = client.get("https://www.my_local_test_host/sub?param=value")
|
|
942
|
+
# This request will be mocked
|
|
943
|
+
response2 = client.get("https://test_url")
|
|
944
|
+
```
|
|
945
|
+
|
|
946
|
+
## Migrating to httpx2-pytest
|
|
947
|
+
|
|
948
|
+
Here is how to migrate from well-known testing libraries to `httpx2-pytest`.
|
|
949
|
+
|
|
950
|
+
### From responses
|
|
951
|
+
|
|
952
|
+
| Feature | responses | httpx2-pytest |
|
|
953
|
+
|:------------------|:---------------------------|:----------------------------|
|
|
954
|
+
| Add a response | `responses.add()` | `httpx_mock.add_response()` |
|
|
955
|
+
| Add a callback | `responses.add_callback()` | `httpx_mock.add_callback()` |
|
|
956
|
+
| Retrieve requests | `responses.calls` | `httpx_mock.get_requests()` |
|
|
957
|
+
|
|
958
|
+
#### Add a response or a callback
|
|
959
|
+
|
|
960
|
+
Undocumented parameters means that they are unchanged between `responses` and `httpx2-pytest`.
|
|
961
|
+
Below is a list of parameters that will require a change in your code.
|
|
962
|
+
|
|
963
|
+
| Parameter | responses | httpx2-pytest |
|
|
964
|
+
|:---------------------|:------------------------------------|:---------------------------------------------------------------------|
|
|
965
|
+
| method | `method=responses.GET` | `method="GET"` |
|
|
966
|
+
| body (as bytes) | `body=b"sample"` | `content=b"sample"` |
|
|
967
|
+
| body (as str) | `body="sample"` | `text="sample"` |
|
|
968
|
+
| status code | `status=201` | `status_code=201` |
|
|
969
|
+
| headers | `adding_headers={"name": "value"}` | `headers={"name": "value"}` |
|
|
970
|
+
| content-type header | `content_type="application/custom"` | `headers={"content-type": "application/custom"}` |
|
|
971
|
+
| Match the full query | `match_querystring=True` | The full query is always matched when providing the `url` parameter. |
|
|
972
|
+
|
|
973
|
+
Sample adding a response with `responses`:
|
|
974
|
+
```python
|
|
975
|
+
from responses import RequestsMock
|
|
976
|
+
|
|
977
|
+
def test_response(responses: RequestsMock):
|
|
978
|
+
responses.add(
|
|
979
|
+
method=responses.GET,
|
|
980
|
+
url="https://test_url",
|
|
981
|
+
body=b"This is the response content",
|
|
982
|
+
status=400,
|
|
983
|
+
)
|
|
984
|
+
|
|
985
|
+
```
|
|
986
|
+
|
|
987
|
+
Sample adding the same response with `httpx2-pytest`:
|
|
988
|
+
```python
|
|
989
|
+
from pytest_httpx2 import HTTPXMock
|
|
990
|
+
|
|
991
|
+
def test_response(httpx_mock: HTTPXMock):
|
|
992
|
+
httpx_mock.add_response(
|
|
993
|
+
method="GET",
|
|
994
|
+
url="https://test_url",
|
|
995
|
+
content=b"This is the response content",
|
|
996
|
+
status_code=400,
|
|
997
|
+
)
|
|
998
|
+
|
|
999
|
+
```
|
|
1000
|
+
|
|
1001
|
+
### From aioresponses
|
|
1002
|
+
|
|
1003
|
+
| Feature | aioresponses | httpx2-pytest |
|
|
1004
|
+
|:---------------|:------------------------|:-------------------------------------------|
|
|
1005
|
+
| Add a response | `aioresponses.method()` | `httpx_mock.add_response(method="METHOD")` |
|
|
1006
|
+
| Add a callback | `aioresponses.method()` | `httpx_mock.add_callback(method="METHOD")` |
|
|
1007
|
+
|
|
1008
|
+
#### Add a response or a callback
|
|
1009
|
+
|
|
1010
|
+
Undocumented parameters means that they are unchanged between `responses` and `httpx2-pytest`.
|
|
1011
|
+
Below is a list of parameters that will require a change in your code.
|
|
1012
|
+
|
|
1013
|
+
| Parameter | responses | httpx2-pytest |
|
|
1014
|
+
|:----------------|:---------------------|:--------------------|
|
|
1015
|
+
| body (as bytes) | `body=b"sample"` | `content=b"sample"` |
|
|
1016
|
+
| body (as str) | `body="sample"` | `text="sample"` |
|
|
1017
|
+
| body (as JSON) | `payload=["sample"]` | `json=["sample"]` |
|
|
1018
|
+
| status code | `status=201` | `status_code=201` |
|
|
1019
|
+
|
|
1020
|
+
Sample adding a response with `aioresponses`:
|
|
1021
|
+
```python
|
|
1022
|
+
import pytest
|
|
1023
|
+
from aioresponses import aioresponses
|
|
1024
|
+
|
|
1025
|
+
|
|
1026
|
+
@pytest.fixture
|
|
1027
|
+
def mock_aioresponse():
|
|
1028
|
+
with aioresponses() as m:
|
|
1029
|
+
yield m
|
|
1030
|
+
|
|
1031
|
+
|
|
1032
|
+
def test_response(mock_aioresponse):
|
|
1033
|
+
mock_aioresponse.get(
|
|
1034
|
+
url="https://test_url",
|
|
1035
|
+
body=b"This is the response content",
|
|
1036
|
+
status=400,
|
|
1037
|
+
)
|
|
1038
|
+
|
|
1039
|
+
```
|
|
1040
|
+
|
|
1041
|
+
Sample adding the same response with `httpx2-pytest`:
|
|
1042
|
+
```python
|
|
1043
|
+
def test_response(httpx_mock):
|
|
1044
|
+
httpx_mock.add_response(
|
|
1045
|
+
method="GET",
|
|
1046
|
+
url="https://test_url",
|
|
1047
|
+
content=b"This is the response content",
|
|
1048
|
+
status_code=400,
|
|
1049
|
+
)
|
|
1050
|
+
|
|
1051
|
+
```
|