Skip to content
Myr

test_responses.py

This file

Path

tests/models/test_responses.py

1,011 lines · 28.5 KiB · Python

Last changed by

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

History of this file

Take it

The walk stopped after 200 commits: lines older than ecbece1 point at it.

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 1–2why, one step back
1import json
2import pickle

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

line 3why, one step back
3import typing

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

line 4why, one step back
4

Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28

line 5why, one step back
5import chardet

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 6–16why, one step back
6import pytest
78import httpx91011class StreamingBody:12 def __iter__(self):13 yield b"Hello, "14 yield b"world!"1516

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

line 17why, one step back
17def streaming_body() -> typing.Iterator[bytes]:

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 18–21why, one step back
18 yield b"Hello, "
19 yield b"world!"2021

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

line 22why, one step back
22async def async_streaming_body() -> typing.AsyncIterator[bytes]:

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 23–26why, one step back
23 yield b"Hello, "
24 yield b"world!"2526

Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28

lines 27–30why, one step back
27def autodetect(content):
28 return chardet.detect(content).get("encoding")2930

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 31–97why, one step back
31def test_response():
32 response = httpx.Response(33 200,34 content=b"Hello, world!",35 request=httpx.Request("GET", "https://example.org"),36 )3738 assert response.status_code == 20039 assert response.reason_phrase == "OK"40 assert response.text == "Hello, world!"41 assert response.request.method == "GET"42 assert response.request.url == "https://example.org"43 assert not response.is_error444546def test_response_content():47 response = httpx.Response(200, content="Hello, world!")4849 assert response.status_code == 20050 assert response.reason_phrase == "OK"51 assert response.text == "Hello, world!"52 assert response.headers == {"Content-Length": "13"}535455def test_response_text():56 response = httpx.Response(200, text="Hello, world!")5758 assert response.status_code == 20059 assert response.reason_phrase == "OK"60 assert response.text == "Hello, world!"61 assert response.headers == {62 "Content-Length": "13",63 "Content-Type": "text/plain; charset=utf-8",64 }656667def test_response_html():68 response = httpx.Response(200, html="<html><body>Hello, world!</html></body>")6970 assert response.status_code == 20071 assert response.reason_phrase == "OK"72 assert response.text == "<html><body>Hello, world!</html></body>"73 assert response.headers == {74 "Content-Length": "39",75 "Content-Type": "text/html; charset=utf-8",76 }777879def test_response_json():80 response = httpx.Response(200, json={"hello": "world"})8182 assert response.status_code == 20083 assert response.reason_phrase == "OK"84 assert response.json() == {"hello": "world"}85 assert response.headers == {86 "Content-Length": "18",87 "Content-Type": "application/json",88 }899091def test_raise_for_status():92 request = httpx.Request("GET", "https://example.org")9394 # 2xx status codes are not an error.95 response = httpx.Response(200, request=request)96 response.raise_for_status()97

