Rollin'
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 fab6fcd · Browse files · 16 files·+432 added−67 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
16 files+432 added−67 removed
- tests:+30 added−27 removed
- other:+402 added−40 removed
Provenance
- Commit
8a29a0a- Tree
15eb0e4- Author
Tom Christie <tom@tomchristie.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
fab6fcd
16 files changed+432 added−67 removed
modified:httpcore/__init__.py+1 added-1 removed
12 unmodified lines13 Timeout,14 )15 from .http2 import HTTP2Connection16 from .http11 import HTTP11Connection17-from .models import URL, Origin, Request, Response17+from .models import URL, Headers, Origin, Request, Response18 from .streams import BaseReader, BaseWriter, Protocol, Reader, Writer, connect19 from .sync import SyncClient, SyncConnectionPool20 21 __version__ = "0.2.1"modified:httpcore/adapters.py+1 added-1 removed
8 unmodified lines9 self,10 method: str,11 url: typing.Union[str, URL],12 *,13- headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),13+ headers: typing.List[typing.Tuple[bytes, bytes]] = [],14 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",15 **options: typing.Any,16 ) -> Response:17 request = Request(method, url, headers=headers, body=body)23 unmodified linesmodified:httpcore/auth.py+1 added-1 removed
13 unmodified lines14 async def send(self, request: Request, **options: typing.Any) -> Response:15 return await self.dispatch.send(request, **options)16 17 async def close(self) -> None:18- self.dispatch.close()18+ await self.dispatch.close()modified:httpcore/client.py+3 added-3 removed
38 unmodified lines39 method: str,40 url: typing.Union[str, URL],41 *,42 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",43- headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),43+ headers: typing.List[typing.Tuple[bytes, bytes]] = [],44 stream: bool = False,45 allow_redirects: bool = True,46 ssl: typing.Optional[SSLConfig] = None,47 timeout: typing.Optional[TimeoutConfig] = None,12 unmodified lines60 async def get(61 self,62 url: typing.Union[str, URL],63 *,64- headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),64+ headers: typing.List[typing.Tuple[bytes, bytes]] = [],65 stream: bool = False,66 ssl: typing.Optional[SSLConfig] = None,67 timeout: typing.Optional[TimeoutConfig] = None,68 ) -> Response:5 unmodified lines74 self,75 url: typing.Union[str, URL],76 *,77 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",78- headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),78+ headers: typing.List[typing.Tuple[bytes, bytes]] = [],79 stream: bool = False,80 ssl: typing.Optional[SSLConfig] = None,81 timeout: typing.Optional[TimeoutConfig] = None,82 ) -> Response:42 unmodified linesmodified:httpcore/cookies.py+1 added-1 removed
13 unmodified lines14 async def send(self, request: Request, **options: typing.Any) -> Response:15 return await self.dispatch.send(request, **options)16 17 async def close(self) -> None:18- self.dispatch.close()18+ await self.dispatch.close()modified:httpcore/decoders.py+7 added-7 removed
108 unmodified lines109 return data110 111 112 SUPPORTED_DECODERS = {113- b"identity": IdentityDecoder,114- b"deflate": DeflateDecoder,115- b"gzip": GZipDecoder,116- b"br": BrotliDecoder,113+ "identity": IdentityDecoder,114+ "deflate": DeflateDecoder,115+ "gzip": GZipDecoder,116+ "br": BrotliDecoder,117 }118 119 120 if brotli is None:121- SUPPORTED_DECODERS.pop(b"br") # pragma: nocover121+ SUPPORTED_DECODERS.pop("br") # pragma: nocover122 123 124-ACCEPT_ENCODING = b", ".join(125- [key for key in SUPPORTED_DECODERS.keys() if key != b"identity"]124+ACCEPT_ENCODING = ", ".join(125+ [key for key in SUPPORTED_DECODERS.keys() if key != "identity"]126 )modified:httpcore/exceptions.py+5 added
50 unmodified lines51 """52 Attempted to read or stream response content, but the request has been53 closed without loading the body.54 """55+56+57+class InvalidURL(Exception):58+ """59+ """modified:httpcore/http11.py+1 added-1 removed
49 unmodified lines50 51 # Start sending the request.52 method = request.method.encode()53 target = request.url.full_path54- headers = request.headers54+ headers = request.headers.raw55 event = h11.Request(method=method, target=target, headers=headers)56 await self._send_event(event, timeout)57 58 # Send the request body.84 unmodified linesmodified:httpcore/http2.py+1 added-1 removed
94 unmodified lines95 (b":method", request.method.encode()),96 (b":authority", request.url.hostname.encode()),97 (b":scheme", request.url.scheme.encode()),98 (b":path", request.url.full_path.encode()),99- ] + request.headers99+ ] + request.headers.raw100 self.h2_state.send_headers(stream_id, headers)101 data_to_send = self.h2_state.data_to_send()102 await self.writer.write(data_to_send, timeout)103 return stream_id47 unmodified linesmodified:httpcore/models.py+130 added-19 removed
38 unmodified lines39 def query(self) -> str:40 return self.components.query41 42 @property43+ def fragment(self) -> str:44+ return self.components.fragment45+46+ @property47 def hostname(self) -> str:48 return self.components.hostname49 50 @property39 unmodified lines90 def __hash__(self) -> int:91 return hash((self.is_ssl, self.hostname, self.port))92 93 94+class Headers(typing.MutableMapping[str, str]):95+ """96+ A case-insensitive multidict.97+ """98+99+ def __init__(self, headers: typing.List[typing.Tuple[bytes, bytes]]) -> None:100+ self._list = [(k.lower(), v) for k, v in headers]101+102+ @property103+ def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:104+ return self._list105+106+ def keys(self) -> typing.List[str]: # type: ignore107+ return [key.decode("latin-1") for key, value in self._list]108+109+ def values(self) -> typing.List[str]: # type: ignore110+ return [value.decode("latin-1") for key, value in self._list]111+112+ def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore113+ return [114+ (key.decode("latin-1"), value.decode("latin-1"))115+ for key, value in self._list116+ ]117+118+ def get(self, key: str, default: typing.Any = None) -> typing.Any:119+ try:120+ return self[key]121+ except KeyError:122+ return default123+124+ def getlist(self, key: str) -> typing.List[str]:125+ get_header_key = key.lower().encode("latin-1")126+ return [127+ item_value.decode("latin-1")128+ for item_key, item_value in self._list129+ if item_key == get_header_key130+ ]131+132+ def __getitem__(self, key: str) -> str:133+ get_header_key = key.lower().encode("latin-1")134+ for header_key, header_value in self._list:135+ if header_key == get_header_key:136+ return header_value.decode("latin-1")137+ raise KeyError(key)138+139+ def __setitem__(self, key: str, value: str) -> None:140+ """141+ Set the header `key` to `value`, removing any duplicate entries.142+ Retains insertion order.143+ """144+ set_key = key.lower().encode("latin-1")145+ set_value = value.encode("latin-1")146+147+ found_indexes = []148+ for idx, (item_key, item_value) in enumerate(self._list):149+ if item_key == set_key:150+ found_indexes.append(idx)151+152+ for idx in reversed(found_indexes[1:]):153+ del self._list[idx]154+155+ if found_indexes:156+ idx = found_indexes[0]157+ self._list[idx] = (set_key, set_value)158+ else:159+ self._list.append((set_key, set_value))160+161+ def __delitem__(self, key: str) -> None:162+ """163+ Remove the header `key`.164+ """165+ del_key = key.lower().encode("latin-1")166+167+ pop_indexes = []168+ for idx, (item_key, item_value) in enumerate(self._list):169+ if item_key == del_key:170+ pop_indexes.append(idx)171+172+ for idx in reversed(pop_indexes):173+ del self._list[idx]174+175+ def __contains__(self, key: typing.Any) -> bool:176+ get_header_key = key.lower().encode("latin-1")177+ for header_key, header_value in self._list:178+ if header_key == get_header_key:179+ return True180+ return False181+182+ def __iter__(self) -> typing.Iterator[typing.Any]:183+ return iter(self.keys())184+185+ def __len__(self) -> int:186+ return len(self._list)187+188+ def __eq__(self, other: typing.Any) -> bool:189+ if not isinstance(other, Headers):190+ return False191+ return sorted(self._list) == sorted(other._list)192+193+ def __repr__(self) -> str:194+ class_name = self.__class__.__name__195+ as_dict = dict(self.items())196+ if len(as_dict) == len(self):197+ return f"{class_name}({as_dict!r})"198+ return f"{class_name}(raw={self.raw!r})"199+200+201 class Request:202 def __init__(203 self,204 method: str,205 url: typing.Union[str, URL],206 *,96- headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),207+ headers: typing.List[typing.Tuple[bytes, bytes]] = [],208 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",209 ):210 self.method = method.upper()211 self.url = URL(url) if isinstance(url, str) else url101- self.headers = list(headers)212 if isinstance(body, bytes):213 self.is_streaming = False214 self.body = body215 else:216 self.is_streaming = True217 self.body_aiter = body108- self.headers = self._auto_headers() + self.headers218+ self.headers = self.build_headers(headers)219 110- def _auto_headers(self) -> typing.List[typing.Tuple[bytes, bytes]]:220+ def build_headers(221+ self, init_headers: typing.List[typing.Tuple[bytes, bytes]]222+ ) -> Headers:223 has_host = False224 has_content_length = False225 has_accept_encoding = False226 115- for header, value in self.headers:227+ for header, value in init_headers:228 header = header.strip().lower()229 if header == b"host":230 has_host = True231 elif header in (b"content-length", b"transfer-encoding"):232 has_content_length = True233 elif header == b"accept-encoding":234 has_accept_encoding = True235 124- headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]236+ auto_headers = [] # type: typing.List[typing.Tuple[bytes, bytes]]237 238 if not has_host:127- headers.append((b"host", self.url.netloc.encode("ascii")))239+ auto_headers.append((b"host", self.url.netloc.encode("ascii")))240 if not has_content_length:241 if self.is_streaming:130- headers.append((b"transfer-encoding", b"chunked"))242+ auto_headers.append((b"transfer-encoding", b"chunked"))243 elif self.body:244 content_length = str(len(self.body)).encode()133- headers.append((b"content-length", content_length))245+ auto_headers.append((b"content-length", content_length))246 if not has_accept_encoding:135- headers.append((b"accept-encoding", ACCEPT_ENCODING))247+ auto_headers.append((b"accept-encoding", ACCEPT_ENCODING.encode()))248 137- return headers249+ return Headers(auto_headers + init_headers)250 251 async def stream(self) -> typing.AsyncIterator[bytes]:252 if self.is_streaming:253 async for part in self.body_aiter:8 unmodified lines262 status_code: int,263 *,264 reason: typing.Optional[str] = None,265 protocol: typing.Optional[str] = None,154- headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),266+ headers: typing.List[typing.Tuple[bytes, bytes]] = [],267 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",268 on_close: typing.Callable = None,269 ):270 self.status_code = status_code4 unmodified lines275 self.reason = ""276 else:277 self.reason = reason278 self.protocol = protocol167- self.headers = list(headers)279+ self.headers = Headers(headers)280 self.on_close = on_close281 self.is_closed = False282 self.is_streamed = False283 284 decoders = [] # type: typing.List[Decoder]173- for header, value in self.headers:174- if header.strip().lower() == b"content-encoding":175- for part in value.split(b","):176- part = part.strip().lower()177- decoder_cls = SUPPORTED_DECODERS[part]178- decoders.append(decoder_cls())285+ value = self.headers.get("content-encoding", "identity")286+ for part in value.split(","):287+ part = part.strip().lower()288+ decoder_cls = SUPPORTED_DECODERS[part]289+ decoders.append(decoder_cls())290 291 if len(decoders) == 0:292 self.decoder = IdentityDecoder() # type: Decoder293 elif len(decoders) == 1:59 unmodified linesmodified:httpcore/redirects.py+53 added-2 removed
1 import typing2+from urllib.parse import urljoin, urlparse3 4 from .adapters import Adapter5 from .exceptions import TooManyRedirects5-from .models import Request, Response6+from .models import URL, Request, Response7+from .status_codes import codes8+from .utils import requote_uri9 10 11 class RedirectAdapter(Adapter):12 def __init__(self, dispatch: Adapter, max_redirects: int):18 unmodified lines31 32 return response33 34 async def close(self) -> None:32- self.dispatch.close()35+ await self.dispatch.close()36 37 def build_redirect_request(self, request: Request, response: Response) -> Request:38+ method = self.redirect_method(request, response)39+ url = self.redirect_url(request, response)40 raise NotImplementedError()41+42+ def redirect_method(self, request: Request, response: Response) -> str:43+ """44+ When being redirected we may want to change the method of the request45+ based on certain specs or browser behavior.46+ """47+ method = request.method48+49+ # https://tools.ietf.org/html/rfc7231#section-6.4.450+ if response.status_code == codes["see_other"] and method != "HEAD":51+ method = "GET"52+53+ # Do what the browsers do, despite standards...54+ # First, turn 302s into GETs.55+ if response.status_code == codes["found"] and method != "HEAD":56+ method = "GET"57+58+ # Second, if a POST is responded to with a 301, turn it into a GET.59+ # This bizarre behaviour is explained in Issue 1704.60+ if response.status_code == codes["moved"] and method == "POST":61+ method = "GET"62+63+ return method64+65+ def redirect_url(self, request: Request, response: Response) -> URL:66+ location = response.headers["Location"]67+68+ # Handle redirection without scheme (see: RFC 1808 Section 4)69+ if location.startswith("//"):70+ location = f"{request.url.scheme}:{location}"71+72+ # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)73+ parsed = urlparse(location)74+ if parsed.fragment == "" and request.url.fragment:75+ parsed = parsed._replace(fragment=request.url.fragment)76+ url = parsed.geturl()77+78+ # Facilitate relative 'location' headers, as allowed by RFC 7231.79+ # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')80+ # Compliant with RFC3986, we percent encode the url.81+ if not parsed.netloc:82+ url = urljoin(str(request.url), requote_uri(url))83+ else:84+ url = requote_uri(url)85+86+ return URL(url)added:httpcore/status_codes.py+123 added
1+"""2+The ``codes`` object defines a mapping from common names for HTTP statuses3+to their numerical codes, accessible either as attributes or as dictionary4+items.5+>>> requests.codes['temporary_redirect']6+3077+>>> requests.codes.teapot8+4189+Some codes have multiple names, and both upper- and lower-case versions of10+the names are allowed. For example, ``codes.ok``, ``codes.OK``, and11+``codes.okay`` all correspond to the HTTP status code 200.12+"""13+14+import typing15+16+from .structures import LookupDict17+18+_codes = {19+ # Informational.20+ 100: ("continue",),21+ 101: ("switching_protocols",),22+ 102: ("processing",),23+ 103: ("checkpoint",),24+ 122: ("uri_too_long", "request_uri_too_long"),25+ 200: ("ok", "okay", "all_ok", "all_okay", "all_good", "\\o/", "✓"),26+ 201: ("created",),27+ 202: ("accepted",),28+ 203: ("non_authoritative_info", "non_authoritative_information"),29+ 204: ("no_content",),30+ 205: ("reset_content", "reset"),31+ 206: ("partial_content", "partial"),32+ 207: ("multi_status", "multiple_status", "multi_stati", "multiple_stati"),33+ 208: ("already_reported",),34+ 226: ("im_used",),35+ # Redirection.36+ 300: ("multiple_choices",),37+ 301: ("moved_permanently", "moved", "\\o-"),38+ 302: ("found",),39+ 303: ("see_other", "other"),40+ 304: ("not_modified",),41+ 305: ("use_proxy",),42+ 306: ("switch_proxy",),43+ 307: ("temporary_redirect", "temporary_moved", "temporary"),44+ 308: (45+ "permanent_redirect",46+ "resume_incomplete",47+ "resume",48+ ), # These 2 to be removed in 3.049+ # Client Error.50+ 400: ("bad_request", "bad"),51+ 401: ("unauthorized",),52+ 402: ("payment_required", "payment"),53+ 403: ("forbidden",),54+ 404: ("not_found", "-o-"),55+ 405: ("method_not_allowed", "not_allowed"),56+ 406: ("not_acceptable",),57+ 407: ("proxy_authentication_required", "proxy_auth", "proxy_authentication"),58+ 408: ("request_timeout", "timeout"),59+ 409: ("conflict",),60+ 410: ("gone",),61+ 411: ("length_required",),62+ 412: ("precondition_failed", "precondition"),63+ 413: ("request_entity_too_large",),64+ 414: ("request_uri_too_large",),65+ 415: ("unsupported_media_type", "unsupported_media", "media_type"),66+ 416: (67+ "requested_range_not_satisfiable",68+ "requested_range",69+ "range_not_satisfiable",70+ ),71+ 417: ("expectation_failed",),72+ 418: ("im_a_teapot", "teapot", "i_am_a_teapot"),73+ 421: ("misdirected_request",),74+ 422: ("unprocessable_entity", "unprocessable"),75+ 423: ("locked",),76+ 424: ("failed_dependency", "dependency"),77+ 425: ("unordered_collection", "unordered"),78+ 426: ("upgrade_required", "upgrade"),79+ 428: ("precondition_required", "precondition"),80+ 429: ("too_many_requests", "too_many"),81+ 431: ("header_fields_too_large", "fields_too_large"),82+ 444: ("no_response", "none"),83+ 449: ("retry_with", "retry"),84+ 450: ("blocked_by_windows_parental_controls", "parental_controls"),85+ 451: ("unavailable_for_legal_reasons", "legal_reasons"),86+ 499: ("client_closed_request",),87+ # Server Error.88+ 500: ("internal_server_error", "server_error", "/o\\", "✗"),89+ 501: ("not_implemented",),90+ 502: ("bad_gateway",),91+ 503: ("service_unavailable", "unavailable"),92+ 504: ("gateway_timeout",),93+ 505: ("http_version_not_supported", "http_version"),94+ 506: ("variant_also_negotiates",),95+ 507: ("insufficient_storage",),96+ 509: ("bandwidth_limit_exceeded", "bandwidth"),97+ 510: ("not_extended",),98+ 511: ("network_authentication_required", "network_auth", "network_authentication"),99+} # type: typing.Dict[int, typing.Sequence[str]]100+101+codes = LookupDict(name="status_codes")102+103+104+def _init() -> None:105+ for code, titles in _codes.items():106+ for title in titles:107+ setattr(codes, title, code)108+ if not title.startswith(("\\", "/")):109+ setattr(codes, title.upper(), code)110+111+ def doc(code: int) -> str:112+ names = ", ".join("``%s``" % n for n in _codes[code])113+ return "* %d: %s" % (code, names)114+115+ global __doc__116+ __doc__ = (117+ __doc__ + "\n" + "\n".join(doc(code) for code in sorted(_codes))118+ if __doc__ is not None119+ else None120+ )121+122+123+_init()added:httpcore/structures.py+20 added
1+import typing2+3+4+class LookupDict(dict):5+ """Dictionary lookup object."""6+7+ def __init__(self, name: str = None) -> None:8+ self.name = name9+ super(LookupDict, self).__init__()10+11+ def __repr__(self) -> str:12+ return "<lookup '%s'>" % (self.name)13+14+ def __getitem__(self, key: typing.Any) -> typing.Any:15+ # We allow fall-through here, so values default to None16+17+ return self.__dict__.get(key, None)18+19+ def get(self, key: typing.Any, default: typing.Any = None) -> typing.Any:20+ return self.__dict__.get(key, default)modified:httpcore/sync.py+3 added-3 removed
3 unmodified lines4 5 from .adapters import Adapter6 from .config import SSLConfig, TimeoutConfig7 from .connection_pool import ConnectionPool8-from .models import URL, Response8+from .models import URL, Headers, Response9 10 11 class SyncResponse:12 def __init__(self, response: Response, loop: asyncio.AbstractEventLoop):8 unmodified lines21 def reason(self) -> str:22 return self._response.reason23 24 @property25- def headers(self) -> typing.List[typing.Tuple[bytes, bytes]]:25+ def headers(self) -> Headers:26 return self._response.headers27 28 @property29 def body(self) -> bytes:23 unmodified lines53 self,54 method: str,55 url: typing.Union[str, URL],56 *,57- headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),57+ headers: typing.List[typing.Tuple[bytes, bytes]] = [],58 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",59 **options: typing.Any60 ) -> SyncResponse:61 response = self._loop.run_until_complete(22 unmodified linesadded:httpcore/utils.py+52 added
1+from urllib.parse import quote2+3+from .exceptions import InvalidURL4+5+# The unreserved URI characters (RFC 3986)6+UNRESERVED_SET = frozenset(7+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~"8+)9+10+11+def unquote_unreserved(uri: str) -> str:12+ """Un-escape any percent-escape sequences in a URI that are unreserved13+ characters. This leaves all reserved, illegal and non-ASCII bytes encoded.14+ :rtype: str15+ """16+ parts = uri.split("%")17+ for i in range(1, len(parts)):18+ h = parts[i][0:2]19+ if len(h) == 2 and h.isalnum():20+ try:21+ c = chr(int(h, 16))22+ except ValueError:23+ raise InvalidURL("Invalid percent-escape sequence: '%s'" % h)24+25+ if c in UNRESERVED_SET:26+ parts[i] = c + parts[i][2:]27+ else:28+ parts[i] = "%" + parts[i]29+ else:30+ parts[i] = "%" + parts[i]31+ return "".join(parts)32+33+34+def requote_uri(uri: str) -> str:35+ """36+ Re-quote the given URI.37+38+ This function passes the given URI through an unquote/quote cycle to39+ ensure that it is fully and consistently quoted.40+ """41+ safe_with_percent = "!#$%&'()*+,/:;=?@[]~"42+ safe_without_percent = "!#$&'()*+,/:;=?@[]~"43+ try:44+ # Unquote only the unreserved characters45+ # Then quote only illegal characters (do not quote reserved,46+ # unreserved, or '%')47+ return quote(unquote_unreserved(uri), safe=safe_with_percent)48+ except InvalidURL:49+ # We couldn't unquote the given URI, so let's try quoting it, but50+ # there may be unquoted '%'s in the URI. We need to make sure they're51+ # properly quoted so they do not cause issues elsewhere.52+ return quote(uri, safe=safe_without_percent)modified:tests/test_requests.py+30 added-27 removed
3 unmodified lines4 5 6 def test_host_header():7 request = httpcore.Request("GET", "http://example.org")8- assert request.headers == [9- (b"host", b"example.org"),10- (b"accept-encoding", b"deflate, gzip, br"),11- ]8+ assert request.headers == httpcore.Headers(9+ [(b"host", b"example.org"), (b"accept-encoding", b"deflate, gzip, br")]10+ )11 12 13 def test_content_length_header():14 request = httpcore.Request("POST", "http://example.org", body=b"test 123")15+ assert request.headers == httpcore.Headers(16- assert request.headers == [17- (b"host", b"example.org"),18- (b"content-length", b"8"),19- (b"accept-encoding", b"deflate, gzip, br"),20- ]16+ [17+ (b"host", b"example.org"),18+ (b"content-length", b"8"),19+ (b"accept-encoding", b"deflate, gzip, br"),20+ ]21+ )22 23 24 def test_transfer_encoding_header():25 async def streaming_body(data):1 unmodified line27 28 body = streaming_body(b"test 123")29 30 request = httpcore.Request("POST", "http://example.org", body=body)31+ assert request.headers == httpcore.Headers(30- assert request.headers == [31- (b"host", b"example.org"),32- (b"transfer-encoding", b"chunked"),33- (b"accept-encoding", b"deflate, gzip, br"),34- ]32+ [33+ (b"host", b"example.org"),34+ (b"transfer-encoding", b"chunked"),35+ (b"accept-encoding", b"deflate, gzip, br"),36+ ]37+ )38 39 40 def test_override_host_header():41 headers = [(b"host", b"1.2.3.4:80")]42 43 request = httpcore.Request("GET", "http://example.org", headers=headers)41- assert request.headers == [42- (b"accept-encoding", b"deflate, gzip, br"),43- (b"host", b"1.2.3.4:80"),44- ]44+ assert request.headers == httpcore.Headers(45+ [(b"accept-encoding", b"deflate, gzip, br"), (b"host", b"1.2.3.4:80")]46+ )47 48 49 def test_override_accept_encoding_header():50 headers = [(b"accept-encoding", b"identity")]51 52 request = httpcore.Request("GET", "http://example.org", headers=headers)51- assert request.headers == [52- (b"host", b"example.org"),53- (b"accept-encoding", b"identity"),54- ]53+ assert request.headers == httpcore.Headers(54+ [(b"host", b"example.org"), (b"accept-encoding", b"identity")]55+ )56 57 58 def test_override_content_length_header():59 async def streaming_body(data):2 unmodified lines62 body = streaming_body(b"test 123")63 headers = [(b"content-length", b"8")]64 65 request = httpcore.Request("POST", "http://example.org", body=body, headers=headers)66+ assert request.headers == httpcore.Headers(65- assert request.headers == [66- (b"host", b"example.org"),67- (b"accept-encoding", b"deflate, gzip, br"),68- (b"content-length", b"8"),69- ]67+ [68+ (b"host", b"example.org"),69+ (b"accept-encoding", b"deflate, gzip, br"),70+ (b"content-length", b"8"),71+ ]72+ )73 74 75 def test_url():76 request = httpcore.Request("GET", "http://example.org")19 unmodified lines