test_responses.py
This file
Path
tests/models/test_responses.py
1,020 lines · 29.1 KiB · Python
Last changed by
Drop private imports from test_decoders.py (#2570)Florimond Mancabefore adoptioncca6206
History of this fileTake it
The walk stopped after 200 commits: lines older than 3f9da8e point at it.
Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 1–2why, one step back1import json2import pickleTyping: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
line 3why, one step back3import typingBump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
line 4why, one step back4Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28
line 5why, one step back5import chardetBump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 6–16why, one step back6import pytest78import httpx91011class StreamingBody:12 def __iter__(self):13 yield b"Hello, "14 yield b"world!"1516Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
line 17why, one step back17def streaming_body() -> typing.Iterator[bytes]:Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 18–21why, one step back18 yield b"Hello, "19 yield b"world!"2021Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
line 22why, one step back22async def async_streaming_body() -> typing.AsyncIterator[bytes]:Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 23–26why, one step back23 yield b"Hello, "24 yield b"world!"2526Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28
lines 27–30why, one step back27def autodetect(content):28 return chardet.detect(content).get("encoding")2930Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 31–171why, one step back31def 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()9798 # 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 )119120 # 4xx status codes are a client error.121 response = httpx.Response(403, request=request)122 assert response.is_client_error123 assert response.is_error124 with pytest.raises(httpx.HTTPStatusError) as exc_info:125 response.raise_for_status()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 )130131 # 5xx status codes are a server error.132 response = httpx.Response(500, request=request)133 assert response.is_server_error134 assert response.is_error135 with pytest.raises(httpx.HTTPStatusError) as exc_info:136 response.raise_for_status()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 )141142 # 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"170171Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28
line 172why, one step back172def test_response_default_to_utf8_encoding():Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
line 173why, one step back173 """Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28
line 174why, one step back174 Default to utf-8 encoding if there is no Content-Type header.Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 175–181why, one step back175 """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 back182 assert response.encoding == "utf-8"Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 183–184why, one step back183184Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28
line 185why, one step back185def test_response_fallback_to_utf8_encoding():Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
line 186why, one step back186 """Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28
line 187why, one step back187 Fallback to utf-8 if we get an invalid charset in the Content-Type header.Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 188–196why, one step back188 """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 back197 assert response.encoding == "utf-8"Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 198–212why, one step back198199200def 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 == 200Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28
line 213why, one step back213 assert response.encoding == "utf-8"Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 214–229why, one step back214 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 back230 assert response.encoding == "utf-8"Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 231–235why, one step back231232233def 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 back236 even with no charset specified, if autodetect is enabled.Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 237–240why, one step back237 """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 back241 200, content=content, headers=headers, default_encoding=autodetectBump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 242–249why, one step back242 )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 back250 even with no charset specified, if autodetect is enabled.Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 251–254why, one step back251 """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 back255 200, content=content, headers=headers, default_encoding=autodetectBump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 256–262why, one step back256 )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 back263 Default to attempting utf-8 encoding for non-text content-type headers.Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 264–271why, one step back264 """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 back272 assert response.encoding == "utf-8"Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 273–308why, one step back273274275def 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 back309 assert response.encoding == "utf-8"Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 310–323why, one step back310 assert response.is_closed311312 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 back324 assert response.encoding == "utf-8"Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 325–333why, one step back325 assert response.is_closed326327 content = response.read()328329 assert content == b""330 assert response.content == b""331 assert response.is_closed332333replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 334why, one step back334@pytest.mark.anyioBump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 335–342why, one step back335async 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 back343 assert response.encoding == "utf-8"Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 344–352why, one step back344 assert response.is_closed345346 content = await response.aread()347348 assert content == b"Hello, world!"349 assert response.content == b"Hello, world!"350 assert response.is_closed351352replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 353why, one step back353@pytest.mark.anyioBump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 354–358why, one step back354async 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 back359 assert response.encoding == "utf-8"Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 360–386why, one step back360 assert response.is_closed361362 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())383 parts = [part for part in response.iter_raw(chunk_size=5)]384 assert parts == [b"Hello", b", wor", b"ld!"]385386 response = httpx.Response(200, content=streaming_body())Drop private imports from test_decoders.py (#2570)Florimond Mancabefore adoptioncca6206
lines 387–388why, one step back387 parts = [part for part in response.iter_raw(chunk_size=7)]388 assert parts == [b"Hello, ", b"world!"]Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
line 389why, one step back389Drop private imports from test_decoders.py (#2570)Florimond Mancabefore adoptioncca6206
line 390why, one step back390 response = httpx.Response(200, content=streaming_body())Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 391–399why, one step back391 parts = [part for part in response.iter_raw(chunk_size=13)]392 assert parts == [b"Hello, world!"]393394 response = httpx.Response(200, content=streaming_body())395 parts = [part for part in response.iter_raw(chunk_size=20)]396 assert parts == [b"Hello, world!"]397398399def 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]:Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 401–452why, 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!"]410411412def 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_downloaded451452replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 453why, one step back453@pytest.mark.anyioBump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 454–462why, one step back454async 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!"461462replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 463why, one step back463@pytest.mark.anyioBump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 464–480why, one step back464async 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!"]479480replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 481why, one step back481@pytest.mark.anyioBump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 482–491why, one step back482async 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()]490491replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 492why, one step back492@pytest.mark.anyioBump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 493–502why, one step back493async 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()501502replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 503why, one step back503@pytest.mark.anyioBump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 504–542why, one step back504async 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 == []540541542def 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]:Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 544–554why, 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!"]553554replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 555why, one step back555@pytest.mark.anyioBump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 556–567why, one step back556async 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!"566567replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 568why, one step back568@pytest.mark.anyioBump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 569–598why, one step back569async 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!"]Drop private imports from test_decoders.py (#2570)Florimond Mancabefore adoptioncca6206
lines 599–606why, one step back599600 response = httpx.Response(200, content=b"Hello, world!!")601 parts = [part for part in response.iter_text(chunk_size=7)]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=7)]606 assert parts == ["Hello, ", "world!"]Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 607–616why, one step back607608 response = httpx.Response(200, content=b"Hello, world!")609 parts = [part for part in response.iter_text(chunk_size=13)]610 assert parts == ["Hello, world!"]611612 response = httpx.Response(200, content=b"Hello, world!")613 parts = [part for part in response.iter_text(chunk_size=20)]614 assert parts == ["Hello, world!"]615616replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 617why, one step back617@pytest.mark.anyioBump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 618–629why, one step back618async def test_aiter_text():619 response = httpx.Response(620 200,621 content=b"Hello, world!",622 )623624 content = ""625 async for part in response.aiter_text():626 content += part627 assert content == "Hello, world!"628629replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 630why, one step back630@pytest.mark.anyioBump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 631–650why, one step back631async def test_aiter_text_with_chunk_size():632 response = httpx.Response(200, content=b"Hello, world!")633 parts = [part async for part in response.aiter_text(chunk_size=5)]634 assert parts == ["Hello", ", wor", "ld!"]635636 response = httpx.Response(200, content=b"Hello, world!")637 parts = [part async for part in response.aiter_text(chunk_size=13)]638 assert parts == ["Hello, world!"]639640 response = httpx.Response(200, content=b"Hello, world!")641 parts = [part async for part in response.aiter_text(chunk_size=20)]642 assert parts == ["Hello, world!"]643644645def test_iter_lines():646 response = httpx.Response(647 200,648 content=b"Hello,\nworld!",649 )650 content = [line for line in response.iter_lines()]Change LineDecoder to match stdlib splitlines, resulting in significant speed up (#2423)Gianni Tedescobefore adoption85c5898
line 651why, one step back651 assert content == ["Hello,", "world!"]Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 652–653why, one step back652653replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 654why, one step back654@pytest.mark.anyioBump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 655–663why, one step back655async def test_aiter_lines():656 response = httpx.Response(657 200,658 content=b"Hello,\nworld!",659 )660661 content = []662 async for line in response.aiter_lines():663 content.append(line)Change LineDecoder to match stdlib splitlines, resulting in significant speed up (#2423)Gianni Tedescobefore adoption85c5898
line 664why, one step back664 assert content == ["Hello,", "world!"]Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 665–682why, one step back665666667def test_sync_streaming_response():668 response = httpx.Response(669 200,670 content=streaming_body(),671 )672673 assert response.status_code == 200674 assert not response.is_closed675676 content = response.read()677678 assert content == b"Hello, world!"679 assert response.content == b"Hello, world!"680 assert response.is_closed681682replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 683why, one step back683@pytest.mark.anyioBump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 684–713why, one step back684async def test_async_streaming_response():685 response = httpx.Response(686 200,687 content=async_streaming_body(),688 )689690 assert response.status_code == 200691 assert not response.is_closed692693 content = await response.aread()694695 assert content == b"Hello, world!"696 assert response.content == b"Hello, world!"697 assert response.is_closed698699700def test_cannot_read_after_stream_consumed():701 response = httpx.Response(702 200,703 content=streaming_body(),704 )705706 content = b""707 for part in response.iter_bytes():708 content += part709710 with pytest.raises(httpx.StreamConsumed):711 response.read()712713replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 714why, one step back714@pytest.mark.anyioBump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 715–739why, one step back715async def test_cannot_aread_after_stream_consumed():716 response = httpx.Response(717 200,718 content=async_streaming_body(),719 )720721 content = b""722 async for part in response.aiter_bytes():723 content += part724725 with pytest.raises(httpx.StreamConsumed):726 await response.aread()727728729def test_cannot_read_after_response_closed():730 response = httpx.Response(731 200,732 content=streaming_body(),733 )734735 response.close()736 with pytest.raises(httpx.StreamClosed):737 response.read()738739replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 740why, one step back740@pytest.mark.anyioBump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 741–751why, one step back741async def test_cannot_aread_after_response_closed():742 response = httpx.Response(743 200,744 content=async_streaming_body(),745 )746747 await response.aclose()748 with pytest.raises(httpx.StreamClosed):749 await response.aread()750751replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 752why, one step back752@pytest.mark.anyioBump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 753–759why, one step back753async def test_elapsed_not_available_until_closed():754 response = httpx.Response(755 200,756 content=async_streaming_body(),757 )758759 with pytest.raises(RuntimeError):Use ruff instead of flake8, autoflake and isort (#2648)Marcelo Trylesinskibefore adoptiondaec2bd
line 760why, one step back760 response.elapsed # noqa: B018Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 761–873why, one step back761762763def test_unknown_status_code():764 response = httpx.Response(765 600,766 )767 assert response.status_code == 600768 assert response.reason_phrase == ""769 assert response.text == ""770771772def test_json_with_specified_encoding():773 data = {"greeting": "hello", "recipient": "world"}774 content = json.dumps(data).encode("utf-16")775 headers = {"Content-Type": "application/json, charset=utf-16"}776 response = httpx.Response(777 200,778 content=content,779 headers=headers,780 )781 assert response.json() == data782783784def test_json_with_options():785 data = {"greeting": "hello", "recipient": "world", "amount": 1}786 content = json.dumps(data).encode("utf-16")787 headers = {"Content-Type": "application/json, charset=utf-16"}788 response = httpx.Response(789 200,790 content=content,791 headers=headers,792 )793 assert response.json(parse_int=str)["amount"] == "1"794795796@pytest.mark.parametrize(797 "encoding",798 [799 "utf-8",800 "utf-8-sig",801 "utf-16",802 "utf-16-be",803 "utf-16-le",804 "utf-32",805 "utf-32-be",806 "utf-32-le",807 ],808)809def test_json_without_specified_charset(encoding):810 data = {"greeting": "hello", "recipient": "world"}811 content = json.dumps(data).encode(encoding)812 headers = {"Content-Type": "application/json"}813 response = httpx.Response(814 200,815 content=content,816 headers=headers,817 )818 assert response.json() == data819820821@pytest.mark.parametrize(822 "encoding",823 [824 "utf-8",825 "utf-8-sig",826 "utf-16",827 "utf-16-be",828 "utf-16-le",829 "utf-32",830 "utf-32-be",831 "utf-32-le",832 ],833)834def test_json_with_specified_charset(encoding):835 data = {"greeting": "hello", "recipient": "world"}836 content = json.dumps(data).encode(encoding)837 headers = {"Content-Type": f"application/json; charset={encoding}"}838 response = httpx.Response(839 200,840 content=content,841 headers=headers,842 )843 assert response.json() == data844845846@pytest.mark.parametrize(847 "headers, expected",848 [849 (850 {"Link": "<https://example.com>; rel='preload'"},851 {"preload": {"rel": "preload", "url": "https://example.com"}},852 ),853 (854 {"Link": '</hub>; rel="hub", </resource>; rel="self"'},855 {856 "hub": {"url": "/hub", "rel": "hub"},857 "self": {"url": "/resource", "rel": "self"},858 },859 ),860 ],861)862def test_link_headers(headers, expected):863 response = httpx.Response(864 200,865 content=None,866 headers=headers,867 )868 assert response.links == expected869870871@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))872def test_decode_error_with_request(header_value):873 headers = [(b"Content-Encoding", header_value)]Drop unneccessary private import in tests (#2498)Tom Christiebefore adoptionaf56476
line 874why, one step back874 broken_compressed_body = b"xxxxxxxxxxxxxx"Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 875–878why, one step back875 with pytest.raises(httpx.DecodingError):876 httpx.Response(877 200,878 headers=headers,Drop unneccessary private import in tests (#2498)Tom Christiebefore adoptionaf56476
line 879why, one step back879 content=broken_compressed_body,Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 880–885why, one step back880 )881882 with pytest.raises(httpx.DecodingError):883 httpx.Response(884 200,885 headers=headers,Drop unneccessary private import in tests (#2498)Tom Christiebefore adoptionaf56476
line 886why, one step back886 content=broken_compressed_body,Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 887–893why, one step back887 request=httpx.Request("GET", "https://www.example.org/"),888 )889890891@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))892def test_value_error_without_request(header_value):893 headers = [(b"Content-Encoding", header_value)]Drop unneccessary private import in tests (#2498)Tom Christiebefore adoptionaf56476
line 894why, one step back894 broken_compressed_body = b"xxxxxxxxxxxxxx"Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
line 895why, one step back895 with pytest.raises(httpx.DecodingError):Drop unneccessary private import in tests (#2498)Tom Christiebefore adoptionaf56476
line 896why, one step back896 httpx.Response(200, headers=headers, content=broken_compressed_body)Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 897–920why, one step back897898899def test_response_with_unset_request():900 response = httpx.Response(200, content=b"Hello, world!")901902 assert response.status_code == 200903 assert response.reason_phrase == "OK"904 assert response.text == "Hello, world!"905 assert not response.is_error906907908def test_set_request_after_init():909 response = httpx.Response(200, content=b"Hello, world!")910911 response.request = httpx.Request("GET", "https://www.example.org")912913 assert response.request.method == "GET"914 assert response.request.url == "https://www.example.org"915916917def test_cannot_access_unset_request():918 response = httpx.Response(200, content=b"Hello, world!")919920 with pytest.raises(RuntimeError):Use ruff instead of flake8, autoflake and isort (#2648)Marcelo Trylesinskibefore adoptiondaec2bd
line 921why, one step back921 response.request # noqa: B018Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 922–924why, one step back922923924def test_generator_with_transfer_encoding_header():Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
line 925why, one step back925 def content() -> typing.Iterator[bytes]:use # pragma: no cover instead of # pragma: nocover (#2471)Adrian Garcia Badaraccobefore adoption16e2830
line 926why, one step back926 yield b"test 123" # pragma: no coverBump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 927–932why, one step back927928 response = httpx.Response(200, content=content())929 assert response.headers == {"Transfer-Encoding": "chunked"}930931932def test_generator_with_content_length_header():Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
line 933why, one step back933 def content() -> typing.Iterator[bytes]:use # pragma: no cover instead of # pragma: nocover (#2471)Adrian Garcia Badaraccobefore adoption16e2830
line 934why, one step back934 yield b"test 123" # pragma: no coverBump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 935–958why, one step back935936 headers = {"Content-Length": "8"}937 response = httpx.Response(200, content=content(), headers=headers)938 assert response.headers == {"Content-Length": "8"}939940941def test_response_picklable():942 response = httpx.Response(943 200,944 content=b"Hello, world!",945 request=httpx.Request("GET", "https://example.org"),946 )947 pickle_response = pickle.loads(pickle.dumps(response))948 assert pickle_response.is_closed is True949 assert pickle_response.is_stream_consumed is True950 assert pickle_response.next_request is None951 assert pickle_response.stream is not None952 assert pickle_response.content == b"Hello, world!"953 assert pickle_response.status_code == 200954 assert pickle_response.request.url == response.request.url955 assert pickle_response.extensions == {}956 assert pickle_response.history == []957958replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
line 959why, one step back959@pytest.mark.anyioBump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 960–963why, one step back960async def test_response_async_streaming_picklable():961 response = httpx.Response(200, content=async_streaming_body())962 pickle_response = pickle.loads(pickle.dumps(response))963 with pytest.raises(httpx.ResponseNotRead):Use ruff instead of flake8, autoflake and isort (#2648)Marcelo Trylesinskibefore adoptiondaec2bd
line 964why, one step back964 pickle_response.content # noqa: B018Bump `black` to 22.3.0 (#2153)Marcelo Trylesinskibefore adoption3f9da8e
lines 965–976why, one step back965 with pytest.raises(httpx.StreamClosed):966 await pickle_response.aread()967 assert pickle_response.is_stream_consumed is False968 assert pickle_response.num_bytes_downloaded == 0969 assert pickle_response.headers == {"Transfer-Encoding": "chunked"}970971 response = httpx.Response(200, content=async_streaming_body())972 await response.aread()973 pickle_response = pickle.loads(pickle.dumps(response))974 assert pickle_response.is_stream_consumed is True975 assert pickle_response.content == b"Hello, world!"976 assert pickle_response.num_bytes_downloaded == 13Make charset auto-detection optional. (#2165)Tom Christiebefore adoption1c33a28
lines 977–1020why, one step back977978979def test_response_decode_text_using_autodetect():980 # Ensure that a 'default_encoding="autodetect"' on the response allows for981 # encoding autodetection to be used when no "Content-Type: text/plain; charset=..."982 # info is present.983 #984 # Here we have some french text encoded with ISO-8859-1, rather than UTF-8.985 text = (986 "Non-seulement Despréaux ne se trompait pas, mais de tous les écrivains "987 "que la France a produits, sans excepter Voltaire lui-même, imprégné de "988 "l'esprit anglais par son séjour à Londres, c'est incontestablement "989 "Molière ou Poquelin qui reproduit avec l'exactitude la plus vive et la "990 "plus complète le fond du génie français."991 )992 content = text.encode("ISO-8859-1")993 response = httpx.Response(200, content=content, default_encoding=autodetect)994995 assert response.status_code == 200996 assert response.reason_phrase == "OK"997 assert response.encoding == "ISO-8859-1"998 assert response.text == text99910001001def test_response_decode_text_using_explicit_encoding():1002 # Ensure that a 'default_encoding="..."' on the response is used for text decoding1003 # when no "Content-Type: text/plain; charset=..."" info is present.1004 #1005 # Here we have some french text encoded with Windows-1252, rather than UTF-8.1006 # https://en.wikipedia.org/wiki/Windows-12521007 text = (1008 "Non-seulement Despréaux ne se trompait pas, mais de tous les écrivains "1009 "que la France a produits, sans excepter Voltaire lui-même, imprégné de "1010 "l'esprit anglais par son séjour à Londres, c'est incontestablement "1011 "Molière ou Poquelin qui reproduit avec l'exactitude la plus vive et la "1012 "plus complète le fond du génie français."1013 )1014 content = text.encode("cp1252")1015 response = httpx.Response(200, content=content, default_encoding="cp1252")10161017 assert response.status_code == 2001018 assert response.reason_phrase == "OK"1019 assert response.encoding == "cp1252"1020 assert response.text == text