test_content.py
This file
Path
tests/test_content.py
523 lines · 17.0 KiB · Python
Last changed by
Ensure JSON representation is compact. #3363 (#3367)BERRADA-Omarbefore adoption9fd6f0c
History of this fileTake it
1import io2import typing34import pytest56import httpx7from httpx._content import encode_json89method = "POST"10url = "https://www.example.com"111213@pytest.mark.anyio14async def test_empty_content():15 request = httpx.Request(method, url)16 assert isinstance(request.stream, httpx.SyncByteStream)17 assert isinstance(request.stream, httpx.AsyncByteStream)1819 sync_content = b"".join(list(request.stream))20 async_content = b"".join([part async for part in request.stream])2122 assert request.headers == {"Host": "www.example.com", "Content-Length": "0"}23 assert sync_content == b""24 assert async_content == b""252627@pytest.mark.anyio28async def test_bytes_content():29 request = httpx.Request(method, url, content=b"Hello, world!")30 assert isinstance(request.stream, typing.Iterable)31 assert isinstance(request.stream, typing.AsyncIterable)3233 sync_content = b"".join(list(request.stream))34 async_content = b"".join([part async for part in request.stream])3536 assert request.headers == {"Host": "www.example.com", "Content-Length": "13"}37 assert sync_content == b"Hello, world!"38 assert async_content == b"Hello, world!"3940 # Support 'data' for compat with requests.41 with pytest.warns(DeprecationWarning):42 request = httpx.Request(method, url, data=b"Hello, world!") # type: ignore43 assert isinstance(request.stream, typing.Iterable)44 assert isinstance(request.stream, typing.AsyncIterable)4546 sync_content = b"".join(list(request.stream))47 async_content = b"".join([part async for part in request.stream])4849 assert request.headers == {"Host": "www.example.com", "Content-Length": "13"}50 assert sync_content == b"Hello, world!"51 assert async_content == b"Hello, world!"525354@pytest.mark.anyio55async def test_bytesio_content():56 request = httpx.Request(method, url, content=io.BytesIO(b"Hello, world!"))57 assert isinstance(request.stream, typing.Iterable)58 assert not isinstance(request.stream, typing.AsyncIterable)5960 content = b"".join(list(request.stream))6162 assert request.headers == {"Host": "www.example.com", "Content-Length": "13"}63 assert content == b"Hello, world!"646566@pytest.mark.anyio67async def test_async_bytesio_content():68 class AsyncBytesIO:69 def __init__(self, content: bytes) -> None:70 self._idx = 071 self._content = content7273 async def aread(self, chunk_size: int) -> bytes:74 chunk = self._content[self._idx : self._idx + chunk_size]75 self._idx = self._idx + chunk_size76 return chunk7778 async def __aiter__(self):79 yield self._content # pragma: no cover8081 request = httpx.Request(method, url, content=AsyncBytesIO(b"Hello, world!"))82 assert not isinstance(request.stream, typing.Iterable)83 assert isinstance(request.stream, typing.AsyncIterable)8485 content = b"".join([part async for part in request.stream])8687 assert request.headers == {88 "Host": "www.example.com",89 "Transfer-Encoding": "chunked",90 }91 assert content == b"Hello, world!"929394@pytest.mark.anyio95async def test_iterator_content():96 def hello_world() -> typing.Iterator[bytes]:97 yield b"Hello, "98 yield b"world!"99100 request = httpx.Request(method, url, content=hello_world())101 assert isinstance(request.stream, typing.Iterable)102 assert not isinstance(request.stream, typing.AsyncIterable)103104 content = b"".join(list(request.stream))105106 assert request.headers == {107 "Host": "www.example.com",108 "Transfer-Encoding": "chunked",109 }110 assert content == b"Hello, world!"111112 with pytest.raises(httpx.StreamConsumed):113 list(request.stream)114115 # Support 'data' for compat with requests.116 with pytest.warns(DeprecationWarning):117 request = httpx.Request(method, url, data=hello_world()) # type: ignore118 assert isinstance(request.stream, typing.Iterable)119 assert not isinstance(request.stream, typing.AsyncIterable)120121 content = b"".join(list(request.stream))122123 assert request.headers == {124 "Host": "www.example.com",125 "Transfer-Encoding": "chunked",126 }127 assert content == b"Hello, world!"128129130@pytest.mark.anyio131async def test_aiterator_content():132 async def hello_world() -> typing.AsyncIterator[bytes]:133 yield b"Hello, "134 yield b"world!"135136 request = httpx.Request(method, url, content=hello_world())137 assert not isinstance(request.stream, typing.Iterable)138 assert isinstance(request.stream, typing.AsyncIterable)139140 content = b"".join([part async for part in request.stream])141142 assert request.headers == {143 "Host": "www.example.com",144 "Transfer-Encoding": "chunked",145 }146 assert content == b"Hello, world!"147148 with pytest.raises(httpx.StreamConsumed):149 [part async for part in request.stream]150151 # Support 'data' for compat with requests.152 with pytest.warns(DeprecationWarning):153 request = httpx.Request(method, url, data=hello_world()) # type: ignore154 assert not isinstance(request.stream, typing.Iterable)155 assert isinstance(request.stream, typing.AsyncIterable)156157 content = b"".join([part async for part in request.stream])158159 assert request.headers == {160 "Host": "www.example.com",161 "Transfer-Encoding": "chunked",162 }163 assert content == b"Hello, world!"164165166@pytest.mark.anyio167async def test_json_content():168 request = httpx.Request(method, url, json={"Hello": "world!"})169 assert isinstance(request.stream, typing.Iterable)170 assert isinstance(request.stream, typing.AsyncIterable)171172 sync_content = b"".join(list(request.stream))173 async_content = b"".join([part async for part in request.stream])174175 assert request.headers == {176 "Host": "www.example.com",177 "Content-Length": "18",178 "Content-Type": "application/json",179 }180 assert sync_content == b'{"Hello":"world!"}'181 assert async_content == b'{"Hello":"world!"}'182183184@pytest.mark.anyio185async def test_urlencoded_content():186 request = httpx.Request(method, url, data={"Hello": "world!"})187 assert isinstance(request.stream, typing.Iterable)188 assert isinstance(request.stream, typing.AsyncIterable)189190 sync_content = b"".join(list(request.stream))191 async_content = b"".join([part async for part in request.stream])192193 assert request.headers == {194 "Host": "www.example.com",195 "Content-Length": "14",196 "Content-Type": "application/x-www-form-urlencoded",197 }198 assert sync_content == b"Hello=world%21"199 assert async_content == b"Hello=world%21"200201202@pytest.mark.anyio203async def test_urlencoded_boolean():204 request = httpx.Request(method, url, data={"example": True})205 assert isinstance(request.stream, typing.Iterable)206 assert isinstance(request.stream, typing.AsyncIterable)207208 sync_content = b"".join(list(request.stream))209 async_content = b"".join([part async for part in request.stream])210211 assert request.headers == {212 "Host": "www.example.com",213 "Content-Length": "12",214 "Content-Type": "application/x-www-form-urlencoded",215 }216 assert sync_content == b"example=true"217 assert async_content == b"example=true"218219220@pytest.mark.anyio221async def test_urlencoded_none():222 request = httpx.Request(method, url, data={"example": None})223 assert isinstance(request.stream, typing.Iterable)224 assert isinstance(request.stream, typing.AsyncIterable)225226 sync_content = b"".join(list(request.stream))227 async_content = b"".join([part async for part in request.stream])228229 assert request.headers == {230 "Host": "www.example.com",231 "Content-Length": "8",232 "Content-Type": "application/x-www-form-urlencoded",233 }234 assert sync_content == b"example="235 assert async_content == b"example="236237238@pytest.mark.anyio239async def test_urlencoded_list():240 request = httpx.Request(method, url, data={"example": ["a", 1, True]})241 assert isinstance(request.stream, typing.Iterable)242 assert isinstance(request.stream, typing.AsyncIterable)243244 sync_content = b"".join(list(request.stream))245 async_content = b"".join([part async for part in request.stream])246247 assert request.headers == {248 "Host": "www.example.com",249 "Content-Length": "32",250 "Content-Type": "application/x-www-form-urlencoded",251 }252 assert sync_content == b"example=a&example=1&example=true"253 assert async_content == b"example=a&example=1&example=true"254255256@pytest.mark.anyio257async def test_multipart_files_content():258 files = {"file": io.BytesIO(b"<file content>")}259 headers = {"Content-Type": "multipart/form-data; boundary=+++"}260 request = httpx.Request(261 method,262 url,263 files=files,264 headers=headers,265 )266 assert isinstance(request.stream, typing.Iterable)267 assert isinstance(request.stream, typing.AsyncIterable)268269 sync_content = b"".join(list(request.stream))270 async_content = b"".join([part async for part in request.stream])271272 assert request.headers == {273 "Host": "www.example.com",274 "Content-Length": "138",275 "Content-Type": "multipart/form-data; boundary=+++",276 }277 assert sync_content == b"".join(278 [279 b"--+++\r\n",280 b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',281 b"Content-Type: application/octet-stream\r\n",282 b"\r\n",283 b"<file content>\r\n",284 b"--+++--\r\n",285 ]286 )287 assert async_content == b"".join(288 [289 b"--+++\r\n",290 b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',291 b"Content-Type: application/octet-stream\r\n",292 b"\r\n",293 b"<file content>\r\n",294 b"--+++--\r\n",295 ]296 )297298299@pytest.mark.anyio300async def test_multipart_data_and_files_content():301 data = {"message": "Hello, world!"}302 files = {"file": io.BytesIO(b"<file content>")}303 headers = {"Content-Type": "multipart/form-data; boundary=+++"}304 request = httpx.Request(method, url, data=data, files=files, headers=headers)305 assert isinstance(request.stream, typing.Iterable)306 assert isinstance(request.stream, typing.AsyncIterable)307308 sync_content = b"".join(list(request.stream))309 async_content = b"".join([part async for part in request.stream])310311 assert request.headers == {312 "Host": "www.example.com",313 "Content-Length": "210",314 "Content-Type": "multipart/form-data; boundary=+++",315 }316 assert sync_content == b"".join(317 [318 b"--+++\r\n",319 b'Content-Disposition: form-data; name="message"\r\n',320 b"\r\n",321 b"Hello, world!\r\n",322 b"--+++\r\n",323 b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',324 b"Content-Type: application/octet-stream\r\n",325 b"\r\n",326 b"<file content>\r\n",327 b"--+++--\r\n",328 ]329 )330 assert async_content == b"".join(331 [332 b"--+++\r\n",333 b'Content-Disposition: form-data; name="message"\r\n',334 b"\r\n",335 b"Hello, world!\r\n",336 b"--+++\r\n",337 b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',338 b"Content-Type: application/octet-stream\r\n",339 b"\r\n",340 b"<file content>\r\n",341 b"--+++--\r\n",342 ]343 )344345346@pytest.mark.anyio347async def test_empty_request():348 request = httpx.Request(method, url, data={}, files={})349 assert isinstance(request.stream, typing.Iterable)350 assert isinstance(request.stream, typing.AsyncIterable)351352 sync_content = b"".join(list(request.stream))353 async_content = b"".join([part async for part in request.stream])354355 assert request.headers == {"Host": "www.example.com", "Content-Length": "0"}356 assert sync_content == b""357 assert async_content == b""358359360def test_invalid_argument():361 with pytest.raises(TypeError):362 httpx.Request(method, url, content=123) # type: ignore363364 with pytest.raises(TypeError):365 httpx.Request(method, url, content={"a": "b"}) # type: ignore366367368@pytest.mark.anyio369async def test_multipart_multiple_files_single_input_content():370 files = [371 ("file", io.BytesIO(b"<file content 1>")),372 ("file", io.BytesIO(b"<file content 2>")),373 ]374 headers = {"Content-Type": "multipart/form-data; boundary=+++"}375 request = httpx.Request(method, url, files=files, headers=headers)376 assert isinstance(request.stream, typing.Iterable)377 assert isinstance(request.stream, typing.AsyncIterable)378379 sync_content = b"".join(list(request.stream))380 async_content = b"".join([part async for part in request.stream])381382 assert request.headers == {383 "Host": "www.example.com",384 "Content-Length": "271",385 "Content-Type": "multipart/form-data; boundary=+++",386 }387 assert sync_content == b"".join(388 [389 b"--+++\r\n",390 b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',391 b"Content-Type: application/octet-stream\r\n",392 b"\r\n",393 b"<file content 1>\r\n",394 b"--+++\r\n",395 b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',396 b"Content-Type: application/octet-stream\r\n",397 b"\r\n",398 b"<file content 2>\r\n",399 b"--+++--\r\n",400 ]401 )402 assert async_content == b"".join(403 [404 b"--+++\r\n",405 b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',406 b"Content-Type: application/octet-stream\r\n",407 b"\r\n",408 b"<file content 1>\r\n",409 b"--+++\r\n",410 b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',411 b"Content-Type: application/octet-stream\r\n",412 b"\r\n",413 b"<file content 2>\r\n",414 b"--+++--\r\n",415 ]416 )417418419@pytest.mark.anyio420async def test_response_empty_content():421 response = httpx.Response(200)422 assert isinstance(response.stream, typing.Iterable)423 assert isinstance(response.stream, typing.AsyncIterable)424425 sync_content = b"".join(list(response.stream))426 async_content = b"".join([part async for part in response.stream])427428 assert response.headers == {}429 assert sync_content == b""430 assert async_content == b""431432433@pytest.mark.anyio434async def test_response_bytes_content():435 response = httpx.Response(200, content=b"Hello, world!")436 assert isinstance(response.stream, typing.Iterable)437 assert isinstance(response.stream, typing.AsyncIterable)438439 sync_content = b"".join(list(response.stream))440 async_content = b"".join([part async for part in response.stream])441442 assert response.headers == {"Content-Length": "13"}443 assert sync_content == b"Hello, world!"444 assert async_content == b"Hello, world!"445446447@pytest.mark.anyio448async def test_response_iterator_content():449 def hello_world() -> typing.Iterator[bytes]:450 yield b"Hello, "451 yield b"world!"452453 response = httpx.Response(200, content=hello_world())454 assert isinstance(response.stream, typing.Iterable)455 assert not isinstance(response.stream, typing.AsyncIterable)456457 content = b"".join(list(response.stream))458459 assert response.headers == {"Transfer-Encoding": "chunked"}460 assert content == b"Hello, world!"461462 with pytest.raises(httpx.StreamConsumed):463 list(response.stream)464465466@pytest.mark.anyio467async def test_response_aiterator_content():468 async def hello_world() -> typing.AsyncIterator[bytes]:469 yield b"Hello, "470 yield b"world!"471472 response = httpx.Response(200, content=hello_world())473 assert not isinstance(response.stream, typing.Iterable)474 assert isinstance(response.stream, typing.AsyncIterable)475476 content = b"".join([part async for part in response.stream])477478 assert response.headers == {"Transfer-Encoding": "chunked"}479 assert content == b"Hello, world!"480481 with pytest.raises(httpx.StreamConsumed):482 [part async for part in response.stream]483484485def test_response_invalid_argument():486 with pytest.raises(TypeError):487 httpx.Response(200, content=123) # type: ignore488489490def test_ensure_ascii_false_with_french_characters():491 data = {"greeting": "Bonjour, ça va ?"}492 headers, byte_stream = encode_json(data)493 json_output = b"".join(byte_stream).decode("utf-8")494495 assert (496 "ça va" in json_output497 ), "ensure_ascii=False should preserve French accented characters"498 assert headers["Content-Type"] == "application/json"499500501def test_separators_for_compact_json():502 data = {"clé": "valeur", "liste": [1, 2, 3]}503 headers, byte_stream = encode_json(data)504 json_output = b"".join(byte_stream).decode("utf-8")505506 assert (507 json_output == '{"clé":"valeur","liste":[1,2,3]}'508 ), "separators=(',', ':') should produce a compact representation"509 assert headers["Content-Type"] == "application/json"510511512def test_allow_nan_false():513 data_with_nan = {"nombre": float("nan")}514 data_with_inf = {"nombre": float("inf")}515516 with pytest.raises(517 ValueError, match="Out of range float values are not JSON compliant"518 ):519 encode_json(data_with_nan)520 with pytest.raises(521 ValueError, match="Out of range float values are not JSON compliant"522 ):523 encode_json(data_with_inf)