Rejig test and tighten up models API
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Tom Christie · committed by Tom Christie · parent 4d908d0 · Browse files · 18 files·+840 added−599 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
18 files+840 added−599 removed
- tests:+722 added−568 removed
- other:+118 added−31 removed
Provenance
- Commit
dea4d42- Tree
67a9104- Author
Tom Christie <tom@tomchristie.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
4d908d0
18 files changed+840 added−599 removed
modified:httpcore/exceptions.py+16 added-4 removed
1+# Timeout exceptions...2+3+4 class Timeout(Exception):5 """6 A base class for all timeouts.7 """22 unmodified lines30 Timeout while waiting to acquire a connection from the pool.31 """32 33 34+# HTTP exceptions...35+36+37+class ProtocolError(Exception):38+ """39+ Malformed HTTP.40+ """41+42+43+# Redirect exceptions...44+45+46 class RedirectError(Exception):47 """48 Base class for HTTP redirect errors.49 """17 unmodified lines67 Infinite redirect loop.68 """69 70 56-class ProtocolError(Exception):57- """58- Malformed HTTP.59- """71+# Response exceptions...72 73 74 class StreamConsumed(Exception):75 """22 unmodified linesmodified:httpcore/models.py+98 added-23 removed
123 unmodified lines124 """125 A case-insensitive multidict.126 """127 128- def __init__(self, headers: HeaderTypes = None) -> None:128+ def __init__(self, headers: HeaderTypes = None, encoding: str = None) -> None:129 if headers is None:130 self._list = [] # type: typing.List[typing.Tuple[bytes, bytes]]131 elif isinstance(headers, Headers):132 self._list = list(headers.raw)133 elif isinstance(headers, dict):134 self._list = [135- (normalize_header_key(k), normalize_header_value(v))135+ (normalize_header_key(k, encoding), normalize_header_value(v, encoding))136 for k, v in headers.items()137 ]138 else:139 self._list = [140- (normalize_header_key(k), normalize_header_value(v)) for k, v in headers140+ (normalize_header_key(k, encoding), normalize_header_value(v, encoding))141+ for k, v in headers142 ]143+ self._encoding = encoding144 145 @property146+ def encoding(self) -> str:147+ """148+ Header encoding is mandated as ascii, but utf-8 or iso-8859-1 may be149+ seen in the wild.150+ """151+ if self._encoding is None:152+ for encoding in ["ascii", "utf-8"]:153+ for key, value in self.raw:154+ try:155+ key.decode(encoding)156+ value.decode(encoding)157+ except UnicodeDecodeError:158+ break159+ else:160+ # The else block runs if 'break' did not occur, meaning161+ # all values fitted the encoding.162+ self._encoding = encoding163+ break164+ else:165+ # The ISO-8859-1 encoding covers all 256 code points in a byte,166+ # so will never raise decode errors.167+ self._encoding = "iso-8859-1"168+ return self._encoding169+170+ @encoding.setter171+ def encoding(self, value: str) -> None:172+ self._encoding = value173+174+ @property175 def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:176+ """177+ Returns a list of the raw header items, as byte pairs.178+ May be mutated in-place.179+ """180 return self._list181 182 def keys(self) -> typing.List[str]: # type: ignore148- return [key.decode("latin-1") for key, value in self._list]183+ return [key.decode(self.encoding) for key, value in self._list]184 185 def values(self) -> typing.List[str]: # type: ignore151- return [value.decode("latin-1") for key, value in self._list]186+ return [value.decode(self.encoding) for key, value in self._list]187 188 def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore189 return [155- (key.decode("latin-1"), value.decode("latin-1"))190+ (key.decode(self.encoding), value.decode(self.encoding))191 for key, value in self._list192 ]193 194 def get(self, key: str, default: typing.Any = None) -> typing.Any:1 unmodified line196 return self[key]197 except KeyError:198 return default199 165- def getlist(self, key: str) -> typing.List[str]:166- get_header_key = key.lower().encode("latin-1")167- return [168- item_value.decode("latin-1")200+ def getlist(self, key: str, default: typing.Any = None, split_commas = None) -> typing.List[str]:201+ """202+ Return multiple header values.203+204+ If there are header values that include commas, then we default to205+ spliting them into multiple results, except for Set-Cookie.206+207+ See: https://tools.ietf.org/html/rfc7230#section-3.2.2208+ """209+ get_header_key = key.lower().encode(self.encoding)210+ if split_commas is None:211+ split_commas = get_header_key != b'set-cookie'212+213+ values = [214+ item_value.decode(self.encoding)215 for item_key, item_value in self._list216 if item_key == get_header_key217 ]218 219+ if not values:220+ return [] if default is None else default221+222+ if not split_commas:223+ return values224+225+ split_values = []226+ for value in values:227+ split_values.extend([item.strip() for item in value.split(",")])228+ return split_values229+230 def __getitem__(self, key: str) -> str:174- get_header_key = key.lower().encode("latin-1")231+ """232+ Return a single header value.233+234+ If there are multiple headers with the same key, then we concatenate235+ them with commas. See: https://tools.ietf.org/html/rfc7230#section-3.2.2236+ """237+ normalized_key = key.lower().encode(self.encoding)238+239+ items = []240 for header_key, header_value in self._list:176- if header_key == get_header_key:177- return header_value.decode("latin-1")241+ if header_key == normalized_key:242+ items.append(header_value.decode(self.encoding))243+244+ if items:245+ return ", ".join(items)246+247 raise KeyError(key)248 249 def __setitem__(self, key: str, value: str) -> None:250 """251 Set the header `key` to `value`, removing any duplicate entries.252 Retains insertion order.253 """185- set_key = key.lower().encode("latin-1")186- set_value = value.encode("latin-1")254+ set_key = key.lower().encode(self.encoding)255+ set_value = value.encode(self.encoding)256 257 found_indexes = []258 for idx, (item_key, item_value) in enumerate(self._list):259 if item_key == set_key:11 unmodified lines271 def __delitem__(self, key: str) -> None:272 """273 Remove the header `key`.274 """206- del_key = key.lower().encode("latin-1")275+ del_key = key.lower().encode(self.encoding)276 277 pop_indexes = []278 for idx, (item_key, item_value) in enumerate(self._list):279 if item_key == del_key:2 unmodified lines282 for idx in reversed(pop_indexes):283 del self._list[idx]284 285 def __contains__(self, key: typing.Any) -> bool:217- get_header_key = key.lower().encode("latin-1")286+ get_header_key = key.lower().encode(self.encoding)287 for header_key, header_value in self._list:288 if header_key == get_header_key:289 return True290 return False10 unmodified lines301 return sorted(self._list) == sorted(other._list)302 303 def __repr__(self) -> str:304 class_name = self.__class__.__name__305+306+ encoding_str = ""307+ if self.encoding != "ascii":308+ encoding_str = f", encoding={self.encoding!r}"309+310 as_dict = dict(self.items())311 if len(as_dict) == len(self):238- return f"{class_name}({as_dict!r})"239- return f"{class_name}(raw={self.raw!r})"312+ return f"{class_name}({as_dict!r}{encoding_str})"313+ as_list = self.items()314+ return f"{class_name}({as_list!r}{encoding_str})"315 316 317 class Request:318 def __init__(106 unmodified lines425 content, depending on the Content-Encoding used in the response.426 """427 if not hasattr(self, "_decoder"):428 decoders = [] # type: typing.List[Decoder]354- value = self.headers.get("content-encoding", "identity")355- for part in value.split(","):356- part = part.strip().lower()357- decoder_cls = SUPPORTED_DECODERS[part]429+ values = self.headers.getlist("content-encoding", ["identity"])430+ for value in values:431+ value = value.strip().lower()432+ decoder_cls = SUPPORTED_DECODERS[value]433 decoders.append(decoder_cls())434 435 if len(decoders) == 1:436 self._decoder = decoders[0]66 unmodified linesmodified:httpcore/utils.py+4 added-4 removed
52 unmodified lines53 # properly quoted so they do not cause issues elsewhere.54 return quote(uri, safe=safe_without_percent)55 56 57-def normalize_header_key(value: typing.AnyStr) -> bytes:57+def normalize_header_key(value: typing.AnyStr, encoding: str = None) -> bytes:58 """59 Coerce str/bytes into a strictly byte-wise HTTP header key.60 """61 if isinstance(value, bytes):62 return value.lower()63- return value.encode("latin-1").lower()63+ return value.encode(encoding or "ascii").lower()64 65 66-def normalize_header_value(value: typing.AnyStr) -> bytes:66+def normalize_header_value(value: typing.AnyStr, encoding: str = None) -> bytes:67 """68 Coerce str/bytes into a strictly byte-wise HTTP header value.69 """70 if isinstance(value, bytes):71 return value72- return value.encode("latin-1")72+ return value.encode(encoding or "ascii")73 74 75 def get_reason_phrase(status_code: int) -> str:76 """6 unmodified linesadded:tests/dispatch/test_connection_pools.py+126 added
1+import pytest2+3+import httpcore4+5+6+@pytest.mark.asyncio7+async def test_keepalive_connections(server):8+ """9+ Connections should default to staying in a keep-alive state.10+ """11+ async with httpcore.ConnectionPool() as http:12+ response = await http.request("GET", "http://127.0.0.1:8000/")13+ assert len(http.active_connections) == 014+ assert len(http.keepalive_connections) == 115+16+ response = await http.request("GET", "http://127.0.0.1:8000/")17+ assert len(http.active_connections) == 018+ assert len(http.keepalive_connections) == 119+20+21+@pytest.mark.asyncio22+async def test_differing_connection_keys(server):23+ """24+ Connnections to differing connection keys should result in multiple connections.25+ """26+ async with httpcore.ConnectionPool() as http:27+ response = await http.request("GET", "http://127.0.0.1:8000/")28+ assert len(http.active_connections) == 029+ assert len(http.keepalive_connections) == 130+31+ response = await http.request("GET", "http://localhost:8000/")32+ assert len(http.active_connections) == 033+ assert len(http.keepalive_connections) == 234+35+36+@pytest.mark.asyncio37+async def test_soft_limit(server):38+ """39+ The soft_limit config should limit the maximum number of keep-alive connections.40+ """41+ limits = httpcore.PoolLimits(soft_limit=1)42+43+ async with httpcore.ConnectionPool(limits=limits) as http:44+ response = await http.request("GET", "http://127.0.0.1:8000/")45+ assert len(http.active_connections) == 046+ assert len(http.keepalive_connections) == 147+48+ response = await http.request("GET", "http://localhost:8000/")49+ assert len(http.active_connections) == 050+ assert len(http.keepalive_connections) == 151+52+53+@pytest.mark.asyncio54+async def test_streaming_response_holds_connection(server):55+ """56+ A streaming request should hold the connection open until the response is read.57+ """58+ async with httpcore.ConnectionPool() as http:59+ response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)60+ assert len(http.active_connections) == 161+ assert len(http.keepalive_connections) == 062+63+ await response.read()64+65+ assert len(http.active_connections) == 066+ assert len(http.keepalive_connections) == 167+68+69+@pytest.mark.asyncio70+async def test_multiple_concurrent_connections(server):71+ """72+ Multiple conncurrent requests should open multiple conncurrent connections.73+ """74+ async with httpcore.ConnectionPool() as http:75+ response_a = await http.request("GET", "http://127.0.0.1:8000/", stream=True)76+ assert len(http.active_connections) == 177+ assert len(http.keepalive_connections) == 078+79+ response_b = await http.request("GET", "http://127.0.0.1:8000/", stream=True)80+ assert len(http.active_connections) == 281+ assert len(http.keepalive_connections) == 082+83+ await response_b.read()84+ assert len(http.active_connections) == 185+ assert len(http.keepalive_connections) == 186+87+ await response_a.read()88+ assert len(http.active_connections) == 089+ assert len(http.keepalive_connections) == 290+91+92+@pytest.mark.asyncio93+async def test_close_connections(server):94+ """95+ Using a `Connection: close` header should close the connection.96+ """97+ headers = [(b"connection", b"close")]98+ async with httpcore.ConnectionPool() as http:99+ response = await http.request("GET", "http://127.0.0.1:8000/", headers=headers)100+ assert len(http.active_connections) == 0101+ assert len(http.keepalive_connections) == 0102+103+104+@pytest.mark.asyncio105+async def test_standard_response_close(server):106+ """107+ A standard close should keep the connection open.108+ """109+ async with httpcore.ConnectionPool() as http:110+ response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)111+ await response.read()112+ await response.close()113+ assert len(http.active_connections) == 0114+ assert len(http.keepalive_connections) == 1115+116+117+@pytest.mark.asyncio118+async def test_premature_response_close(server):119+ """120+ A premature close should close the connection.121+ """122+ async with httpcore.ConnectionPool() as http:123+ response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)124+ await response.close()125+ assert len(http.active_connections) == 0126+ assert len(http.keepalive_connections) == 0added:tests/dispatch/test_connections.py+20 added
1+import pytest2+3+import httpcore4+5+6+@pytest.mark.asyncio7+async def test_get(server):8+ http = httpcore.HTTPConnection(origin="http://127.0.0.1:8000/")9+ response = await http.request("GET", "http://127.0.0.1:8000/")10+ assert response.status_code == 20011+ assert response.body == b"Hello, world!"12+13+14+@pytest.mark.asyncio15+async def test_post(server):16+ http = httpcore.HTTPConnection(origin="http://127.0.0.1:8000/")17+ response = await http.request(18+ "POST", "http://127.0.0.1:8000/", body=b"Hello, world!"19+ )20+ assert response.status_code == 200added:tests/dispatch/test_http2.py+116 added
1+import json2+3+import h2.config4+import h2.connection5+import h2.events6+import pytest7+8+import httpcore9+10+11+class MockServer(httpcore.BaseReader, httpcore.BaseWriter):12+ """13+ This class exposes Reader and Writer style interfaces14+ """15+16+ def __init__(self):17+ config = h2.config.H2Configuration(client_side=False)18+ self.conn = h2.connection.H2Connection(config=config)19+ self.buffer = b""20+ self.requests = {}21+22+ # BaseReader interface23+24+ async def read(self, n, timeout) -> bytes:25+ send, self.buffer = self.buffer[:n], self.buffer[n:]26+ return send27+28+ # BaseWriter interface29+30+ def write_no_block(self, data: bytes) -> None:31+ events = self.conn.receive_data(data)32+ self.buffer += self.conn.data_to_send()33+ for event in events:34+ if isinstance(event, h2.events.RequestReceived):35+ self.request_received(event.headers, event.stream_id)36+ elif isinstance(event, h2.events.DataReceived):37+ self.receive_data(event.data, event.stream_id)38+ elif isinstance(event, h2.events.StreamEnded):39+ self.stream_complete(event.stream_id)40+41+ async def write(self, data: bytes, timeout) -> None:42+ self.write_no_block(data)43+44+ async def close(self) -> None:45+ pass46+47+ # Server implementation48+49+ def request_received(self, headers, stream_id):50+ if stream_id not in self.requests:51+ self.requests[stream_id] = []52+ self.requests[stream_id].append({"headers": headers, "data": b""})53+54+ def receive_data(self, data, stream_id):55+ self.requests[stream_id][-1]["data"] += data56+57+ def stream_complete(self, stream_id):58+ request = self.requests[stream_id].pop(0)59+ if not self.requests[stream_id]:60+ del self.requests[stream_id]61+62+ request_headers = dict(request["headers"])63+ request_data = request["data"]64+65+ response_body = json.dumps(66+ {67+ "method": request_headers[b":method"].decode(),68+ "path": request_headers[b":path"].decode(),69+ "body": request_data.decode(),70+ }71+ ).encode()72+73+ response_headers = ((b":status", b"200"),)74+ self.conn.send_headers(stream_id, response_headers)75+ self.conn.send_data(stream_id, response_body, end_stream=True)76+ self.buffer += self.conn.data_to_send()77+78+79+@pytest.mark.asyncio80+async def test_http2_get_request():81+ server = MockServer()82+ async with httpcore.HTTP2Connection(reader=server, writer=server) as conn:83+ response = await conn.request("GET", "http://example.org")84+ assert response.status_code == 20085+ assert json.loads(response.body) == {"method": "GET", "path": "/", "body": ""}86+87+88+@pytest.mark.asyncio89+async def test_http2_post_request():90+ server = MockServer()91+ async with httpcore.HTTP2Connection(reader=server, writer=server) as conn:92+ response = await conn.request("POST", "http://example.org", body=b"<data>")93+ assert response.status_code == 20094+ assert json.loads(response.body) == {95+ "method": "POST",96+ "path": "/",97+ "body": "<data>",98+ }99+100+101+@pytest.mark.asyncio102+async def test_http2_multiple_requests():103+ server = MockServer()104+ async with httpcore.HTTP2Connection(reader=server, writer=server) as conn:105+ response_1 = await conn.request("GET", "http://example.org/1")106+ response_2 = await conn.request("GET", "http://example.org/2")107+ response_3 = await conn.request("GET", "http://example.org/3")108+109+ assert response_1.status_code == 200110+ assert json.loads(response_1.body) == {"method": "GET", "path": "/1", "body": ""}111+112+ assert response_2.status_code == 200113+ assert json.loads(response_2.body) == {"method": "GET", "path": "/2", "body": ""}114+115+ assert response_3.status_code == 200116+ assert json.loads(response_3.body) == {"method": "GET", "path": "/3", "body": ""}added:tests/models/test_headers.py+154 added
1+import httpcore2+3+4+def test_headers():5+ h = httpcore.Headers([("a", "123"), ("a", "456"), ("b", "789")])6+ assert "a" in h7+ assert "A" in h8+ assert "b" in h9+ assert "B" in h10+ assert "c" not in h11+ assert h["a"] == "123, 456"12+ assert h.get("a") == "123, 456"13+ assert h.get("nope", default=None) is None14+ assert h.getlist("a") == ["123", "456"]15+ assert h.keys() == ["a", "a", "b"]16+ assert h.values() == ["123", "456", "789"]17+ assert h.items() == [("a", "123"), ("a", "456"), ("b", "789")]18+ assert list(h) == ["a", "a", "b"]19+ assert dict(h) == {"a": "123, 456", "b": "789"}20+ assert repr(h) == "Headers([('a', '123'), ('a', '456'), ('b', '789')])"21+ assert h == httpcore.Headers([("a", "123"), ("b", "789"), ("a", "456")])22+ assert h != [("a", "123"), ("A", "456"), ("b", "789")]23+24+ h = httpcore.Headers({"a": "123", "b": "789"})25+ assert h["A"] == "123"26+ assert h["B"] == "789"27+ assert h.raw == [(b"a", b"123"), (b"b", b"789")]28+ assert repr(h) == "Headers({'a': '123', 'b': '789'})"29+30+31+def test_header_mutations():32+ h = httpcore.Headers()33+ assert dict(h) == {}34+ h["a"] = "1"35+ assert dict(h) == {"a": "1"}36+ h["a"] = "2"37+ assert dict(h) == {"a": "2"}38+ h.setdefault("a", "3")39+ assert dict(h) == {"a": "2"}40+ h.setdefault("b", "4")41+ assert dict(h) == {"a": "2", "b": "4"}42+ del h["a"]43+ assert dict(h) == {"b": "4"}44+ assert h.raw == [(b"b", b"4")]45+46+47+def test_copy_headers():48+ headers = httpcore.Headers({"custom": "example"})49+ headers_copy = httpcore.Headers(headers)50+ assert headers == headers_copy51+52+53+def test_headers_insert_retains_ordering():54+ headers = httpcore.Headers({"a": "a", "b": "b", "c": "c"})55+ headers["b"] = "123"56+ assert list(headers.values()) == ["a", "123", "c"]57+58+59+def test_headers_insert_appends_if_new():60+ headers = httpcore.Headers({"a": "a", "b": "b", "c": "c"})61+ headers["d"] = "123"62+ assert list(headers.values()) == ["a", "b", "c", "123"]63+64+65+def test_headers_insert_removes_all_existing():66+ headers = httpcore.Headers([("a", "123"), ("a", "456")])67+ headers["a"] = "789"68+ assert dict(headers) == {"a": "789"}69+70+71+def test_headers_delete_removes_all_existing():72+ headers = httpcore.Headers([("a", "123"), ("a", "456")])73+ del headers["a"]74+ assert dict(headers) == {}75+76+77+def test_headers_dict_repr():78+ """79+ Headers should display with a dict repr by default.80+ """81+ headers = httpcore.Headers({"custom": "example"})82+ assert repr(headers) == "Headers({'custom': 'example'})"83+84+85+def test_headers_encoding_in_repr():86+ """87+ Headers should display an encoding in the repr if required.88+ """89+ headers = httpcore.Headers({b"custom": "example ☃".encode("utf-8")})90+ assert repr(headers) == "Headers({'custom': 'example ☃'}, encoding='utf-8')"91+92+93+def test_headers_list_repr():94+ """95+ Headers should display with a list repr if they include multiple identical keys.96+ """97+ headers = httpcore.Headers([("custom", "example 1"), ("custom", "example 2")])98+ assert (99+ repr(headers) == "Headers([('custom', 'example 1'), ('custom', 'example 2')])"100+ )101+102+103+def test_headers_decode_ascii():104+ """105+ Headers should decode as ascii by default.106+ """107+ raw_headers = [(b"Custom", b"Example")]108+ headers = httpcore.Headers(raw_headers)109+ assert dict(headers) == {"custom": "Example"}110+ assert headers.encoding == "ascii"111+112+113+def test_headers_decode_utf_8():114+ """115+ Headers containing non-ascii codepoints should default to decoding as utf-8.116+ """117+ raw_headers = [(b"Custom", "Code point: ☃".encode("utf-8"))]118+ headers = httpcore.Headers(raw_headers)119+ assert dict(headers) == {"custom": "Code point: ☃"}120+ assert headers.encoding == "utf-8"121+122+123+def test_headers_decode_iso_8859_1():124+ """125+ Headers containing non-UTF-8 codepoints should default to decoding as iso-8859-1.126+ """127+ raw_headers = [(b"Custom", "Code point: ÿ".encode("iso-8859-1"))]128+ headers = httpcore.Headers(raw_headers)129+ assert dict(headers) == {"custom": "Code point: ÿ"}130+ assert headers.encoding == "iso-8859-1"131+132+133+def test_headers_decode_explicit_encoding():134+ """135+ An explicit encoding may be set on headers in order to force a136+ particular decoding.137+ """138+ raw_headers = [(b"Custom", "Code point: ☃".encode("utf-8"))]139+ headers = httpcore.Headers(raw_headers)140+ headers.encoding = "iso-8859-1"141+ print(headers)142+ assert dict(headers) == {"custom": "Code point: â\x98\x83"}143+ assert headers.encoding == "iso-8859-1"144+145+146+def test_multiple_headers():147+ """148+ Most headers should split by commas for `getlist`, except 'Set-Cookie'.149+ """150+ h = httpcore.Headers([('set-cookie', 'a, b'), ('set-cookie', 'c')])151+ h.getlist('Set-Cookie') == ['a, b', 'b']152+153+ h = httpcore.Headers([('vary', 'a, b'), ('vary', 'c')])154+ h.getlist('Vary') == ['a', 'b', 'c']added:tests/models/test_requests.py+101 added
1+import pytest2+3+import httpcore4+5+6+def test_host_header():7+ request = httpcore.Request("GET", "http://example.org")8+ request.prepare()9+ assert request.headers == httpcore.Headers(10+ [(b"host", b"example.org"), (b"accept-encoding", b"deflate, gzip, br")]11+ )12+13+14+def test_content_length_header():15+ request = httpcore.Request("POST", "http://example.org", body=b"test 123")16+ request.prepare()17+ assert request.headers == httpcore.Headers(18+ [19+ (b"host", b"example.org"),20+ (b"content-length", b"8"),21+ (b"accept-encoding", b"deflate, gzip, br"),22+ ]23+ )24+25+26+def test_transfer_encoding_header():27+ async def streaming_body(data):28+ yield data # pragma: nocover29+30+ body = streaming_body(b"test 123")31+32+ request = httpcore.Request("POST", "http://example.org", body=body)33+ request.prepare()34+ assert request.headers == httpcore.Headers(35+ [36+ (b"host", b"example.org"),37+ (b"transfer-encoding", b"chunked"),38+ (b"accept-encoding", b"deflate, gzip, br"),39+ ]40+ )41+42+43+def test_override_host_header():44+ headers = [(b"host", b"1.2.3.4:80")]45+46+ request = httpcore.Request("GET", "http://example.org", headers=headers)47+ request.prepare()48+ assert request.headers == httpcore.Headers(49+ [(b"accept-encoding", b"deflate, gzip, br"), (b"host", b"1.2.3.4:80")]50+ )51+52+53+def test_override_accept_encoding_header():54+ headers = [(b"accept-encoding", b"identity")]55+56+ request = httpcore.Request("GET", "http://example.org", headers=headers)57+ request.prepare()58+ assert request.headers == httpcore.Headers(59+ [(b"host", b"example.org"), (b"accept-encoding", b"identity")]60+ )61+62+63+def test_override_content_length_header():64+ async def streaming_body(data):65+ yield data # pragma: nocover66+67+ body = streaming_body(b"test 123")68+ headers = [(b"content-length", b"8")]69+70+ request = httpcore.Request("POST", "http://example.org", body=body, headers=headers)71+ request.prepare()72+ assert request.headers == httpcore.Headers(73+ [74+ (b"host", b"example.org"),75+ (b"accept-encoding", b"deflate, gzip, br"),76+ (b"content-length", b"8"),77+ ]78+ )79+80+81+def test_url():82+ request = httpcore.Request("GET", "http://example.org")83+ assert request.url.scheme == "http"84+ assert request.url.port == 8085+ assert request.url.full_path == "/"86+87+ request = httpcore.Request("GET", "https://example.org/abc?foo=bar")88+ assert request.url.scheme == "https"89+ assert request.url.port == 44390+ assert request.url.full_path == "/abc?foo=bar"91+92+93+def test_invalid_urls():94+ with pytest.raises(ValueError):95+ httpcore.Request("GET", "example.org")96+97+ with pytest.raises(ValueError):98+ httpcore.Request("GET", "invalid://example.org")99+100+ with pytest.raises(ValueError):101+ httpcore.Request("GET", "http:///foo")added:tests/models/test_responses.py+74 added
1+import pytest2+3+import httpcore4+5+6+async def streaming_body():7+ yield b"Hello, "8+ yield b"world!"9+10+11+def test_response():12+ response = httpcore.Response(200, body=b"Hello, world!")13+ assert response.status_code == 20014+ assert response.reason_phrase == "OK"15+ assert response.body == b"Hello, world!"16+ assert response.is_closed17+18+19+@pytest.mark.asyncio20+async def test_read_response():21+ response = httpcore.Response(200, body=b"Hello, world!")22+23+ assert response.status_code == 20024+ assert response.body == b"Hello, world!"25+ assert response.is_closed26+27+ body = await response.read()28+29+ assert body == b"Hello, world!"30+ assert response.body == b"Hello, world!"31+ assert response.is_closed32+33+34+@pytest.mark.asyncio35+async def test_streaming_response():36+ response = httpcore.Response(200, body=streaming_body())37+38+ assert response.status_code == 20039+ assert not hasattr(response, "body")40+ assert not response.is_closed41+42+ body = await response.read()43+44+ assert body == b"Hello, world!"45+ assert response.body == b"Hello, world!"46+ assert response.is_closed47+48+49+@pytest.mark.asyncio50+async def test_cannot_read_after_stream_consumed():51+ response = httpcore.Response(200, body=streaming_body())52+53+ body = b""54+ async for part in response.stream():55+ body += part56+57+ with pytest.raises(httpcore.StreamConsumed):58+ await response.read()59+60+61+@pytest.mark.asyncio62+async def test_cannot_read_after_response_closed():63+ response = httpcore.Response(200, body=streaming_body())64+65+ await response.close()66+67+ with pytest.raises(httpcore.ResponseClosed):68+ await response.read()69+70+71+def test_unknown_status_code():72+ response = httpcore.Response(600)73+ assert response.status_code == 60074+ assert response.reason_phrase == ""deleted:tests/test_api.py-43 removed
1-import pytest2-3-import httpcore4-5-6-@pytest.mark.asyncio7-async def test_get(server):8- url = "http://127.0.0.1:8000/"9- async with httpcore.Client() as client:10- response = await client.get(url)11- assert response.status_code == 20012- assert response.body == b"Hello, world!"13-14-15-@pytest.mark.asyncio16-async def test_post(server):17- url = "http://127.0.0.1:8000/"18- async with httpcore.Client() as client:19- response = await client.post(url, body=b"Hello, world!")20- assert response.status_code == 20021-22-23-@pytest.mark.asyncio24-async def test_stream_response(server):25- async with httpcore.Client() as client:26- response = await client.request("GET", "http://127.0.0.1:8000/", stream=True)27- assert response.status_code == 20028- assert not hasattr(response, "body")29- body = await response.read()30- assert body == b"Hello, world!"31-32-33-@pytest.mark.asyncio34-async def test_stream_request(server):35- async def hello_world():36- yield b"Hello, "37- yield b"world!"38-39- async with httpcore.Client() as client:40- response = await client.request(41- "POST", "http://127.0.0.1:8000/", body=hello_world()42- )43- assert response.status_code == 200added:tests/test_client.py+43 added
1+import pytest2+3+import httpcore4+5+6+@pytest.mark.asyncio7+async def test_get(server):8+ url = "http://127.0.0.1:8000/"9+ async with httpcore.Client() as client:10+ response = await client.get(url)11+ assert response.status_code == 20012+ assert response.body == b"Hello, world!"13+14+15+@pytest.mark.asyncio16+async def test_post(server):17+ url = "http://127.0.0.1:8000/"18+ async with httpcore.Client() as client:19+ response = await client.post(url, body=b"Hello, world!")20+ assert response.status_code == 20021+22+23+@pytest.mark.asyncio24+async def test_stream_response(server):25+ async with httpcore.Client() as client:26+ response = await client.request("GET", "http://127.0.0.1:8000/", stream=True)27+ assert response.status_code == 20028+ assert not hasattr(response, "body")29+ body = await response.read()30+ assert body == b"Hello, world!"31+32+33+@pytest.mark.asyncio34+async def test_stream_request(server):35+ async def hello_world():36+ yield b"Hello, "37+ yield b"world!"38+39+ async with httpcore.Client() as client:40+ response = await client.request(41+ "POST", "http://127.0.0.1:8000/", body=hello_world()42+ )43+ assert response.status_code == 200deleted:tests/test_connection_pools.py-126 removed
1-import pytest2-3-import httpcore4-5-6-@pytest.mark.asyncio7-async def test_keepalive_connections(server):8- """9- Connections should default to staying in a keep-alive state.10- """11- async with httpcore.ConnectionPool() as http:12- response = await http.request("GET", "http://127.0.0.1:8000/")13- assert len(http.active_connections) == 014- assert len(http.keepalive_connections) == 115-16- response = await http.request("GET", "http://127.0.0.1:8000/")17- assert len(http.active_connections) == 018- assert len(http.keepalive_connections) == 119-20-21-@pytest.mark.asyncio22-async def test_differing_connection_keys(server):23- """24- Connnections to differing connection keys should result in multiple connections.25- """26- async with httpcore.ConnectionPool() as http:27- response = await http.request("GET", "http://127.0.0.1:8000/")28- assert len(http.active_connections) == 029- assert len(http.keepalive_connections) == 130-31- response = await http.request("GET", "http://localhost:8000/")32- assert len(http.active_connections) == 033- assert len(http.keepalive_connections) == 234-35-36-@pytest.mark.asyncio37-async def test_soft_limit(server):38- """39- The soft_limit config should limit the maximum number of keep-alive connections.40- """41- limits = httpcore.PoolLimits(soft_limit=1)42-43- async with httpcore.ConnectionPool(limits=limits) as http:44- response = await http.request("GET", "http://127.0.0.1:8000/")45- assert len(http.active_connections) == 046- assert len(http.keepalive_connections) == 147-48- response = await http.request("GET", "http://localhost:8000/")49- assert len(http.active_connections) == 050- assert len(http.keepalive_connections) == 151-52-53-@pytest.mark.asyncio54-async def test_streaming_response_holds_connection(server):55- """56- A streaming request should hold the connection open until the response is read.57- """58- async with httpcore.ConnectionPool() as http:59- response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)60- assert len(http.active_connections) == 161- assert len(http.keepalive_connections) == 062-63- await response.read()64-65- assert len(http.active_connections) == 066- assert len(http.keepalive_connections) == 167-68-69-@pytest.mark.asyncio70-async def test_multiple_concurrent_connections(server):71- """72- Multiple conncurrent requests should open multiple conncurrent connections.73- """74- async with httpcore.ConnectionPool() as http:75- response_a = await http.request("GET", "http://127.0.0.1:8000/", stream=True)76- assert len(http.active_connections) == 177- assert len(http.keepalive_connections) == 078-79- response_b = await http.request("GET", "http://127.0.0.1:8000/", stream=True)80- assert len(http.active_connections) == 281- assert len(http.keepalive_connections) == 082-83- await response_b.read()84- assert len(http.active_connections) == 185- assert len(http.keepalive_connections) == 186-87- await response_a.read()88- assert len(http.active_connections) == 089- assert len(http.keepalive_connections) == 290-91-92-@pytest.mark.asyncio93-async def test_close_connections(server):94- """95- Using a `Connection: close` header should close the connection.96- """97- headers = [(b"connection", b"close")]98- async with httpcore.ConnectionPool() as http:99- response = await http.request("GET", "http://127.0.0.1:8000/", headers=headers)100- assert len(http.active_connections) == 0101- assert len(http.keepalive_connections) == 0102-103-104-@pytest.mark.asyncio105-async def test_standard_response_close(server):106- """107- A standard close should keep the connection open.108- """109- async with httpcore.ConnectionPool() as http:110- response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)111- await response.read()112- await response.close()113- assert len(http.active_connections) == 0114- assert len(http.keepalive_connections) == 1115-116-117-@pytest.mark.asyncio118-async def test_premature_response_close(server):119- """120- A premature close should close the connection.121- """122- async with httpcore.ConnectionPool() as http:123- response = await http.request("GET", "http://127.0.0.1:8000/", stream=True)124- await response.close()125- assert len(http.active_connections) == 0126- assert len(http.keepalive_connections) == 0deleted:tests/test_connections.py-20 removed
1-import pytest2-3-import httpcore4-5-6-@pytest.mark.asyncio7-async def test_get(server):8- http = httpcore.HTTPConnection(origin="http://127.0.0.1:8000/")9- response = await http.request("GET", "http://127.0.0.1:8000/")10- assert response.status_code == 20011- assert response.body == b"Hello, world!"12-13-14-@pytest.mark.asyncio15-async def test_post(server):16- http = httpcore.HTTPConnection(origin="http://127.0.0.1:8000/")17- response = await http.request(18- "POST", "http://127.0.0.1:8000/", body=b"Hello, world!"19- )20- assert response.status_code == 200added:tests/test_decoders.py+88 added
1+import zlib2+3+import brotli4+import pytest5+6+import httpcore7+8+9+def test_deflate():10+ body = b"test 123"11+ compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)12+ compressed_body = compressor.compress(body) + compressor.flush()13+14+ headers = [(b"Content-Encoding", b"deflate")]15+ response = httpcore.Response(200, headers=headers, body=compressed_body)16+ assert response.body == body17+18+19+def test_gzip():20+ body = b"test 123"21+ compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)22+ compressed_body = compressor.compress(body) + compressor.flush()23+24+ headers = [(b"Content-Encoding", b"gzip")]25+ response = httpcore.Response(200, headers=headers, body=compressed_body)26+ assert response.body == body27+28+29+def test_brotli():30+ body = b"test 123"31+ compressed_body = brotli.compress(body)32+33+ headers = [(b"Content-Encoding", b"br")]34+ response = httpcore.Response(200, headers=headers, body=compressed_body)35+ assert response.body == body36+37+38+def test_multi():39+ body = b"test 123"40+41+ deflate_compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)42+ compressed_body = deflate_compressor.compress(body) + deflate_compressor.flush()43+44+ gzip_compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)45+ compressed_body = (46+ gzip_compressor.compress(compressed_body) + gzip_compressor.flush()47+ )48+49+ headers = [(b"Content-Encoding", b"deflate, gzip")]50+ response = httpcore.Response(200, headers=headers, body=compressed_body)51+ assert response.body == body52+53+54+def test_multi_with_identity():55+ body = b"test 123"56+ compressed_body = brotli.compress(body)57+58+ headers = [(b"Content-Encoding", b"br, identity")]59+ response = httpcore.Response(200, headers=headers, body=compressed_body)60+ assert response.body == body61+62+ headers = [(b"Content-Encoding", b"identity, br")]63+ response = httpcore.Response(200, headers=headers, body=compressed_body)64+ assert response.body == body65+66+67+@pytest.mark.asyncio68+async def test_streaming():69+ body = b"test 123"70+ compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)71+72+ async def compress(body):73+ yield compressor.compress(body)74+ yield compressor.flush()75+76+ headers = [(b"Content-Encoding", b"gzip")]77+ response = httpcore.Response(200, headers=headers, body=compress(body))78+ assert not hasattr(response, "body")79+ assert await response.read() == body80+81+82+@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))83+def test_decoding_errors(header_value):84+ headers = [(b"Content-Encoding", header_value)]85+ body = b"test 123"86+ compressed_body = brotli.compress(body)[3:]87+ with pytest.raises(httpcore.exceptions.DecodingError):88+ response = httpcore.Response(200, headers=headers, body=compressed_body)deleted:tests/test_decoding.py-88 removed
1-import zlib2-3-import brotli4-import pytest5-6-import httpcore7-8-9-def test_deflate():10- body = b"test 123"11- compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)12- compressed_body = compressor.compress(body) + compressor.flush()13-14- headers = [(b"Content-Encoding", b"deflate")]15- response = httpcore.Response(200, headers=headers, body=compressed_body)16- assert response.body == body17-18-19-def test_gzip():20- body = b"test 123"21- compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)22- compressed_body = compressor.compress(body) + compressor.flush()23-24- headers = [(b"Content-Encoding", b"gzip")]25- response = httpcore.Response(200, headers=headers, body=compressed_body)26- assert response.body == body27-28-29-def test_brotli():30- body = b"test 123"31- compressed_body = brotli.compress(body)32-33- headers = [(b"Content-Encoding", b"br")]34- response = httpcore.Response(200, headers=headers, body=compressed_body)35- assert response.body == body36-37-38-def test_multi():39- body = b"test 123"40-41- deflate_compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)42- compressed_body = deflate_compressor.compress(body) + deflate_compressor.flush()43-44- gzip_compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)45- compressed_body = (46- gzip_compressor.compress(compressed_body) + gzip_compressor.flush()47- )48-49- headers = [(b"Content-Encoding", b"deflate, gzip")]50- response = httpcore.Response(200, headers=headers, body=compressed_body)51- assert response.body == body52-53-54-def test_multi_with_identity():55- body = b"test 123"56- compressed_body = brotli.compress(body)57-58- headers = [(b"Content-Encoding", b"br, identity")]59- response = httpcore.Response(200, headers=headers, body=compressed_body)60- assert response.body == body61-62- headers = [(b"Content-Encoding", b"identity, br")]63- response = httpcore.Response(200, headers=headers, body=compressed_body)64- assert response.body == body65-66-67-@pytest.mark.asyncio68-async def test_streaming():69- body = b"test 123"70- compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)71-72- async def compress(body):73- yield compressor.compress(body)74- yield compressor.flush()75-76- headers = [(b"Content-Encoding", b"gzip")]77- response = httpcore.Response(200, headers=headers, body=compress(body))78- assert not hasattr(response, "body")79- assert await response.read() == body80-81-82-@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))83-def test_decoding_errors(header_value):84- headers = [(b"Content-Encoding", header_value)]85- body = b"test 123"86- compressed_body = brotli.compress(body)[3:]87- with pytest.raises(httpcore.exceptions.DecodingError):88- response = httpcore.Response(200, headers=headers, body=compressed_body)deleted:tests/test_http2.py-116 removed
1-import json2-3-import h2.config4-import h2.connection5-import h2.events6-import pytest7-8-import httpcore9-10-11-class MockServer(httpcore.BaseReader, httpcore.BaseWriter):12- """13- This class exposes Reader and Writer style interfaces14- """15-16- def __init__(self):17- config = h2.config.H2Configuration(client_side=False)18- self.conn = h2.connection.H2Connection(config=config)19- self.buffer = b""20- self.requests = {}21-22- # BaseReader interface23-24- async def read(self, n, timeout) -> bytes:25- send, self.buffer = self.buffer[:n], self.buffer[n:]26- return send27-28- # BaseWriter interface29-30- def write_no_block(self, data: bytes) -> None:31- events = self.conn.receive_data(data)32- self.buffer += self.conn.data_to_send()33- for event in events:34- if isinstance(event, h2.events.RequestReceived):35- self.request_received(event.headers, event.stream_id)36- elif isinstance(event, h2.events.DataReceived):37- self.receive_data(event.data, event.stream_id)38- elif isinstance(event, h2.events.StreamEnded):39- self.stream_complete(event.stream_id)40-41- async def write(self, data: bytes, timeout) -> None:42- self.write_no_block(data)43-44- async def close(self) -> None:45- pass46-47- # Server implementation48-49- def request_received(self, headers, stream_id):50- if stream_id not in self.requests:51- self.requests[stream_id] = []52- self.requests[stream_id].append({"headers": headers, "data": b""})53-54- def receive_data(self, data, stream_id):55- self.requests[stream_id][-1]["data"] += data56-57- def stream_complete(self, stream_id):58- request = self.requests[stream_id].pop(0)59- if not self.requests[stream_id]:60- del self.requests[stream_id]61-62- request_headers = dict(request["headers"])63- request_data = request["data"]64-65- response_body = json.dumps(66- {67- "method": request_headers[b":method"].decode(),68- "path": request_headers[b":path"].decode(),69- "body": request_data.decode(),70- }71- ).encode()72-73- response_headers = ((b":status", b"200"),)74- self.conn.send_headers(stream_id, response_headers)75- self.conn.send_data(stream_id, response_body, end_stream=True)76- self.buffer += self.conn.data_to_send()77-78-79-@pytest.mark.asyncio80-async def test_http2_get_request():81- server = MockServer()82- async with httpcore.HTTP2Connection(reader=server, writer=server) as conn:83- response = await conn.request("GET", "http://example.org")84- assert response.status_code == 20085- assert json.loads(response.body) == {"method": "GET", "path": "/", "body": ""}86-87-88-@pytest.mark.asyncio89-async def test_http2_post_request():90- server = MockServer()91- async with httpcore.HTTP2Connection(reader=server, writer=server) as conn:92- response = await conn.request("POST", "http://example.org", body=b"<data>")93- assert response.status_code == 20094- assert json.loads(response.body) == {95- "method": "POST",96- "path": "/",97- "body": "<data>",98- }99-100-101-@pytest.mark.asyncio102-async def test_http2_multiple_requests():103- server = MockServer()104- async with httpcore.HTTP2Connection(reader=server, writer=server) as conn:105- response_1 = await conn.request("GET", "http://example.org/1")106- response_2 = await conn.request("GET", "http://example.org/2")107- response_3 = await conn.request("GET", "http://example.org/3")108-109- assert response_1.status_code == 200110- assert json.loads(response_1.body) == {"method": "GET", "path": "/1", "body": ""}111-112- assert response_2.status_code == 200113- assert json.loads(response_2.body) == {"method": "GET", "path": "/2", "body": ""}114-115- assert response_3.status_code == 200116- assert json.loads(response_3.body) == {"method": "GET", "path": "/3", "body": ""}deleted:tests/test_requests.py-101 removed
1-import pytest2-3-import httpcore4-5-6-def test_host_header():7- request = httpcore.Request("GET", "http://example.org")8- request.prepare()9- assert request.headers == httpcore.Headers(10- [(b"host", b"example.org"), (b"accept-encoding", b"deflate, gzip, br")]11- )12-13-14-def test_content_length_header():15- request = httpcore.Request("POST", "http://example.org", body=b"test 123")16- request.prepare()17- assert request.headers == httpcore.Headers(18- [19- (b"host", b"example.org"),20- (b"content-length", b"8"),21- (b"accept-encoding", b"deflate, gzip, br"),22- ]23- )24-25-26-def test_transfer_encoding_header():27- async def streaming_body(data):28- yield data # pragma: nocover29-30- body = streaming_body(b"test 123")31-32- request = httpcore.Request("POST", "http://example.org", body=body)33- request.prepare()34- assert request.headers == httpcore.Headers(35- [36- (b"host", b"example.org"),37- (b"transfer-encoding", b"chunked"),38- (b"accept-encoding", b"deflate, gzip, br"),39- ]40- )41-42-43-def test_override_host_header():44- headers = [(b"host", b"1.2.3.4:80")]45-46- request = httpcore.Request("GET", "http://example.org", headers=headers)47- request.prepare()48- assert request.headers == httpcore.Headers(49- [(b"accept-encoding", b"deflate, gzip, br"), (b"host", b"1.2.3.4:80")]50- )51-52-53-def test_override_accept_encoding_header():54- headers = [(b"accept-encoding", b"identity")]55-56- request = httpcore.Request("GET", "http://example.org", headers=headers)57- request.prepare()58- assert request.headers == httpcore.Headers(59- [(b"host", b"example.org"), (b"accept-encoding", b"identity")]60- )61-62-63-def test_override_content_length_header():64- async def streaming_body(data):65- yield data # pragma: nocover66-67- body = streaming_body(b"test 123")68- headers = [(b"content-length", b"8")]69-70- request = httpcore.Request("POST", "http://example.org", body=body, headers=headers)71- request.prepare()72- assert request.headers == httpcore.Headers(73- [74- (b"host", b"example.org"),75- (b"accept-encoding", b"deflate, gzip, br"),76- (b"content-length", b"8"),77- ]78- )79-80-81-def test_url():82- request = httpcore.Request("GET", "http://example.org")83- assert request.url.scheme == "http"84- assert request.url.port == 8085- assert request.url.full_path == "/"86-87- request = httpcore.Request("GET", "https://example.org/abc?foo=bar")88- assert request.url.scheme == "https"89- assert request.url.port == 44390- assert request.url.full_path == "/abc?foo=bar"91-92-93-def test_invalid_urls():94- with pytest.raises(ValueError):95- httpcore.Request("GET", "example.org")96-97- with pytest.raises(ValueError):98- httpcore.Request("GET", "invalid://example.org")99-100- with pytest.raises(ValueError):101- httpcore.Request("GET", "http:///foo")deleted:tests/test_responses.py-74 removed
1-import pytest2-3-import httpcore4-5-6-async def streaming_body():7- yield b"Hello, "8- yield b"world!"9-10-11-def test_response():12- response = httpcore.Response(200, body=b"Hello, world!")13- assert response.status_code == 20014- assert response.reason_phrase == "OK"15- assert response.body == b"Hello, world!"16- assert response.is_closed17-18-19-@pytest.mark.asyncio20-async def test_read_response():21- response = httpcore.Response(200, body=b"Hello, world!")22-23- assert response.status_code == 20024- assert response.body == b"Hello, world!"25- assert response.is_closed26-27- body = await response.read()28-29- assert body == b"Hello, world!"30- assert response.body == b"Hello, world!"31- assert response.is_closed32-33-34-@pytest.mark.asyncio35-async def test_streaming_response():36- response = httpcore.Response(200, body=streaming_body())37-38- assert response.status_code == 20039- assert not hasattr(response, "body")40- assert not response.is_closed41-42- body = await response.read()43-44- assert body == b"Hello, world!"45- assert response.body == b"Hello, world!"46- assert response.is_closed47-48-49-@pytest.mark.asyncio50-async def test_cannot_read_after_stream_consumed():51- response = httpcore.Response(200, body=streaming_body())52-53- body = b""54- async for part in response.stream():55- body += part56-57- with pytest.raises(httpcore.StreamConsumed):58- await response.read()59-60-61-@pytest.mark.asyncio62-async def test_cannot_read_after_response_closed():63- response = httpcore.Response(200, body=streaming_body())64-65- await response.close()66-67- with pytest.raises(httpcore.ResponseClosed):68- await response.read()69-70-71-def test_unknown_status_code():72- response = httpcore.Response(600)73- assert response.status_code == 60074- assert response.reason_phrase == ""