test_responses.py
This file
Path
tests/models/test_responses.py
1,014 lines · 28.6 KiB · Python
Last changed by
Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
History of this fileTake 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 back1import json2import pickleTyping: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
line 3why, one step back3import typing:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1
line 4why, one step back4Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28
line 5why, one step back5import chardet:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1
lines 6–17why, one step back6import pytest78import httpx9from httpx._compat import brotli101112class StreamingBody:13 def __iter__(self):14 yield b"Hello, "15 yield b"world!"1617Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
line 18why, one step back18def streaming_body() -> typing.Iterator[bytes]::pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1
lines 19–22why, one step back19 yield b"Hello, "20 yield b"world!"2122Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
line 23why, one step back23async def async_streaming_body() -> typing.AsyncIterator[bytes]::pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1
lines 24–27why, one step back24 yield b"Hello, "25 yield b"world!"2627Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28
lines 28–31why, one step back28def autodetect(content):29 return chardet.detect(content).get("encoding")3031:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1
lines 32–98why, one step back32def test_response():33 response = httpx.Response(34 200,35 content=b"Hello, world!",36 request=httpx.Request("GET", "https://example.org"),37 )3839 assert response.status_code == 20040 assert response.reason_phrase == "OK"41 assert response.text == "Hello, world!"42 assert response.request.method == "GET"43 assert response.request.url == "https://example.org"44 assert not response.is_error454647def test_response_content():48 response = httpx.Response(200, content="Hello, world!")4950 assert response.status_code == 20051 assert response.reason_phrase == "OK"52 assert response.text == "Hello, world!"53 assert response.headers == {"Content-Length": "13"}545556def test_response_text():57 response = httpx.Response(200, text="Hello, world!")5859 assert response.status_code == 20060 assert response.reason_phrase == "OK"61 assert response.text == "Hello, world!"62 assert response.headers == {63 "Content-Length": "13",64 "Content-Type": "text/plain; charset=utf-8",65 }666768def test_response_html():69 response = httpx.Response(200, html="<html><body>Hello, world!</html></body>")7071 assert response.status_code == 20072 assert response.reason_phrase == "OK"73 assert response.text == "<html><body>Hello, world!</html></body>"74 assert response.headers == {75 "Content-Length": "39",76 "Content-Type": "text/html; charset=utf-8",77 }787980def test_response_json():81 response = httpx.Response(200, json={"hello": "world"})8283 assert response.status_code == 20084 assert response.reason_phrase == "OK"85 assert response.json() == {"hello": "world"}86 assert response.headers == {87 "Content-Length": "18",88 "Content-Type": "application/json",89 }909192def test_raise_for_status():93 request = httpx.Request("GET", "https://example.org")9495 # 2xx status codes are not an error.96 response = httpx.Response(200, request=request)97 response.raise_for_status()98is_informational / is_success / is_redirect / is_client_error / is_server_error (#1854)Tom Christiebefore adoptiona761e17
lines 99–120why, one step back99 # 1xx status codes are informational responses.100 response = httpx.Response(101, request=request)101 assert response.is_informational102 with pytest.raises(httpx.HTTPStatusError) as exc_info:103 response.raise_for_status()104 assert str(exc_info.value) == (105 "Informational response '101 Switching Protocols' for url 'https://example.org'\n"106 "For more information check: https://httpstatuses.com/101"107 )108109 # 3xx status codes are redirections.110 headers = {"location": "https://other.org"}111 response = httpx.Response(303, headers=headers, request=request)112 assert response.is_redirect113 with pytest.raises(httpx.HTTPStatusError) as exc_info:114 response.raise_for_status()115 assert str(exc_info.value) == (116 "Redirect response '303 See Other' for url 'https://example.org'\n"117 "Redirect location: 'https://other.org'\n"118 "For more information check: https://httpstatuses.com/303"119 )120:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1
lines 121–122why, one step back121 # 4xx status codes are a client error.122 response = httpx.Response(403, request=request)is_informational / is_success / is_redirect / is_client_error / is_server_error (#1854)Tom Christiebefore adoptiona761e17
lines 123–125why, one step back123 assert response.is_client_error124 assert response.is_error125 with pytest.raises(httpx.HTTPStatusError) as exc_info::pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1
line 126why, one step back126 response.raise_for_status()is_informational / is_success / is_redirect / is_client_error / is_server_error (#1854)Tom Christiebefore adoptiona761e17
lines 127–130why, one step back127 assert str(exc_info.value) == (128 "Client error '403 Forbidden' for url 'https://example.org'\n"129 "For more information check: https://httpstatuses.com/403"130 ):pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1
lines 131–133why, one step back131132 # 5xx status codes are a server error.133 response = httpx.Response(500, request=request)is_informational / is_success / is_redirect / is_client_error / is_server_error (#1854)Tom Christiebefore adoptiona761e17
lines 134–136why, one step back134 assert response.is_server_error135 assert response.is_error136 with pytest.raises(httpx.HTTPStatusError) as exc_info::pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1
line 137why, one step back137 response.raise_for_status()is_informational / is_success / is_redirect / is_client_error / is_server_error (#1854)Tom Christiebefore adoptiona761e17
lines 138–141why, one step back138 assert str(exc_info.value) == (139 "Server error '500 Internal Server Error' for url 'https://example.org'\n"140 "For more information check: https://httpstatuses.com/500"141 ):pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1
lines 142–172why, one step back142143 # Calling .raise_for_status without setting a request instance is144 # not valid. Should raise a runtime error.145 response = httpx.Response(200)146 with pytest.raises(RuntimeError):147 response.raise_for_status()148149150def test_response_repr():151 response = httpx.Response(152 200,153 content=b"Hello, world!",154 )155 assert repr(response) == "<Response [200 OK]>"156157158def test_response_content_type_encoding():159 """160 Use the charset encoding in the Content-Type header if possible.161 """162 headers = {"Content-Type": "text-plain; charset=latin-1"}163 content = "Latin 1: ÿ".encode("latin-1")164 response = httpx.Response(165 200,166 content=content,167 headers=headers,168 )169 assert response.text == "Latin 1: ÿ"170 assert response.encoding == "latin-1"171172Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28
line 173why, one step back173def test_response_default_to_utf8_encoding()::pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1
line 174why, one step back174 """Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28
line 175why, one step back175 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 176–182why, one step back176 """177 content = "おはようございます。".encode("utf-8")178 response = httpx.Response(179 200,180 content=content,181 )182 assert response.text == "おはようございます。"Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28
line 183why, one step back183 assert response.encoding == "utf-8":pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1
lines 184–185why, one step back184185Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28
line 186why, one step back186def test_response_fallback_to_utf8_encoding()::pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1
line 187why, one step back187 """Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28
line 188why, one step back188 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 189–197why, one step back189 """190 headers = {"Content-Type": "text-plain; charset=invalid-codec-name"}191 content = "おはようございます。".encode("utf-8")192 response = httpx.Response(193 200,194 content=content,195 headers=headers,196 )197 assert response.text == "おはようございます。"Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28
line 198why, one step back198 assert response.encoding == "utf-8":pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1
lines 199–213why, one step back199200201def test_response_no_charset_with_ascii_content():202 """203 A response with ascii encoded content should decode correctly,204 even with no charset specified.205 """206 content = b"Hello, world!"207 headers = {"Content-Type": "text/plain"}208 response = httpx.Response(209 200,210 content=content,211 headers=headers,212 )213 assert response.status_code == 200Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28
line 214why, one step back214 assert response.encoding == "utf-8":pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1
lines 215–230why, one step back215 assert response.text == "Hello, world!"216217218def test_response_no_charset_with_utf8_content():219 """220 A response with UTF-8 encoded content should decode correctly,221 even with no charset specified.222 """223 content = "Unicode Snowman: ☃".encode("utf-8")224 headers = {"Content-Type": "text/plain"}225 response = httpx.Response(226 200,227 content=content,228 headers=headers,229 )230 assert response.text == "Unicode Snowman: ☃"Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28
line 231why, one step back231 assert response.encoding == "utf-8":pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1
lines 232–236why, one step back232233234def test_response_no_charset_with_iso_8859_1_content():235 """236 A response with ISO 8859-1 encoded content should decode correctly,Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28
line 237why, one step back237 even with no charset specified, if autodetect is enabled.:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1
lines 238–241why, one step back238 """239 content = "Accented: Österreich abcdefghijklmnopqrstuzwxyz".encode("iso-8859-1")240 headers = {"Content-Type": "text/plain"}241 response = httpx.Response(Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28
line 242why, one step back242 200, content=content, headers=headers, default_encoding=autodetect:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1
lines 243–250why, one step back243 )244 assert response.text == "Accented: Österreich abcdefghijklmnopqrstuzwxyz"245 assert response.charset_encoding is None246247248def test_response_no_charset_with_cp_1252_content():249 """250 A response with Windows 1252 encoded content should decode correctly,Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28
line 251why, one step back251 even with no charset specified, if autodetect is enabled.:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1
lines 252–255why, one step back252 """253 content = "Euro Currency: € abcdefghijklmnopqrstuzwxyz".encode("cp1252")254 headers = {"Content-Type": "text/plain"}255 response = httpx.Response(Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28
line 256why, one step back256 200, content=content, headers=headers, default_encoding=autodetect:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1
lines 257–263why, one step back257 )258 assert response.text == "Euro Currency: € abcdefghijklmnopqrstuzwxyz"259 assert response.charset_encoding is None260261262def test_response_non_text_encoding():263 """Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28
line 264why, one step back264 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 265–272why, one step back265 """266 headers = {"Content-Type": "image/png"}267 response = httpx.Response(268 200,269 content=b"xyz",270 headers=headers,271 )272 assert response.text == "xyz"Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28
line 273why, one step back273 assert response.encoding == "utf-8":pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1
lines 274–309why, one step back274275276def test_response_set_explicit_encoding():277 headers = {278 "Content-Type": "text-plain; charset=utf-8"279 } # Deliberately incorrect charset280 response = httpx.Response(281 200,282 content="Latin 1: ÿ".encode("latin-1"),283 headers=headers,284 )285 response.encoding = "latin-1"286 assert response.text == "Latin 1: ÿ"287 assert response.encoding == "latin-1"288289290def test_response_force_encoding():291 response = httpx.Response(292 200,293 content="Snowman: ☃".encode("utf-8"),294 )295 response.encoding = "iso-8859-1"296 assert response.status_code == 200297 assert response.reason_phrase == "OK"298 assert response.text == "Snowman: â\x98\x83"299 assert response.encoding == "iso-8859-1"300301302def test_read():303 response = httpx.Response(304 200,305 content=b"Hello, world!",306 )307308 assert response.status_code == 200309 assert response.text == "Hello, world!"Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28
line 310why, one step back310 assert response.encoding == "utf-8":pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1
lines 311–324why, one step back311 assert response.is_closed312313 content = response.read()314315 assert content == b"Hello, world!"316 assert response.content == b"Hello, world!"317 assert response.is_closed318319320def test_empty_read():321 response = httpx.Response(200)322323 assert response.status_code == 200324 assert response.text == ""Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28
line 325why, one step back325 assert response.encoding == "utf-8":pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1
lines 326–343why, one step back326 assert response.is_closed327328 content = response.read()329330 assert content == b""331 assert response.content == b""332 assert response.is_closed333334335@pytest.mark.asyncio336async def test_aread():337 response = httpx.Response(338 200,339 content=b"Hello, world!",340 )341342 assert response.status_code == 200343 assert response.text == "Hello, world!"Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28
line 344why, one step back344 assert response.encoding == "utf-8":pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1
lines 345–359why, one step back345 assert response.is_closed346347 content = await response.aread()348349 assert content == b"Hello, world!"350 assert response.content == b"Hello, world!"351 assert response.is_closed352353354@pytest.mark.asyncio355async def test_empty_aread():356 response = httpx.Response(200)357358 assert response.status_code == 200359 assert response.text == ""Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28
line 360why, one step back360 assert response.encoding == "utf-8":pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1
lines 361–398why, one step back361 assert response.is_closed362363 content = await response.aread()364365 assert content == b""366 assert response.content == b""367 assert response.is_closed368369370def test_iter_raw():371 response = httpx.Response(372 200,373 content=streaming_body(),374 )375376 raw = b""377 for part in response.iter_raw():378 raw += part379 assert raw == b"Hello, world!"380381382def test_iter_raw_with_chunksize():383 response = httpx.Response(200, content=streaming_body())384385 parts = [part for part in response.iter_raw(chunk_size=5)]386 assert parts == [b"Hello", b", wor", b"ld!"]387388 response = httpx.Response(200, content=streaming_body())389390 parts = [part for part in response.iter_raw(chunk_size=13)]391 assert parts == [b"Hello, world!"]392393 response = httpx.Response(200, content=streaming_body())394395 parts = [part for part in response.iter_raw(chunk_size=20)]396 assert parts == [b"Hello, world!"]397398Ensure that iter_bytes does not ever yield any zero-length chunks (#2068)Tom Christiebefore adoption420911b
line 399why, one step back399def test_iter_raw_doesnt_return_empty_chunks():Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
line 400why, one step back400 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 401–411why, one step back401 yield b"Hello, "402 yield b""403 yield b"world!"404 yield b""405406 response = httpx.Response(200, content=streaming_body_with_empty_chunks())407408 parts = [part for part in response.iter_raw()]409 assert parts == [b"Hello, ", b"world!"]410411:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1
lines 412–539why, one step back412def test_iter_raw_on_iterable():413 response = httpx.Response(414 200,415 content=StreamingBody(),416 )417418 raw = b""419 for part in response.iter_raw():420 raw += part421 assert raw == b"Hello, world!"422423424def test_iter_raw_on_async():425 response = httpx.Response(426 200,427 content=async_streaming_body(),428 )429430 with pytest.raises(RuntimeError):431 [part for part in response.iter_raw()]432433434def test_close_on_async():435 response = httpx.Response(436 200,437 content=async_streaming_body(),438 )439440 with pytest.raises(RuntimeError):441 response.close()442443444def test_iter_raw_increments_updates_counter():445 response = httpx.Response(200, content=streaming_body())446447 num_downloaded = response.num_bytes_downloaded448 for part in response.iter_raw():449 assert len(part) == (response.num_bytes_downloaded - num_downloaded)450 num_downloaded = response.num_bytes_downloaded451452453@pytest.mark.asyncio454async def test_aiter_raw():455 response = httpx.Response(200, content=async_streaming_body())456457 raw = b""458 async for part in response.aiter_raw():459 raw += part460 assert raw == b"Hello, world!"461462463@pytest.mark.asyncio464async def test_aiter_raw_with_chunksize():465 response = httpx.Response(200, content=async_streaming_body())466467 parts = [part async for part in response.aiter_raw(chunk_size=5)]468 assert parts == [b"Hello", b", wor", b"ld!"]469470 response = httpx.Response(200, content=async_streaming_body())471472 parts = [part async for part in response.aiter_raw(chunk_size=13)]473 assert parts == [b"Hello, world!"]474475 response = httpx.Response(200, content=async_streaming_body())476477 parts = [part async for part in response.aiter_raw(chunk_size=20)]478 assert parts == [b"Hello, world!"]479480481@pytest.mark.asyncio482async def test_aiter_raw_on_sync():483 response = httpx.Response(484 200,485 content=streaming_body(),486 )487488 with pytest.raises(RuntimeError):489 [part async for part in response.aiter_raw()]490491492@pytest.mark.asyncio493async def test_aclose_on_sync():494 response = httpx.Response(495 200,496 content=streaming_body(),497 )498499 with pytest.raises(RuntimeError):500 await response.aclose()501502503@pytest.mark.asyncio504async def test_aiter_raw_increments_updates_counter():505 response = httpx.Response(200, content=async_streaming_body())506507 num_downloaded = response.num_bytes_downloaded508 async for part in response.aiter_raw():509 assert len(part) == (response.num_bytes_downloaded - num_downloaded)510 num_downloaded = response.num_bytes_downloaded511512513def test_iter_bytes():514 response = httpx.Response(200, content=b"Hello, world!")515516 content = b""517 for part in response.iter_bytes():518 content += part519 assert content == b"Hello, world!"520521522def test_iter_bytes_with_chunk_size():523 response = httpx.Response(200, content=streaming_body())524 parts = [part for part in response.iter_bytes(chunk_size=5)]525 assert parts == [b"Hello", b", wor", b"ld!"]526527 response = httpx.Response(200, content=streaming_body())528 parts = [part for part in response.iter_bytes(chunk_size=13)]529 assert parts == [b"Hello, world!"]530531 response = httpx.Response(200, content=streaming_body())532 parts = [part for part in response.iter_bytes(chunk_size=20)]533 assert parts == [b"Hello, world!"]534535536def test_iter_bytes_with_empty_response():537 response = httpx.Response(200, content=b"")538 parts = [part for part in response.iter_bytes()]539 assert parts == []Ensure that iter_bytes does not ever yield any zero-length chunks (#2068)Tom Christiebefore adoption420911b
lines 540–542why, one step back540541542def test_iter_bytes_doesnt_return_empty_chunks():Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
line 543why, one step back543 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 544–552why, one step back544 yield b"Hello, "545 yield b""546 yield b"world!"547 yield b""548549 response = httpx.Response(200, content=streaming_body_with_empty_chunks())550551 parts = [part for part in response.iter_bytes()]552 assert parts == [b"Hello, ", b"world!"]:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1
lines 553–918why, one step back553554555@pytest.mark.asyncio556async def test_aiter_bytes():557 response = httpx.Response(558 200,559 content=b"Hello, world!",560 )561562 content = b""563 async for part in response.aiter_bytes():564 content += part565 assert content == b"Hello, world!"566567568@pytest.mark.asyncio569async def test_aiter_bytes_with_chunk_size():570 response = httpx.Response(200, content=async_streaming_body())571 parts = [part async for part in response.aiter_bytes(chunk_size=5)]572 assert parts == [b"Hello", b", wor", b"ld!"]573574 response = httpx.Response(200, content=async_streaming_body())575 parts = [part async for part in response.aiter_bytes(chunk_size=13)]576 assert parts == [b"Hello, world!"]577578 response = httpx.Response(200, content=async_streaming_body())579 parts = [part async for part in response.aiter_bytes(chunk_size=20)]580 assert parts == [b"Hello, world!"]581582583def test_iter_text():584 response = httpx.Response(585 200,586 content=b"Hello, world!",587 )588589 content = ""590 for part in response.iter_text():591 content += part592 assert content == "Hello, world!"593594595def test_iter_text_with_chunk_size():596 response = httpx.Response(200, content=b"Hello, world!")597 parts = [part for part in response.iter_text(chunk_size=5)]598 assert parts == ["Hello", ", wor", "ld!"]599600 response = httpx.Response(200, content=b"Hello, world!")601 parts = [part for part in response.iter_text(chunk_size=13)]602 assert parts == ["Hello, world!"]603604 response = httpx.Response(200, content=b"Hello, world!")605 parts = [part for part in response.iter_text(chunk_size=20)]606 assert parts == ["Hello, world!"]607608609@pytest.mark.asyncio610async def test_aiter_text():611 response = httpx.Response(612 200,613 content=b"Hello, world!",614 )615616 content = ""617 async for part in response.aiter_text():618 content += part619 assert content == "Hello, world!"620621622@pytest.mark.asyncio623async def test_aiter_text_with_chunk_size():624 response = httpx.Response(200, content=b"Hello, world!")625 parts = [part async for part in response.aiter_text(chunk_size=5)]626 assert parts == ["Hello", ", wor", "ld!"]627628 response = httpx.Response(200, content=b"Hello, world!")629 parts = [part async for part in response.aiter_text(chunk_size=13)]630 assert parts == ["Hello, world!"]631632 response = httpx.Response(200, content=b"Hello, world!")633 parts = [part async for part in response.aiter_text(chunk_size=20)]634 assert parts == ["Hello, world!"]635636637def test_iter_lines():638 response = httpx.Response(639 200,640 content=b"Hello,\nworld!",641 )642 content = [line for line in response.iter_lines()]643 assert content == ["Hello,\n", "world!"]644645646@pytest.mark.asyncio647async def test_aiter_lines():648 response = httpx.Response(649 200,650 content=b"Hello,\nworld!",651 )652653 content = []654 async for line in response.aiter_lines():655 content.append(line)656 assert content == ["Hello,\n", "world!"]657658659def test_sync_streaming_response():660 response = httpx.Response(661 200,662 content=streaming_body(),663 )664665 assert response.status_code == 200666 assert not response.is_closed667668 content = response.read()669670 assert content == b"Hello, world!"671 assert response.content == b"Hello, world!"672 assert response.is_closed673674675@pytest.mark.asyncio676async def test_async_streaming_response():677 response = httpx.Response(678 200,679 content=async_streaming_body(),680 )681682 assert response.status_code == 200683 assert not response.is_closed684685 content = await response.aread()686687 assert content == b"Hello, world!"688 assert response.content == b"Hello, world!"689 assert response.is_closed690691692def test_cannot_read_after_stream_consumed():693 response = httpx.Response(694 200,695 content=streaming_body(),696 )697698 content = b""699 for part in response.iter_bytes():700 content += part701702 with pytest.raises(httpx.StreamConsumed):703 response.read()704705706@pytest.mark.asyncio707async def test_cannot_aread_after_stream_consumed():708 response = httpx.Response(709 200,710 content=async_streaming_body(),711 )712713 content = b""714 async for part in response.aiter_bytes():715 content += part716717 with pytest.raises(httpx.StreamConsumed):718 await response.aread()719720721def test_cannot_read_after_response_closed():722 response = httpx.Response(723 200,724 content=streaming_body(),725 )726727 response.close()728 with pytest.raises(httpx.StreamClosed):729 response.read()730731732@pytest.mark.asyncio733async def test_cannot_aread_after_response_closed():734 response = httpx.Response(735 200,736 content=async_streaming_body(),737 )738739 await response.aclose()740 with pytest.raises(httpx.StreamClosed):741 await response.aread()742743744@pytest.mark.asyncio745async def test_elapsed_not_available_until_closed():746 response = httpx.Response(747 200,748 content=async_streaming_body(),749 )750751 with pytest.raises(RuntimeError):752 response.elapsed753754755def test_unknown_status_code():756 response = httpx.Response(757 600,758 )759 assert response.status_code == 600760 assert response.reason_phrase == ""761 assert response.text == ""762763764def test_json_with_specified_encoding():765 data = {"greeting": "hello", "recipient": "world"}766 content = json.dumps(data).encode("utf-16")767 headers = {"Content-Type": "application/json, charset=utf-16"}768 response = httpx.Response(769 200,770 content=content,771 headers=headers,772 )773 assert response.json() == data774775776def test_json_with_options():777 data = {"greeting": "hello", "recipient": "world", "amount": 1}778 content = json.dumps(data).encode("utf-16")779 headers = {"Content-Type": "application/json, charset=utf-16"}780 response = httpx.Response(781 200,782 content=content,783 headers=headers,784 )785 assert response.json(parse_int=str)["amount"] == "1"786787788@pytest.mark.parametrize(789 "encoding",790 [791 "utf-8",792 "utf-8-sig",793 "utf-16",794 "utf-16-be",795 "utf-16-le",796 "utf-32",797 "utf-32-be",798 "utf-32-le",799 ],800)801def test_json_without_specified_charset(encoding):802 data = {"greeting": "hello", "recipient": "world"}803 content = json.dumps(data).encode(encoding)804 headers = {"Content-Type": "application/json"}805 response = httpx.Response(806 200,807 content=content,808 headers=headers,809 )810 assert response.json() == data811812813@pytest.mark.parametrize(814 "encoding",815 [816 "utf-8",817 "utf-8-sig",818 "utf-16",819 "utf-16-be",820 "utf-16-le",821 "utf-32",822 "utf-32-be",823 "utf-32-le",824 ],825)826def test_json_with_specified_charset(encoding):827 data = {"greeting": "hello", "recipient": "world"}828 content = json.dumps(data).encode(encoding)829 headers = {"Content-Type": f"application/json; charset={encoding}"}830 response = httpx.Response(831 200,832 content=content,833 headers=headers,834 )835 assert response.json() == data836837838@pytest.mark.parametrize(839 "headers, expected",840 [841 (842 {"Link": "<https://example.com>; rel='preload'"},843 {"preload": {"rel": "preload", "url": "https://example.com"}},844 ),845 (846 {"Link": '</hub>; rel="hub", </resource>; rel="self"'},847 {848 "hub": {"url": "/hub", "rel": "hub"},849 "self": {"url": "/resource", "rel": "self"},850 },851 ),852 ],853)854def test_link_headers(headers, expected):855 response = httpx.Response(856 200,857 content=None,858 headers=headers,859 )860 assert response.links == expected861862863@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))864def test_decode_error_with_request(header_value):865 headers = [(b"Content-Encoding", header_value)]866 body = b"test 123"867 compressed_body = brotli.compress(body)[3:]868 with pytest.raises(httpx.DecodingError):869 httpx.Response(870 200,871 headers=headers,872 content=compressed_body,873 )874875 with pytest.raises(httpx.DecodingError):876 httpx.Response(877 200,878 headers=headers,879 content=compressed_body,880 request=httpx.Request("GET", "https://www.example.org/"),881 )882883884@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))885def test_value_error_without_request(header_value):886 headers = [(b"Content-Encoding", header_value)]887 body = b"test 123"888 compressed_body = brotli.compress(body)[3:]889 with pytest.raises(httpx.DecodingError):890 httpx.Response(200, headers=headers, content=compressed_body)891892893def test_response_with_unset_request():894 response = httpx.Response(200, content=b"Hello, world!")895896 assert response.status_code == 200897 assert response.reason_phrase == "OK"898 assert response.text == "Hello, world!"899 assert not response.is_error900901902def test_set_request_after_init():903 response = httpx.Response(200, content=b"Hello, world!")904905 response.request = httpx.Request("GET", "https://www.example.org")906907 assert response.request.method == "GET"908 assert response.request.url == "https://www.example.org"909910911def test_cannot_access_unset_request():912 response = httpx.Response(200, content=b"Hello, world!")913914 with pytest.raises(RuntimeError):915 response.request916917918def test_generator_with_transfer_encoding_header():Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
line 919why, one step back919 def content() -> typing.Iterator[bytes]:use # pragma: no cover instead of # pragma: nocover (#2471)Adrian Garcia Badaraccobefore adoption16e2830
line 920why, one step back920 yield b"test 123" # pragma: no cover:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1
lines 921–926why, one step back921922 response = httpx.Response(200, content=content())923 assert response.headers == {"Transfer-Encoding": "chunked"}924925926def test_generator_with_content_length_header():Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
line 927why, one step back927 def content() -> typing.Iterator[bytes]:use # pragma: no cover instead of # pragma: nocover (#2471)Adrian Garcia Badaraccobefore adoption16e2830
line 928why, one step back928 yield b"test 123" # pragma: no cover:pencil: Docs patch following PR #1791 section compatibility.encoding (#1812)TAHRI Ahmed Rbefore adoptionecbece1
lines 929–970why, one step back929930 headers = {"Content-Length": "8"}931 response = httpx.Response(200, content=content(), headers=headers)932 assert response.headers == {"Content-Length": "8"}933934935def test_response_picklable():936 response = httpx.Response(937 200,938 content=b"Hello, world!",939 request=httpx.Request("GET", "https://example.org"),940 )941 pickle_response = pickle.loads(pickle.dumps(response))942 assert pickle_response.is_closed is True943 assert pickle_response.is_stream_consumed is True944 assert pickle_response.next_request is None945 assert pickle_response.stream is not None946 assert pickle_response.content == b"Hello, world!"947 assert pickle_response.status_code == 200948 assert pickle_response.request.url == response.request.url949 assert pickle_response.extensions == {}950 assert pickle_response.history == []951952953@pytest.mark.asyncio954async def test_response_async_streaming_picklable():955 response = httpx.Response(200, content=async_streaming_body())956 pickle_response = pickle.loads(pickle.dumps(response))957 with pytest.raises(httpx.ResponseNotRead):958 pickle_response.content959 with pytest.raises(httpx.StreamClosed):960 await pickle_response.aread()961 assert pickle_response.is_stream_consumed is False962 assert pickle_response.num_bytes_downloaded == 0963 assert pickle_response.headers == {"Transfer-Encoding": "chunked"}964965 response = httpx.Response(200, content=async_streaming_body())966 await response.aread()967 pickle_response = pickle.loads(pickle.dumps(response))968 assert pickle_response.is_stream_consumed is True969 assert pickle_response.content == b"Hello, world!"970 assert pickle_response.num_bytes_downloaded == 13Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28
lines 971–1014why, one step back971972973def test_response_decode_text_using_autodetect():974 # Ensure that a 'default_encoding="autodetect"' on the response allows for975 # encoding autodetection to be used when no "Content-Type: text/plain; charset=..."976 # info is present.977 #978 # Here we have some french text encoded with ISO-8859-1, rather than UTF-8.979 text = (980 "Non-seulement Despréaux ne se trompait pas, mais de tous les écrivains "981 "que la France a produits, sans excepter Voltaire lui-même, imprégné de "982 "l'esprit anglais par son séjour à Londres, c'est incontestablement "983 "Molière ou Poquelin qui reproduit avec l'exactitude la plus vive et la "984 "plus complète le fond du génie français."985 )986 content = text.encode("ISO-8859-1")987 response = httpx.Response(200, content=content, default_encoding=autodetect)988989 assert response.status_code == 200990 assert response.reason_phrase == "OK"991 assert response.encoding == "ISO-8859-1"992 assert response.text == text993994995def test_response_decode_text_using_explicit_encoding():996 # Ensure that a 'default_encoding="..."' on the response is used for text decoding997 # when no "Content-Type: text/plain; charset=..."" info is present.998 #999 # Here we have some french text encoded with Windows-1252, rather than UTF-8.1000 # https://en.wikipedia.org/wiki/Windows-12521001 text = (1002 "Non-seulement Despréaux ne se trompait pas, mais de tous les écrivains "1003 "que la France a produits, sans excepter Voltaire lui-même, imprégné de "1004 "l'esprit anglais par son séjour à Londres, c'est incontestablement "1005 "Molière ou Poquelin qui reproduit avec l'exactitude la plus vive et la "1006 "plus complète le fond du génie français."1007 )1008 content = text.encode("cp1252")1009 response = httpx.Response(200, content=content, default_encoding="cp1252")10101011 assert response.status_code == 2001012 assert response.reason_phrase == "OK"1013 assert response.encoding == "cp1252"1014 assert response.text == text