Skip to content
Myr

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

18 files+840 added−599 removed

modified:httpcore/exceptions.py+16 added-4 removed
1# Timeout exceptions...234class Timeout(Exception):5 """6 A base class for all timeouts.7 """
22 unmodified lines
30 Timeout while waiting to acquire a connection from the pool.31 """323334# HTTP exceptions...353637class ProtocolError(Exception):38 """39 Malformed HTTP.40 """414243# Redirect exceptions...444546class RedirectError(Exception):47 """48 Base class for HTTP redirect errors.49 """
17 unmodified lines
67 Infinite redirect loop.68 """697056class ProtocolError(Exception):57 """58 Malformed HTTP.59 """71# Response exceptions...727374class StreamConsumed(Exception):75 """
22 unmodified lines
modified:httpcore/models.py+98 added-23 removed
123 unmodified lines
124 """125 A case-insensitive multidict.126 """127128 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 = encoding144145 @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._encoding169170 @encoding.setter171 def encoding(self, value: str) -> None:172 self._encoding = value173174 @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._list181182 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]184185 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]187188 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 ]193194 def get(self, key: str, default: typing.Any = None) -> typing.Any:
1 unmodified line
196 return self[key]197 except KeyError:198 return default199165 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.203204 If there are header values that include commas, then we default to205 spliting them into multiple results, except for Set-Cookie.206207 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'212213 values = [214 item_value.decode(self.encoding)215 for item_key, item_value in self._list216 if item_key == get_header_key217 ]218219 if not values:220 return [] if default is None else default221222 if not split_commas:223 return values224225 split_values = []226 for value in values:227 split_values.extend([item.strip() for item in value.split(",")])228 return split_values229230 def __getitem__(self, key: str) -> str:174 get_header_key = key.lower().encode("latin-1")231 """232 Return a single header value.233234 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)238239 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))243244 if items:245 return ", ".join(items)246247 raise KeyError(key)248249 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)256257 found_indexes = []258 for idx, (item_key, item_value) in enumerate(self._list):259 if item_key == set_key:
11 unmodified lines
271 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)276277 pop_indexes = []278 for idx, (item_key, item_value) in enumerate(self._list):279 if item_key == del_key:
2 unmodified lines
282 for idx in reversed(pop_indexes):283 del self._list[idx]284285 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 False
10 unmodified lines
301 return sorted(self._list) == sorted(other._list)302303 def __repr__(self) -> str:304 class_name = self.__class__.__name__305306 encoding_str = ""307 if self.encoding != "ascii":308 encoding_str = f", encoding={self.encoding!r}"309310 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})"315316317class Request:318 def __init__(
106 unmodified lines
425 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())434435 if len(decoders) == 1:436 self._decoder = decoders[0]
66 unmodified lines
modified:httpcore/utils.py+4 added-4 removed
52 unmodified lines
53 # properly quoted so they do not cause issues elsewhere.54 return quote(uri, safe=safe_without_percent)555657def normalize_header_key(value: typing.AnyStr) -> bytes:57def 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()646566def normalize_header_value(value: typing.AnyStr) -> bytes:66def 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")737475def get_reason_phrase(status_code: int) -> str:76 """
6 unmodified lines
added:tests/dispatch/test_connection_pools.py+126 added
1import pytest23import httpcore456@pytest.mark.asyncio7async 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) == 11516 response = await http.request("GET", "http://127.0.0.1:8000/")17 assert len(http.active_connections) == 018 assert len(http.keepalive_connections) == 1192021@pytest.mark.asyncio22async 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) == 13031 response = await http.request("GET", "http://localhost:8000/")32 assert len(http.active_connections) == 033 assert len(http.keepalive_connections) == 2343536@pytest.mark.asyncio37async 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)4243 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) == 14748 response = await http.request("GET", "http://localhost:8000/")49 assert len(http.active_connections) == 050 assert len(http.keepalive_connections) == 1515253@pytest.mark.asyncio54async 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) == 06263 await response.read()6465 assert len(http.active_connections) == 066 assert len(http.keepalive_connections) == 1676869@pytest.mark.asyncio70async 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) == 07879 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) == 08283 await response_b.read()84 assert len(http.active_connections) == 185 assert len(http.keepalive_connections) == 18687 await response_a.read()88 assert len(http.active_connections) == 089 assert len(http.keepalive_connections) == 2909192@pytest.mark.asyncio93async 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) == 0102103104@pytest.mark.asyncio105async 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) == 1115116117@pytest.mark.asyncio118async 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) == 0
added:tests/dispatch/test_connections.py+20 added
1import pytest23import httpcore456@pytest.mark.asyncio7async 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!"121314@pytest.mark.asyncio15async 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 == 200
added:tests/dispatch/test_http2.py+116 added
1import json23import h2.config4import h2.connection5import h2.events6import pytest78import httpcore91011class MockServer(httpcore.BaseReader, httpcore.BaseWriter):12 """13 This class exposes Reader and Writer style interfaces14 """1516 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 = {}2122 # BaseReader interface2324 async def read(self, n, timeout) -> bytes:25 send, self.buffer = self.buffer[:n], self.buffer[n:]26 return send2728 # BaseWriter interface2930 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)4041 async def write(self, data: bytes, timeout) -> None:42 self.write_no_block(data)4344 async def close(self) -> None:45 pass4647 # Server implementation4849 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""})5354 def receive_data(self, data, stream_id):55 self.requests[stream_id][-1]["data"] += data5657 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]6162 request_headers = dict(request["headers"])63 request_data = request["data"]6465 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()7273 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()777879@pytest.mark.asyncio80async 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": ""}868788@pytest.mark.asyncio89async 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 }99100101@pytest.mark.asyncio102async 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")108109 assert response_1.status_code == 200110 assert json.loads(response_1.body) == {"method": "GET", "path": "/1", "body": ""}111112 assert response_2.status_code == 200113 assert json.loads(response_2.body) == {"method": "GET", "path": "/2", "body": ""}114115 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
1import httpcore234def 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")]2324 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'})"293031def 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")]454647def test_copy_headers():48 headers = httpcore.Headers({"custom": "example"})49 headers_copy = httpcore.Headers(headers)50 assert headers == headers_copy515253def 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"]575859def 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"]636465def test_headers_insert_removes_all_existing():66 headers = httpcore.Headers([("a", "123"), ("a", "456")])67 headers["a"] = "789"68 assert dict(headers) == {"a": "789"}697071def test_headers_delete_removes_all_existing():72 headers = httpcore.Headers([("a", "123"), ("a", "456")])73 del headers["a"]74 assert dict(headers) == {}757677def 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'})"838485def 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')"919293def 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 )101102103def 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"111112113def 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"121122123def 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"131132133def 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"144145146def 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']152153 h = httpcore.Headers([('vary', 'a, b'), ('vary', 'c')])154 h.getlist('Vary') == ['a', 'b', 'c']
added:tests/models/test_requests.py+101 added
1import pytest23import httpcore456def 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 )121314def 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 )242526def test_transfer_encoding_header():27 async def streaming_body(data):28 yield data # pragma: nocover2930 body = streaming_body(b"test 123")3132 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 )414243def test_override_host_header():44 headers = [(b"host", b"1.2.3.4:80")]4546 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 )515253def test_override_accept_encoding_header():54 headers = [(b"accept-encoding", b"identity")]5556 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 )616263def test_override_content_length_header():64 async def streaming_body(data):65 yield data # pragma: nocover6667 body = streaming_body(b"test 123")68 headers = [(b"content-length", b"8")]6970 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 )798081def 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 == "/"8687 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"919293def test_invalid_urls():94 with pytest.raises(ValueError):95 httpcore.Request("GET", "example.org")9697 with pytest.raises(ValueError):98 httpcore.Request("GET", "invalid://example.org")99100 with pytest.raises(ValueError):101 httpcore.Request("GET", "http:///foo")
added:tests/models/test_responses.py+74 added
1import pytest23import httpcore456async def streaming_body():7 yield b"Hello, "8 yield b"world!"91011def 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_closed171819@pytest.mark.asyncio20async def test_read_response():21 response = httpcore.Response(200, body=b"Hello, world!")2223 assert response.status_code == 20024 assert response.body == b"Hello, world!"25 assert response.is_closed2627 body = await response.read()2829 assert body == b"Hello, world!"30 assert response.body == b"Hello, world!"31 assert response.is_closed323334@pytest.mark.asyncio35async def test_streaming_response():36 response = httpcore.Response(200, body=streaming_body())3738 assert response.status_code == 20039 assert not hasattr(response, "body")40 assert not response.is_closed4142 body = await response.read()4344 assert body == b"Hello, world!"45 assert response.body == b"Hello, world!"46 assert response.is_closed474849@pytest.mark.asyncio50async def test_cannot_read_after_stream_consumed():51 response = httpcore.Response(200, body=streaming_body())5253 body = b""54 async for part in response.stream():55 body += part5657 with pytest.raises(httpcore.StreamConsumed):58 await response.read()596061@pytest.mark.asyncio62async def test_cannot_read_after_response_closed():63 response = httpcore.Response(200, body=streaming_body())6465 await response.close()6667 with pytest.raises(httpcore.ResponseClosed):68 await response.read()697071def 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
1import pytest23import httpcore456@pytest.mark.asyncio7async 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!"131415@pytest.mark.asyncio16async 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 == 200212223@pytest.mark.asyncio24async 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!"313233@pytest.mark.asyncio34async def test_stream_request(server):35 async def hello_world():36 yield b"Hello, "37 yield b"world!"3839 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 == 200
added:tests/test_client.py+43 added
1import pytest23import httpcore456@pytest.mark.asyncio7async 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!"131415@pytest.mark.asyncio16async 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 == 200212223@pytest.mark.asyncio24async 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!"313233@pytest.mark.asyncio34async def test_stream_request(server):35 async def hello_world():36 yield b"Hello, "37 yield b"world!"3839 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 == 200
deleted:tests/test_connection_pools.py-126 removed
1import pytest23import httpcore456@pytest.mark.asyncio7async 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) == 11516 response = await http.request("GET", "http://127.0.0.1:8000/")17 assert len(http.active_connections) == 018 assert len(http.keepalive_connections) == 1192021@pytest.mark.asyncio22async 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) == 13031 response = await http.request("GET", "http://localhost:8000/")32 assert len(http.active_connections) == 033 assert len(http.keepalive_connections) == 2343536@pytest.mark.asyncio37async 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)4243 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) == 14748 response = await http.request("GET", "http://localhost:8000/")49 assert len(http.active_connections) == 050 assert len(http.keepalive_connections) == 1515253@pytest.mark.asyncio54async 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) == 06263 await response.read()6465 assert len(http.active_connections) == 066 assert len(http.keepalive_connections) == 1676869@pytest.mark.asyncio70async 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) == 07879 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) == 08283 await response_b.read()84 assert len(http.active_connections) == 185 assert len(http.keepalive_connections) == 18687 await response_a.read()88 assert len(http.active_connections) == 089 assert len(http.keepalive_connections) == 2909192@pytest.mark.asyncio93async 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) == 0102103104@pytest.mark.asyncio105async 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) == 1115116117@pytest.mark.asyncio118async 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) == 0
deleted:tests/test_connections.py-20 removed
1import pytest23import httpcore456@pytest.mark.asyncio7async 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!"121314@pytest.mark.asyncio15async 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 == 200
added:tests/test_decoders.py+88 added
1import zlib23import brotli4import pytest56import httpcore789def 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()1314 headers = [(b"Content-Encoding", b"deflate")]15 response = httpcore.Response(200, headers=headers, body=compressed_body)16 assert response.body == body171819def 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()2324 headers = [(b"Content-Encoding", b"gzip")]25 response = httpcore.Response(200, headers=headers, body=compressed_body)26 assert response.body == body272829def test_brotli():30 body = b"test 123"31 compressed_body = brotli.compress(body)3233 headers = [(b"Content-Encoding", b"br")]34 response = httpcore.Response(200, headers=headers, body=compressed_body)35 assert response.body == body363738def test_multi():39 body = b"test 123"4041 deflate_compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)42 compressed_body = deflate_compressor.compress(body) + deflate_compressor.flush()4344 gzip_compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)45 compressed_body = (46 gzip_compressor.compress(compressed_body) + gzip_compressor.flush()47 )4849 headers = [(b"Content-Encoding", b"deflate, gzip")]50 response = httpcore.Response(200, headers=headers, body=compressed_body)51 assert response.body == body525354def test_multi_with_identity():55 body = b"test 123"56 compressed_body = brotli.compress(body)5758 headers = [(b"Content-Encoding", b"br, identity")]59 response = httpcore.Response(200, headers=headers, body=compressed_body)60 assert response.body == body6162 headers = [(b"Content-Encoding", b"identity, br")]63 response = httpcore.Response(200, headers=headers, body=compressed_body)64 assert response.body == body656667@pytest.mark.asyncio68async def test_streaming():69 body = b"test 123"70 compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)7172 async def compress(body):73 yield compressor.compress(body)74 yield compressor.flush()7576 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() == body808182@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))83def 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
1import zlib23import brotli4import pytest56import httpcore789def 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()1314 headers = [(b"Content-Encoding", b"deflate")]15 response = httpcore.Response(200, headers=headers, body=compressed_body)16 assert response.body == body171819def 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()2324 headers = [(b"Content-Encoding", b"gzip")]25 response = httpcore.Response(200, headers=headers, body=compressed_body)26 assert response.body == body272829def test_brotli():30 body = b"test 123"31 compressed_body = brotli.compress(body)3233 headers = [(b"Content-Encoding", b"br")]34 response = httpcore.Response(200, headers=headers, body=compressed_body)35 assert response.body == body363738def test_multi():39 body = b"test 123"4041 deflate_compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)42 compressed_body = deflate_compressor.compress(body) + deflate_compressor.flush()4344 gzip_compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)45 compressed_body = (46 gzip_compressor.compress(compressed_body) + gzip_compressor.flush()47 )4849 headers = [(b"Content-Encoding", b"deflate, gzip")]50 response = httpcore.Response(200, headers=headers, body=compressed_body)51 assert response.body == body525354def test_multi_with_identity():55 body = b"test 123"56 compressed_body = brotli.compress(body)5758 headers = [(b"Content-Encoding", b"br, identity")]59 response = httpcore.Response(200, headers=headers, body=compressed_body)60 assert response.body == body6162 headers = [(b"Content-Encoding", b"identity, br")]63 response = httpcore.Response(200, headers=headers, body=compressed_body)64 assert response.body == body656667@pytest.mark.asyncio68async def test_streaming():69 body = b"test 123"70 compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)7172 async def compress(body):73 yield compressor.compress(body)74 yield compressor.flush()7576 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() == body808182@pytest.mark.parametrize("header_value", (b"deflate", b"gzip", b"br"))83def 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
1import json23import h2.config4import h2.connection5import h2.events6import pytest78import httpcore91011class MockServer(httpcore.BaseReader, httpcore.BaseWriter):12 """13 This class exposes Reader and Writer style interfaces14 """1516 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 = {}2122 # BaseReader interface2324 async def read(self, n, timeout) -> bytes:25 send, self.buffer = self.buffer[:n], self.buffer[n:]26 return send2728 # BaseWriter interface2930 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)4041 async def write(self, data: bytes, timeout) -> None:42 self.write_no_block(data)4344 async def close(self) -> None:45 pass4647 # Server implementation4849 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""})5354 def receive_data(self, data, stream_id):55 self.requests[stream_id][-1]["data"] += data5657 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]6162 request_headers = dict(request["headers"])63 request_data = request["data"]6465 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()7273 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()777879@pytest.mark.asyncio80async 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": ""}868788@pytest.mark.asyncio89async 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 }99100101@pytest.mark.asyncio102async 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")108109 assert response_1.status_code == 200110 assert json.loads(response_1.body) == {"method": "GET", "path": "/1", "body": ""}111112 assert response_2.status_code == 200113 assert json.loads(response_2.body) == {"method": "GET", "path": "/2", "body": ""}114115 assert response_3.status_code == 200116 assert json.loads(response_3.body) == {"method": "GET", "path": "/3", "body": ""}
deleted:tests/test_requests.py-101 removed
1import pytest23import httpcore456def 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 )121314def 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 )242526def test_transfer_encoding_header():27 async def streaming_body(data):28 yield data # pragma: nocover2930 body = streaming_body(b"test 123")3132 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 )414243def test_override_host_header():44 headers = [(b"host", b"1.2.3.4:80")]4546 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 )515253def test_override_accept_encoding_header():54 headers = [(b"accept-encoding", b"identity")]5556 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 )616263def test_override_content_length_header():64 async def streaming_body(data):65 yield data # pragma: nocover6667 body = streaming_body(b"test 123")68 headers = [(b"content-length", b"8")]6970 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 )798081def 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 == "/"8687 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"919293def test_invalid_urls():94 with pytest.raises(ValueError):95 httpcore.Request("GET", "example.org")9697 with pytest.raises(ValueError):98 httpcore.Request("GET", "invalid://example.org")99100 with pytest.raises(ValueError):101 httpcore.Request("GET", "http:///foo")
deleted:tests/test_responses.py-74 removed
1import pytest23import httpcore456async def streaming_body():7 yield b"Hello, "8 yield b"world!"91011def 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_closed171819@pytest.mark.asyncio20async def test_read_response():21 response = httpcore.Response(200, body=b"Hello, world!")2223 assert response.status_code == 20024 assert response.body == b"Hello, world!"25 assert response.is_closed2627 body = await response.read()2829 assert body == b"Hello, world!"30 assert response.body == b"Hello, world!"31 assert response.is_closed323334@pytest.mark.asyncio35async def test_streaming_response():36 response = httpcore.Response(200, body=streaming_body())3738 assert response.status_code == 20039 assert not hasattr(response, "body")40 assert not response.is_closed4142 body = await response.read()4344 assert body == b"Hello, world!"45 assert response.body == b"Hello, world!"46 assert response.is_closed474849@pytest.mark.asyncio50async def test_cannot_read_after_stream_consumed():51 response = httpcore.Response(200, body=streaming_body())5253 body = b""54 async for part in response.stream():55 body += part5657 with pytest.raises(httpcore.StreamConsumed):58 await response.read()596061@pytest.mark.asyncio62async def test_cannot_read_after_response_closed():63 response = httpcore.Response(200, body=streaming_body())6465 await response.close()6667 with pytest.raises(httpcore.ResponseClosed):68 await response.read()697071def test_unknown_status_code():72 response = httpcore.Response(600)73 assert response.status_code == 60074 assert response.reason_phrase == ""