is_informational / is_success / is_redirect / is_client_error / is_server_error (#1854)Tom Christiebefore adoptiona761e17

lines 98–119why, one step back
98 # 1xx status codes are informational responses.
99 response = httpx.Response(101, request=request)100 assert response.is_informational101 with pytest.raises(httpx.HTTPStatusError) as exc_info:102 response.raise_for_status()103 assert str(exc_info.value) == (104 "Informational response '101 Switching Protocols' for url 'https://example.org'\n"105 "For more information check: https://httpstatuses.com/101"106 )107108 # 3xx status codes are redirections.109 headers = {"location": "https://other.org"}110 response = httpx.Response(303, headers=headers, request=request)111 assert response.is_redirect112 with pytest.raises(httpx.HTTPStatusError) as exc_info:113 response.raise_for_status()114 assert str(exc_info.value) == (115 "Redirect response '303 See Other' for url 'https://example.org'\n"116 "Redirect location: 'https://other.org'\n"117 "For more information check: https://httpstatuses.com/303"118 )119

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 120–121why, one step back
120 # 4xx status codes are a client error.
121 response = httpx.Response(403, request=request)

is_informational / is_success / is_redirect / is_client_error / is_server_error (#1854)Tom Christiebefore adoptiona761e17

lines 122–124why, one step back
122 assert response.is_client_error
123 assert response.is_error124 with pytest.raises(httpx.HTTPStatusError) as exc_info:

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

line 125why, one step back
125 response.raise_for_status()

is_informational / is_success / is_redirect / is_client_error / is_server_error (#1854)Tom Christiebefore adoptiona761e17

lines 126–129why, one step back
126 assert str(exc_info.value) == (
127 "Client error '403 Forbidden' for url 'https://example.org'\n"128 "For more information check: https://httpstatuses.com/403"129 )

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 130–132why, one step back
130
131 # 5xx status codes are a server error.132 response = httpx.Response(500, request=request)

is_informational / is_success / is_redirect / is_client_error / is_server_error (#1854)Tom Christiebefore adoptiona761e17

lines 133–135why, one step back
133 assert response.is_server_error
134 assert response.is_error135 with pytest.raises(httpx.HTTPStatusError) as exc_info:

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

line 136why, one step back
136 response.raise_for_status()

is_informational / is_success / is_redirect / is_client_error / is_server_error (#1854)Tom Christiebefore adoptiona761e17

lines 137–140why, one step back
137 assert str(exc_info.value) == (
138 "Server error '500 Internal Server Error' for url 'https://example.org'\n"139 "For more information check: https://httpstatuses.com/500"140 )

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 141–171why, one step back
141
142 # Calling .raise_for_status without setting a request instance is143 # not valid. Should raise a runtime error.144 response = httpx.Response(200)145 with pytest.raises(RuntimeError):146 response.raise_for_status()147148149def test_response_repr():150 response = httpx.Response(151 200,152 content=b"Hello, world!",153 )154 assert repr(response) == "<Response [200 OK]>"155156157def test_response_content_type_encoding():158 """159 Use the charset encoding in the Content-Type header if possible.160 """161 headers = {"Content-Type": "text-plain; charset=latin-1"}162 content = "Latin 1: ÿ".encode("latin-1")163 response = httpx.Response(164 200,165 content=content,166 headers=headers,167 )168 assert response.text == "Latin 1: ÿ"169 assert response.encoding == "latin-1"170171

Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28

line 172why, one step back
172def test_response_default_to_utf8_encoding():

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

line 173why, one step back
173 """

Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28

line 174why, one step back
174 Default to utf-8 encoding if there is no Content-Type header.

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 175–181why, one step back
175 """
176 content = "おはようございます。".encode("utf-8")177 response = httpx.Response(178 200,179 content=content,180 )181 assert response.text == "おはようございます。"

Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28

line 182why, one step back
182 assert response.encoding == "utf-8"

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 183–184why, one step back
183
184

Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28

line 185why, one step back
185def test_response_fallback_to_utf8_encoding():

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

line 186why, one step back
186 """

Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28

line 187why, one step back
187 Fallback to utf-8 if we get an invalid charset in the Content-Type header.

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 188–196why, one step back
188 """
189 headers = {"Content-Type": "text-plain; charset=invalid-codec-name"}190 content = "おはようございます。".encode("utf-8")191 response = httpx.Response(192 200,193 content=content,194 headers=headers,195 )196 assert response.text == "おはようございます。"

Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28

line 197why, one step back
197 assert response.encoding == "utf-8"

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 198–212why, one step back
198
199200def test_response_no_charset_with_ascii_content():201 """202 A response with ascii encoded content should decode correctly,203 even with no charset specified.204 """205 content = b"Hello, world!"206 headers = {"Content-Type": "text/plain"}207 response = httpx.Response(208 200,209 content=content,210 headers=headers,211 )212 assert response.status_code == 200

Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28

line 213why, one step back
213 assert response.encoding == "utf-8"

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 214–229why, one step back
214 assert response.text == "Hello, world!"
215216217def test_response_no_charset_with_utf8_content():218 """219 A response with UTF-8 encoded content should decode correctly,220 even with no charset specified.221 """222 content = "Unicode Snowman: ☃".encode("utf-8")223 headers = {"Content-Type": "text/plain"}224 response = httpx.Response(225 200,226 content=content,227 headers=headers,228 )229 assert response.text == "Unicode Snowman: ☃"

Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28

line 230why, one step back
230 assert response.encoding == "utf-8"

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 231–235why, one step back
231
232233def test_response_no_charset_with_iso_8859_1_content():234 """235 A response with ISO 8859-1 encoded content should decode correctly,

Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28

line 236why, one step back
236 even with no charset specified, if autodetect is enabled.

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 237–240why, one step back
237 """
238 content = "Accented: Österreich abcdefghijklmnopqrstuzwxyz".encode("iso-8859-1")239 headers = {"Content-Type": "text/plain"}240 response = httpx.Response(

Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28

line 241why, one step back
241 200, content=content, headers=headers, default_encoding=autodetect

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 242–249why, one step back
242 )
243 assert response.text == "Accented: Österreich abcdefghijklmnopqrstuzwxyz"244 assert response.charset_encoding is None245246247def test_response_no_charset_with_cp_1252_content():248 """249 A response with Windows 1252 encoded content should decode correctly,

Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28

line 250why, one step back
250 even with no charset specified, if autodetect is enabled.

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 251–254why, one step back
251 """
252 content = "Euro Currency: € abcdefghijklmnopqrstuzwxyz".encode("cp1252")253 headers = {"Content-Type": "text/plain"}254 response = httpx.Response(

Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28

line 255why, one step back
255 200, content=content, headers=headers, default_encoding=autodetect

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 256–262why, one step back
256 )
257 assert response.text == "Euro Currency: € abcdefghijklmnopqrstuzwxyz"258 assert response.charset_encoding is None259260261def test_response_non_text_encoding():262 """

Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28

line 263why, one step back
263 Default to attempting utf-8 encoding for non-text content-type headers.

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 264–271why, one step back
264 """
265 headers = {"Content-Type": "image/png"}266 response = httpx.Response(267 200,268 content=b"xyz",269 headers=headers,270 )271 assert response.text == "xyz"

Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28

line 272why, one step back
272 assert response.encoding == "utf-8"

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 273–308why, one step back
273
274275def test_response_set_explicit_encoding():276 headers = {277 "Content-Type": "text-plain; charset=utf-8"278 } # Deliberately incorrect charset279 response = httpx.Response(280 200,281 content="Latin 1: ÿ".encode("latin-1"),282 headers=headers,283 )284 response.encoding = "latin-1"285 assert response.text == "Latin 1: ÿ"286 assert response.encoding == "latin-1"287288289def test_response_force_encoding():290 response = httpx.Response(291 200,292 content="Snowman: ☃".encode("utf-8"),293 )294 response.encoding = "iso-8859-1"295 assert response.status_code == 200296 assert response.reason_phrase == "OK"297 assert response.text == "Snowman: â\x98\x83"298 assert response.encoding == "iso-8859-1"299300301def test_read():302 response = httpx.Response(303 200,304 content=b"Hello, world!",305 )306307 assert response.status_code == 200308 assert response.text == "Hello, world!"

Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28

line 309why, one step back
309 assert response.encoding == "utf-8"

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 310–323why, one step back
310 assert response.is_closed
311312 content = response.read()313314 assert content == b"Hello, world!"315 assert response.content == b"Hello, world!"316 assert response.is_closed317318319def test_empty_read():320 response = httpx.Response(200)321322 assert response.status_code == 200323 assert response.text == ""

Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28

line 324why, one step back
324 assert response.encoding == "utf-8"

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 325–333why, one step back
325 assert response.is_closed
326327 content = response.read()328329 assert content == b""330 assert response.content == b""331 assert response.is_closed332333

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 334why, one step back
334@pytest.mark.anyio

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 335–342why, one step back
335async def test_aread():
336 response = httpx.Response(337 200,338 content=b"Hello, world!",339 )340341 assert response.status_code == 200342 assert response.text == "Hello, world!"

Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28

line 343why, one step back
343 assert response.encoding == "utf-8"

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 344–352why, one step back
344 assert response.is_closed
345346 content = await response.aread()347348 assert content == b"Hello, world!"349 assert response.content == b"Hello, world!"350 assert response.is_closed351352

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 353why, one step back
353@pytest.mark.anyio

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 354–358why, one step back
354async def test_empty_aread():
355 response = httpx.Response(200)356357 assert response.status_code == 200358 assert response.text == ""

Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28

line 359why, one step back
359 assert response.encoding == "utf-8"

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 360–397why, one step back
360 assert response.is_closed
361362 content = await response.aread()363364 assert content == b""365 assert response.content == b""366 assert response.is_closed367368369def test_iter_raw():370 response = httpx.Response(371 200,372 content=streaming_body(),373 )374375 raw = b""376 for part in response.iter_raw():377 raw += part378 assert raw == b"Hello, world!"379380381def test_iter_raw_with_chunksize():382 response = httpx.Response(200, content=streaming_body())383384 parts = [part for part in response.iter_raw(chunk_size=5)]385 assert parts == [b"Hello", b", wor", b"ld!"]386387 response = httpx.Response(200, content=streaming_body())388389 parts = [part for part in response.iter_raw(chunk_size=13)]390 assert parts == [b"Hello, world!"]391392 response = httpx.Response(200, content=streaming_body())393394 parts = [part for part in response.iter_raw(chunk_size=20)]395 assert parts == [b"Hello, world!"]396397

Ensure that iter_bytes does not ever yield any zero-length chunks (#2068)Tom Christiebefore adoption420911b

line 398why, one step back
398def test_iter_raw_doesnt_return_empty_chunks():

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

line 399why, one step back
399 def streaming_body_with_empty_chunks() -> typing.Iterator[bytes]:

Ensure that iter_bytes does not ever yield any zero-length chunks (#2068)Tom Christiebefore adoption420911b

lines 400–410why, one step back
400 yield b"Hello, "
401 yield b""402 yield b"world!"403 yield b""404405 response = httpx.Response(200, content=streaming_body_with_empty_chunks())406407 parts = [part for part in response.iter_raw()]408 assert parts == [b"Hello, ", b"world!"]409410

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 411–451why, one step back
411def test_iter_raw_on_iterable():
412 response = httpx.Response(413 200,414 content=StreamingBody(),415 )416417 raw = b""418 for part in response.iter_raw():419 raw += part420 assert raw == b"Hello, world!"421422423def test_iter_raw_on_async():424 response = httpx.Response(425 200,426 content=async_streaming_body(),427 )428429 with pytest.raises(RuntimeError):430 [part for part in response.iter_raw()]431432433def test_close_on_async():434 response = httpx.Response(435 200,436 content=async_streaming_body(),437 )438439 with pytest.raises(RuntimeError):440 response.close()441442443def test_iter_raw_increments_updates_counter():444 response = httpx.Response(200, content=streaming_body())445446 num_downloaded = response.num_bytes_downloaded447 for part in response.iter_raw():448 assert len(part) == (response.num_bytes_downloaded - num_downloaded)449 num_downloaded = response.num_bytes_downloaded450451

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 452why, one step back
452@pytest.mark.anyio

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 453–461why, one step back
453async def test_aiter_raw():
454 response = httpx.Response(200, content=async_streaming_body())455456 raw = b""457 async for part in response.aiter_raw():458 raw += part459 assert raw == b"Hello, world!"460461

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 462why, one step back
462@pytest.mark.anyio

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 463–479why, one step back
463async def test_aiter_raw_with_chunksize():
464 response = httpx.Response(200, content=async_streaming_body())465466 parts = [part async for part in response.aiter_raw(chunk_size=5)]467 assert parts == [b"Hello", b", wor", b"ld!"]468469 response = httpx.Response(200, content=async_streaming_body())470471 parts = [part async for part in response.aiter_raw(chunk_size=13)]472 assert parts == [b"Hello, world!"]473474 response = httpx.Response(200, content=async_streaming_body())475476 parts = [part async for part in response.aiter_raw(chunk_size=20)]477 assert parts == [b"Hello, world!"]478479

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 480why, one step back
480@pytest.mark.anyio

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 481–490why, one step back
481async def test_aiter_raw_on_sync():
482 response = httpx.Response(483 200,484 content=streaming_body(),485 )486487 with pytest.raises(RuntimeError):488 [part async for part in response.aiter_raw()]489490

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 491why, one step back
491@pytest.mark.anyio

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 492–501why, one step back
492async def test_aclose_on_sync():
493 response = httpx.Response(494 200,495 content=streaming_body(),496 )497498 with pytest.raises(RuntimeError):499 await response.aclose()500501

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 502why, one step back
502@pytest.mark.anyio

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 503–538why, one step back
503async def test_aiter_raw_increments_updates_counter():
504 response = httpx.Response(200, content=async_streaming_body())505506 num_downloaded = response.num_bytes_downloaded507 async for part in response.aiter_raw():508 assert len(part) == (response.num_bytes_downloaded - num_downloaded)509 num_downloaded = response.num_bytes_downloaded510511512def test_iter_bytes():513 response = httpx.Response(200, content=b"Hello, world!")514515 content = b""516 for part in response.iter_bytes():517 content += part518 assert content == b"Hello, world!"519520521def test_iter_bytes_with_chunk_size():522 response = httpx.Response(200, content=streaming_body())523 parts = [part for part in response.iter_bytes(chunk_size=5)]524 assert parts == [b"Hello", b", wor", b"ld!"]525526 response = httpx.Response(200, content=streaming_body())527 parts = [part for part in response.iter_bytes(chunk_size=13)]528 assert parts == [b"Hello, world!"]529530 response = httpx.Response(200, content=streaming_body())531 parts = [part for part in response.iter_bytes(chunk_size=20)]532 assert parts == [b"Hello, world!"]533534535def test_iter_bytes_with_empty_response():536 response = httpx.Response(200, content=b"")537 parts = [part for part in response.iter_bytes()]538 assert parts == []

Ensure that iter_bytes does not ever yield any zero-length chunks (#2068)Tom Christiebefore adoption420911b

lines 539–541why, one step back
539
540541def test_iter_bytes_doesnt_return_empty_chunks():

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

line 542why, one step back
542 def streaming_body_with_empty_chunks() -> typing.Iterator[bytes]:

Ensure that iter_bytes does not ever yield any zero-length chunks (#2068)Tom Christiebefore adoption420911b

lines 543–551why, one step back
543 yield b"Hello, "
544 yield b""545 yield b"world!"546 yield b""547548 response = httpx.Response(200, content=streaming_body_with_empty_chunks())549550 parts = [part for part in response.iter_bytes()]551 assert parts == [b"Hello, ", b"world!"]

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 552–553why, one step back
552
553

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 554why, one step back
554@pytest.mark.anyio

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 555–566why, one step back
555async def test_aiter_bytes():
556 response = httpx.Response(557 200,558 content=b"Hello, world!",559 )560561 content = b""562 async for part in response.aiter_bytes():563 content += part564 assert content == b"Hello, world!"565566

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 567why, one step back
567@pytest.mark.anyio

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 568–607why, one step back
568async def test_aiter_bytes_with_chunk_size():
569 response = httpx.Response(200, content=async_streaming_body())570 parts = [part async for part in response.aiter_bytes(chunk_size=5)]571 assert parts == [b"Hello", b", wor", b"ld!"]572573 response = httpx.Response(200, content=async_streaming_body())574 parts = [part async for part in response.aiter_bytes(chunk_size=13)]575 assert parts == [b"Hello, world!"]576577 response = httpx.Response(200, content=async_streaming_body())578 parts = [part async for part in response.aiter_bytes(chunk_size=20)]579 assert parts == [b"Hello, world!"]580581582def test_iter_text():583 response = httpx.Response(584 200,585 content=b"Hello, world!",586 )587588 content = ""589 for part in response.iter_text():590 content += part591 assert content == "Hello, world!"592593594def test_iter_text_with_chunk_size():595 response = httpx.Response(200, content=b"Hello, world!")596 parts = [part for part in response.iter_text(chunk_size=5)]597 assert parts == ["Hello", ", wor", "ld!"]598599 response = httpx.Response(200, content=b"Hello, world!")600 parts = [part for part in response.iter_text(chunk_size=13)]601 assert parts == ["Hello, world!"]602603 response = httpx.Response(200, content=b"Hello, world!")604 parts = [part for part in response.iter_text(chunk_size=20)]605 assert parts == ["Hello, world!"]606607

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 608why, one step back
608@pytest.mark.anyio

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 609–620why, one step back
609async def test_aiter_text():
610 response = httpx.Response(611 200,612 content=b"Hello, world!",613 )614615 content = ""616 async for part in response.aiter_text():617 content += part618 assert content == "Hello, world!"619620

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 621why, one step back
621@pytest.mark.anyio

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 622–644why, one step back
622async def test_aiter_text_with_chunk_size():
623 response = httpx.Response(200, content=b"Hello, world!")624 parts = [part async for part in response.aiter_text(chunk_size=5)]625 assert parts == ["Hello", ", wor", "ld!"]626627 response = httpx.Response(200, content=b"Hello, world!")628 parts = [part async for part in response.aiter_text(chunk_size=13)]629 assert parts == ["Hello, world!"]630631 response = httpx.Response(200, content=b"Hello, world!")632 parts = [part async for part in response.aiter_text(chunk_size=20)]633 assert parts == ["Hello, world!"]634635636def test_iter_lines():637 response = httpx.Response(638 200,639 content=b"Hello,\nworld!",640 )641 content = [line for line in response.iter_lines()]642 assert content == ["Hello,\n", "world!"]643644

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 645why, one step back
645@pytest.mark.anyio

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 646–673why, one step back
646async def test_aiter_lines():
647 response = httpx.Response(648 200,649 content=b"Hello,\nworld!",650 )651652 content = []653 async for line in response.aiter_lines():654 content.append(line)655 assert content == ["Hello,\n", "world!"]656657658def test_sync_streaming_response():659 response = httpx.Response(660 200,661 content=streaming_body(),662 )663664 assert response.status_code == 200665 assert not response.is_closed666667 content = response.read()668669 assert content == b"Hello, world!"670 assert response.content == b"Hello, world!"671 assert response.is_closed672673

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 674why, one step back
674@pytest.mark.anyio

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 675–704why, one step back
675async def test_async_streaming_response():
676 response = httpx.Response(677 200,678 content=async_streaming_body(),679 )680681 assert response.status_code == 200682 assert not response.is_closed683684 content = await response.aread()685686 assert content == b"Hello, world!"687 assert response.content == b"Hello, world!"688 assert response.is_closed689690691def test_cannot_read_after_stream_consumed():692 response = httpx.Response(693 200,694 content=streaming_body(),695 )696697 content = b""698 for part in response.iter_bytes():699 content += part700701 with pytest.raises(httpx.StreamConsumed):702 response.read()703704

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 705why, one step back
705@pytest.mark.anyio

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 706–730why, one step back
706async def test_cannot_aread_after_stream_consumed():
707 response = httpx.Response(708 200,709 content=async_streaming_body(),710 )711712 content = b""713 async for part in response.aiter_bytes():714 content += part715716 with pytest.raises(httpx.StreamConsumed):717 await response.aread()718719720def test_cannot_read_after_response_closed():721 response = httpx.Response(722 200,723 content=streaming_body(),724 )725726 response.close()727 with pytest.raises(httpx.StreamClosed):728 response.read()729730

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 731why, one step back
731@pytest.mark.anyio

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 732–742why, one step back
732async def test_cannot_aread_after_response_closed():
733 response = httpx.Response(734 200,735 content=async_streaming_body(),736 )737738 await response.aclose()739 with pytest.raises(httpx.StreamClosed):740 await response.aread()741742

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 743why, one step back
743@pytest.mark.anyio

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 744–864why, one step back
744async def test_elapsed_not_available_until_closed():
745 response = httpx.Response(746 200,747 content=async_streaming_body(),748 )749750 with pytest.raises(RuntimeError):751 response.elapsed752753754def test_unknown_status_code():755 response = httpx.Response(756 600,757 )758 assert response.status_code == 600759 assert response.reason_phrase == ""760 assert response.text == ""761762763def test_json_with_specified_encoding():764 data = {"greeting": "hello", "recipient": "world"}765 content = json.dumps(data).encode("utf-16")766 headers = {"Content-Type": "application/json, charset=utf-16"}767 response = httpx.Response(768 200,769 content=content,770 headers=headers,771 )772 assert response.json() == data773774775def test_json_with_options():776 data = {"greeting": "hello", "recipient": "world", "amount": 1}777 content = json.dumps(data).encode("utf-16")778 headers = {"Content-Type": "application/json, charset=utf-16"}779 response = httpx.Response(780 200,781 content=content,782 headers=headers,783 )784 assert response.json(parse_int=str)["amount"] == "1"785786787@pytest.mark.parametrize(788 "encoding",789 [790 "utf-8",791 "utf-8-sig",792 "utf-16",793 "utf-16-be",794 "utf-16-le",795 "utf-32",796 "utf-32-be",797 "utf-32-le",798 ],799)800def test_json_without_specified_charset(encoding):801 data = {"greeting": "hello", "recipient": "world"}802 content = json.dumps(data).encode(encoding)803 headers = {"Content-Type": "application/json"}804 response = httpx.Response(805 200,806 content=content,807 headers=headers,808 )809 assert response.json() == data810811812@pytest.mark.parametrize(813 "encoding",814 [815 "utf-8",816 "utf-8-sig",817 "utf-16",818 "utf-16-be",819 "utf-16-le",820 "utf-32",821 "utf-32-be",822 "utf-32-le",823 ],824)825def test_json_with_specified_charset(encoding):826 data = {"greeting": "hello", "recipient": "world"}827 content = json.dumps(data).encode(encoding)828 headers = {"Content-Type": f"application/json; charset={encoding}"}829 response = httpx.Response(830 200,831 content=content,832 headers=headers,833 )834 assert response.json() == data835836837@pytest.mark.parametrize(838 "headers, expected",839 [840 (841 {"Link": "<https://example.com>; rel='preload'"},842 {"preload": {"rel": "preload", "url": "https://example.com"}},843 ),844 (845 {"Link": '</hub>; rel="hub", </resource>; rel="self"'},846 {847 "hub": {"url": "/hub", "rel": "hub"},848 "self": {"url": "/resource", "rel": "self"},849 },850 ),851 ],852)853def test_link_headers(headers, expected):854 response = httpx.Response(855 200,856 content=None,857 headers=headers,858 )859 assert response.links == expected860861862@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))863def test_decode_error_with_request(header_value):864 headers = [(b"Content-Encoding", header_value)]

Drop unneccessary private import in tests (#2498)Tom Christiebefore adoptionaf56476

line 865why, one step back
865 broken_compressed_body = b"xxxxxxxxxxxxxx"

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 866–869why, one step back
866 with pytest.raises(httpx.DecodingError):
867 httpx.Response(868 200,869 headers=headers,

Drop unneccessary private import in tests (#2498)Tom Christiebefore adoptionaf56476

line 870why, one step back
870 content=broken_compressed_body,

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 871–876why, one step back
871 )
872873 with pytest.raises(httpx.DecodingError):874 httpx.Response(875 200,876 headers=headers,

Drop unneccessary private import in tests (#2498)Tom Christiebefore adoptionaf56476

line 877why, one step back
877 content=broken_compressed_body,

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 878–884why, one step back
878 request=httpx.Request("GET", "https://www.example.org/"),
879 )880881882@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))883def test_value_error_without_request(header_value):884 headers = [(b"Content-Encoding", header_value)]

Drop unneccessary private import in tests (#2498)Tom Christiebefore adoptionaf56476

line 885why, one step back
885 broken_compressed_body = b"xxxxxxxxxxxxxx"

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

line 886why, one step back
886 with pytest.raises(httpx.DecodingError):

Drop unneccessary private import in tests (#2498)Tom Christiebefore adoptionaf56476

line 887why, one step back
887 httpx.Response(200, headers=headers, content=broken_compressed_body)

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 888–915why, one step back
888
889890def test_response_with_unset_request():891 response = httpx.Response(200, content=b"Hello, world!")892893 assert response.status_code == 200894 assert response.reason_phrase == "OK"895 assert response.text == "Hello, world!"896 assert not response.is_error897898899def test_set_request_after_init():900 response = httpx.Response(200, content=b"Hello, world!")901902 response.request = httpx.Request("GET", "https://www.example.org")903904 assert response.request.method == "GET"905 assert response.request.url == "https://www.example.org"906907908def test_cannot_access_unset_request():909 response = httpx.Response(200, content=b"Hello, world!")910911 with pytest.raises(RuntimeError):912 response.request913914915def test_generator_with_transfer_encoding_header():

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

line 916why, one step back
916 def content() -> typing.Iterator[bytes]:

use # pragma: no cover instead of # pragma: nocover (#2471)Adrian Garcia Badaraccobefore adoption16e2830

line 917why, one step back
917 yield b"test 123" # pragma: no cover

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 918–923why, one step back
918
919 response = httpx.Response(200, content=content())920 assert response.headers == {"Transfer-Encoding": "chunked"}921922923def test_generator_with_content_length_header():

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

line 924why, one step back
924 def content() -> typing.Iterator[bytes]:

use # pragma: no cover instead of # pragma: nocover (#2471)Adrian Garcia Badaraccobefore adoption16e2830

line 925why, one step back
925 yield b"test 123" # pragma: no cover

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 926–949why, one step back
926
927 headers = {"Content-Length": "8"}928 response = httpx.Response(200, content=content(), headers=headers)929 assert response.headers == {"Content-Length": "8"}930931932def test_response_picklable():933 response = httpx.Response(934 200,935 content=b"Hello, world!",936 request=httpx.Request("GET", "https://example.org"),937 )938 pickle_response = pickle.loads(pickle.dumps(response))939 assert pickle_response.is_closed is True940 assert pickle_response.is_stream_consumed is True941 assert pickle_response.next_request is None942 assert pickle_response.stream is not None943 assert pickle_response.content == b"Hello, world!"944 assert pickle_response.status_code == 200945 assert pickle_response.request.url == response.request.url946 assert pickle_response.extensions == {}947 assert pickle_response.history == []948949

replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8

line 950why, one step back
950@pytest.mark.anyio

:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1

lines 951–967why, one step back
951async def test_response_async_streaming_picklable():
952 response = httpx.Response(200, content=async_streaming_body())953 pickle_response = pickle.loads(pickle.dumps(response))954 with pytest.raises(httpx.ResponseNotRead):955 pickle_response.content956 with pytest.raises(httpx.StreamClosed):957 await pickle_response.aread()958 assert pickle_response.is_stream_consumed is False959 assert pickle_response.num_bytes_downloaded == 0960 assert pickle_response.headers == {"Transfer-Encoding": "chunked"}961962 response = httpx.Response(200, content=async_streaming_body())963 await response.aread()964 pickle_response = pickle.loads(pickle.dumps(response))965 assert pickle_response.is_stream_consumed is True966 assert pickle_response.content == b"Hello, world!"967 assert pickle_response.num_bytes_downloaded == 13

Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28

lines 968–1011why, one step back
968
969970def test_response_decode_text_using_autodetect():971 # Ensure that a 'default_encoding="autodetect"' on the response allows for972 # encoding autodetection to be used when no "Content-Type: text/plain; charset=..."973 # info is present.974 #975 # Here we have some french text encoded with ISO-8859-1, rather than UTF-8.976 text = (977 "Non-seulement Despréaux ne se trompait pas, mais de tous les écrivains "978 "que la France a produits, sans excepter Voltaire lui-même, imprégné de "979 "l'esprit anglais par son séjour à Londres, c'est incontestablement "980 "Molière ou Poquelin qui reproduit avec l'exactitude la plus vive et la "981 "plus complète le fond du génie français."982 )983 content = text.encode("ISO-8859-1")984 response = httpx.Response(200, content=content, default_encoding=autodetect)985986 assert response.status_code == 200987 assert response.reason_phrase == "OK"988 assert response.encoding == "ISO-8859-1"989 assert response.text == text990991992def test_response_decode_text_using_explicit_encoding():993 # Ensure that a 'default_encoding="..."' on the response is used for text decoding994 # when no "Content-Type: text/plain; charset=..."" info is present.995 #996 # Here we have some french text encoded with Windows-1252, rather than UTF-8.997 # https://en.wikipedia.org/wiki/Windows-1252998 text = (999 "Non-seulement Despréaux ne se trompait pas, mais de tous les écrivains "1000 "que la France a produits, sans excepter Voltaire lui-même, imprégné de "1001 "l'esprit anglais par son séjour à Londres, c'est incontestablement "1002 "Molière ou Poquelin qui reproduit avec l'exactitude la plus vive et la "1003 "plus complète le fond du génie français."1004 )1005 content = text.encode("cp1252")1006 response = httpx.Response(200, content=content, default_encoding="cp1252")10071008 assert response.status_code == 2001009 assert response.reason_phrase == "OK"1010 assert response.encoding == "cp1252"1011 assert response.text == text