Drop 'adapters'
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 84b9691 · Browse files · 18 files·+559 added−623 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+559 added−623 removed
- tests:+350 added−325 removed
- other:+209 added−298 removed
Provenance
- Commit
d6628ca- Tree
a1dd616- Author
Tom Christie <tom@tomchristie.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
84b9691
18 files changed+559 added−623 removed
deleted:httpcore/adapters/__init__.py-4 removed
1-"""2-Adapter classes layer additional behavior over the raw dispatching of the3-HTTP request/response.4-"""deleted:httpcore/adapters/authentication.py-18 removed
1-import typing2-3-from ..interfaces import Adapter4-from ..models import Request, Response5-6-7-class AuthenticationAdapter(Adapter):8- def __init__(self, dispatch: Adapter):9- self.dispatch = dispatch10-11- def prepare_request(self, request: Request) -> None:12- self.dispatch.prepare_request(request)13-14- 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- await self.dispatch.close()deleted:httpcore/adapters/cookies.py-18 removed
1-import typing2-3-from ..interfaces import Adapter4-from ..models import Request, Response5-6-7-class CookieAdapter(Adapter):8- def __init__(self, dispatch: Adapter):9- self.dispatch = dispatch10-11- def prepare_request(self, request: Request) -> None:12- self.dispatch.prepare_request(request)13-14- 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- await self.dispatch.close()deleted:httpcore/adapters/environment.py-27 removed
1-import typing2-3-from ..interfaces import Adapter4-from ..models import Request, Response5-6-7-class EnvironmentAdapter(Adapter):8- def __init__(self, dispatch: Adapter, trust_env: bool = True):9- self.dispatch = dispatch10- self.trust_env = trust_env11-12- def prepare_request(self, request: Request) -> None:13- self.dispatch.prepare_request(request)14-15- async def send(self, request: Request, **options: typing.Any) -> Response:16- if self.trust_env:17- self.merge_environment_options(options)18- return await self.dispatch.send(request, **options)19-20- async def close(self) -> None:21- await self.dispatch.close()22-23- def merge_environment_options(self, options: dict) -> None:24- """25- Add environment options.26- """27- # TODOdeleted:httpcore/adapters/redirects.py-130 removed
1-import typing2-3-from ..config import DEFAULT_MAX_REDIRECTS4-from ..constants import codes5-from ..exceptions import RedirectBodyUnavailable, RedirectLoop, TooManyRedirects6-from ..interfaces import Adapter7-from ..models import URL, Headers, Request, Response8-9-10-class RedirectAdapter(Adapter):11- def __init__(self, dispatch: Adapter, max_redirects: int = DEFAULT_MAX_REDIRECTS):12- self.dispatch = dispatch13- self.max_redirects = max_redirects14-15- def prepare_request(self, request: Request) -> None:16- self.dispatch.prepare_request(request)17-18- async def send(self, request: Request, **options: typing.Any) -> Response:19- allow_redirects = options.pop("allow_redirects", True) # type: bool20-21- # The following will not typically be specified by the end-user developer,22- # but are included in `response.next()` calls.23- history = options.pop("history", []) # type: typing.List[Response]24- seen_urls = options.pop("seen_urls", set()) # type: typing.Set[URL]25-26- while True:27- # We perform these checks here, so that calls to `response.next()`28- # will raise redirect errors if appropriate.29- if len(history) > self.max_redirects:30- raise TooManyRedirects()31- if request.url in seen_urls:32- raise RedirectLoop()33-34- response = await self.dispatch.send(request, **options)35- response.history = list(history)36- if not response.is_redirect:37- break38-39- history.insert(0, response)40- seen_urls.add(request.url)41-42- if allow_redirects:43- request = self.build_redirect_request(request, response)44- else:45- next_options = dict(options)46- next_options["seen_urls"] = seen_urls47- next_options["history"] = history48-49- async def send_next() -> Response:50- nonlocal request, response, next_options51- request = self.build_redirect_request(request, response)52- response = await self.send(request, **next_options)53- return response54-55- response.next = send_next # type: ignore56- break57-58- return response59-60- async def close(self) -> None:61- await self.dispatch.close()62-63- def build_redirect_request(self, request: Request, response: Response) -> Request:64- method = self.redirect_method(request, response)65- url = self.redirect_url(request, response)66- headers = self.redirect_headers(request, url)67- content = self.redirect_content(request, method)68- return Request(method=method, url=url, headers=headers, data=content)69-70- def redirect_method(self, request: Request, response: Response) -> str:71- """72- When being redirected we may want to change the method of the request73- based on certain specs or browser behavior.74- """75- method = request.method76-77- # https://tools.ietf.org/html/rfc7231#section-6.4.478- if response.status_code == codes.see_other and method != "HEAD":79- method = "GET"80-81- # Do what the browsers do, despite standards...82- # Turn 302s into GETs.83- if response.status_code == codes.found and method != "HEAD":84- method = "GET"85-86- # If a POST is responded to with a 301, turn it into a GET.87- # This bizarre behaviour is explained in 'requests' issue 1704.88- if response.status_code == codes.moved_permanently and method == "POST":89- method = "GET"90-91- return method92-93- def redirect_url(self, request: Request, response: Response) -> URL:94- """95- Return the URL for the redirect to follow.96- """97- location = response.headers["Location"]98-99- url = URL(location, allow_relative=True)100-101- # Facilitate relative 'Location' headers, as allowed by RFC 7231.102- # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')103- if url.is_relative_url:104- url = url.resolve_with(request.url)105-106- # Attach previous fragment if needed (RFC 7231 7.1.2)107- if request.url.fragment and not url.fragment:108- url = url.copy_with(fragment=request.url.fragment)109-110- return url111-112- def redirect_headers(self, request: Request, url: URL) -> Headers:113- """114- Strip Authorization headers when responses are redirected away from115- the origin.116- """117- headers = Headers(request.headers)118- if url.origin != request.url.origin:119- del headers["Authorization"]120- return headers121-122- def redirect_content(self, request: Request, method: str) -> bytes:123- """124- Return the body that should be used for the redirect request.125- """126- if method != request.method and method == "GET":127- return b""128- if request.is_streaming:129- raise RedirectBodyUnavailable()130- return request.contentmodified:httpcore/dispatch/connection_pool.py+12 added-7 removed
11 unmodified lines12 TimeoutConfig,13 )14 from ..decoders import ACCEPT_ENCODING15 from ..exceptions import PoolTimeout16-from ..interfaces import Adapter16+from ..interfaces import Dispatcher17 from ..models import Origin, Request, Response18 from .connection import HTTPConnection19 20 CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]61 unmodified lines82 def __len__(self) -> int:83 return len(self.all)84 85 86-class ConnectionPool(Adapter):86+class ConnectionPool(Dispatcher):87 def __init__(88 self,89 *,90 ssl: SSLConfig = DEFAULT_SSL_CONFIG,12 unmodified lines103 @property104 def num_connections(self) -> int:105 return len(self.keepalive_connections) + len(self.active_connections)106 107- def prepare_request(self, request: Request) -> None:108- request.prepare()109-110- async def send(self, request: Request, **options: typing.Any) -> Response:107+ async def send(108+ self,109+ request: Request,110+ stream: bool = False,111+ ssl: SSLConfig = None,112+ timeout: TimeoutConfig = None,113+ ) -> Response:114 connection = await self.acquire_connection(request.url.origin)115 try:113- response = await connection.send(request, **options)116+ response = await connection.send(117+ request, stream=stream, ssl=ssl, timeout=timeout118+ )119 except BaseException as exc:120 self.active_connections.remove(connection)121 self.max_connections.release()122 raise exc41 unmodified linesmodified:httpcore/dispatch/connection.py+23 added-14 removed
11 unmodified lines12 TimeoutConfig,13 )14 from ..constants import Protocol15 from ..exceptions import ConnectTimeout16-from ..interfaces import Adapter16+from ..interfaces import Dispatcher17 from ..models import Origin, Request, Response18 from .http2 import HTTP2Connection19 from .http11 import HTTP11Connection20 21 # Callback signature: async def callback(conn: HTTPConnection) -> None22 ReleaseCallback = typing.Callable[["HTTPConnection"], typing.Awaitable[None]]23 24 25-class HTTPConnection(Adapter):25+class HTTPConnection(Dispatcher):26 def __init__(27 self,28 origin: typing.Union[str, Origin],29 ssl: SSLConfig = DEFAULT_SSL_CONFIG,6 unmodified lines36 self.release_func = release_func37 self.h11_connection = None # type: typing.Optional[HTTP11Connection]38 self.h2_connection = None # type: typing.Optional[HTTP2Connection]39 40- def prepare_request(self, request: Request) -> None:41- request.prepare()42-43- async def send(self, request: Request, **options: typing.Any) -> Response:40+ async def send(41+ self,42+ request: Request,43+ stream: bool = False,44+ ssl: SSLConfig = None,45+ timeout: TimeoutConfig = None,46+ ) -> Response:47 if self.h11_connection is None and self.h2_connection is None:45- await self.connect(**options)48+ await self.connect(ssl=ssl, timeout=timeout)49 50 if self.h2_connection is not None:48- response = await self.h2_connection.send(request, **options)51+ response = await self.h2_connection.send(52+ request, stream=stream, timeout=timeout53+ )54 else:55 assert self.h11_connection is not None51- response = await self.h11_connection.send(request, **options)56+ response = await self.h11_connection.send(57+ request, stream=stream, timeout=timeout58+ )59 60 return response61 55- async def connect(self, **options: typing.Any) -> None:56- ssl = options.get("ssl", self.ssl)57- timeout = options.get("timeout", self.timeout)58- assert isinstance(ssl, SSLConfig)59- assert isinstance(timeout, TimeoutConfig)62+ async def connect(63+ self, ssl: SSLConfig = None, timeout: TimeoutConfig = None64+ ) -> None:65+ if ssl is None:66+ ssl = self.ssl67+ if timeout is None:68+ timeout = self.timeout69 70 host = self.origin.host71 port = self.origin.port72 ssl_context = await ssl.load_ssl_context() if self.origin.is_ssl else None31 unmodified linesmodified:httpcore/dispatch/http11.py+5 added-10 removed
7 unmodified lines8 SSLConfig,9 TimeoutConfig,10 )11 from ..exceptions import ConnectTimeout, ReadTimeout12-from ..interfaces import Adapter, BaseReader, BaseWriter12+from ..interfaces import BaseReader, BaseWriter, Dispatcher13 from ..models import Request, Response14 15 H11Event = typing.Union[16 h11.Request,12 unmodified lines29 # the `ConnectionPool.release_connection(conn: HTTPConnection)` method.30 OnReleaseCallback = typing.Callable[[], typing.Awaitable[None]]31 32 33-class HTTP11Connection(Adapter):33+class HTTP11Connection:34 READ_NUM_BYTES = 409635 36 def __init__(37 self,5 unmodified lines43 self.writer = writer44 self.on_release = on_release45 self.h11_state = h11.Connection(our_role=h11.CLIENT)46 47- def prepare_request(self, request: Request) -> None:48- request.prepare()49-50- async def send(self, request: Request, **options: typing.Any) -> Response:51- timeout = options.get("timeout")52- stream = options.get("stream", False)53- assert timeout is None or isinstance(timeout, TimeoutConfig)54-47+ async def send(48+ self, request: Request, stream: bool = False, timeout: TimeoutConfig = None49+ ) -> Response:50 # Start sending the request.51 method = request.method.encode("ascii")52 target = request.url.full_path.encode("ascii")53 headers = request.headers.raw89 unmodified linesmodified:httpcore/dispatch/http2.py+5 added-10 removed
9 unmodified lines10 SSLConfig,11 TimeoutConfig,12 )13 from ..exceptions import ConnectTimeout, ReadTimeout14-from ..interfaces import Adapter, BaseReader, BaseWriter14+from ..interfaces import BaseReader, BaseWriter, Dispatcher15 from ..models import Request, Response16 17 OptionalTimeout = typing.Optional[TimeoutConfig]18 19 20-class HTTP2Connection(Adapter):20+class HTTP2Connection:21 READ_NUM_BYTES = 409622 23 def __init__(24 self, reader: BaseReader, writer: BaseWriter, on_release: typing.Callable = None4 unmodified lines29 self.h2_state = h2.connection.H2Connection()30 self.events = {} # type: typing.Dict[int, typing.List[h2.events.Event]]31 self.initialized = False32 33- def prepare_request(self, request: Request) -> None:34- request.prepare()35-36- async def send(self, request: Request, **options: typing.Any) -> Response:37- timeout = options.get("timeout")38- stream = options.get("stream", False)39- assert timeout is None or isinstance(timeout, TimeoutConfig)40-33+ async def send(34+ self, request: Request, stream: bool = False, timeout: TimeoutConfig = None35+ ) -> Response:36 # Start sending the request.37 if not self.initialized:38 self.initiate_connection()39 stream_id = await self.send_headers(request, timeout)111 unmodified linesmodified:httpcore/__init__.py+1 added-2 removed
1-from .adapters.redirects import RedirectAdapter1 from .backends.sync import SyncClient2 from .client import Client3 from .config import PoolLimits, SSLConfig, TimeoutConfig4 from .constants import Protocol, codes15 unmodified lines20 StreamConsumed,21 Timeout,22 TooManyRedirects,23 )25-from .interfaces import Adapter, BaseReader, BaseWriter24+from .interfaces import BaseReader, BaseWriter, Dispatcher25 from .models import URL, Headers, Origin, QueryParams, Request, Response26 27 __version__ = "0.2.1"modified:httpcore/client.py+146 added-50 removed
1 import typing2 from types import TracebackType3 4-from .adapters.authentication import AuthenticationAdapter5-from .adapters.cookies import CookieAdapter6-from .adapters.environment import EnvironmentAdapter7-from .adapters.redirects import RedirectAdapter4 from .config import (5 DEFAULT_MAX_REDIRECTS,6 DEFAULT_POOL_LIMITS,7 DEFAULT_SSL_CONFIG,1 unmodified line9 PoolLimits,10 SSLConfig,11 TimeoutConfig,12 )13+from .constants import codes14 from .dispatch.connection_pool import ConnectionPool15+from .exceptions import RedirectBodyUnavailable, RedirectLoop, TooManyRedirects16+from .interfaces import Dispatcher17 from .models import (18 URL,19+ Headers,20 HeaderTypes,21 QueryParamTypes,22 Request,23 RequestData,8 unmodified lines32 ssl: SSLConfig = DEFAULT_SSL_CONFIG,33 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,34 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,35 max_redirects: int = DEFAULT_MAX_REDIRECTS,36+ dispatch: Dispatcher = None,37 ):37- connection_pool = ConnectionPool(38- ssl=ssl, timeout=timeout, pool_limits=pool_limits39- )40- cookie_adapter = CookieAdapter(dispatch=connection_pool)41- auth_adapter = AuthenticationAdapter(dispatch=cookie_adapter)42- redirect_adapter = RedirectAdapter(43- dispatch=auth_adapter, max_redirects=max_redirects44- )45- self.adapter = EnvironmentAdapter(dispatch=redirect_adapter)38+ if dispatch is None:39+ dispatch = ConnectionPool(ssl=ssl, timeout=timeout, pool_limits=pool_limits)40 47- async def request(48- self,49- method: str,50- url: URLTypes,51- *,52- data: RequestData = b"",53- query_params: QueryParamTypes = None,54- headers: HeaderTypes = None,55- stream: bool = False,56- allow_redirects: bool = True,57- ssl: SSLConfig = None,58- timeout: TimeoutConfig = None,59- ) -> Response:60- request = Request(61- method, url, data=data, query_params=query_params, headers=headers62- )63- self.prepare_request(request)64- response = await self.send(65- request,66- stream=stream,67- allow_redirects=allow_redirects,68- ssl=ssl,69- timeout=timeout,70- )71- return response41+ self.max_redirects = max_redirects42+ self.dispatch = dispatch43 44 async def get(45 self,46 url: URLTypes,155 unmodified lines202 ssl=ssl,203 timeout=timeout,204 )205 206+ async def request(207+ self,208+ method: str,209+ url: URLTypes,210+ *,211+ data: RequestData = b"",212+ query_params: QueryParamTypes = None,213+ headers: HeaderTypes = None,214+ stream: bool = False,215+ allow_redirects: bool = True,216+ ssl: SSLConfig = None,217+ timeout: TimeoutConfig = None,218+ ) -> Response:219+ request = Request(220+ method, url, data=data, query_params=query_params, headers=headers221+ )222+ self.prepare_request(request)223+ response = await self.send(224+ request,225+ stream=stream,226+ allow_redirects=allow_redirects,227+ ssl=ssl,228+ timeout=timeout,229+ )230+ return response231+232 def prepare_request(self, request: Request) -> None:236- self.adapter.prepare_request(request)233+ request.prepare()234 235 async def send(236 self,237 request: Request,238 *,239 stream: bool = False,243- allow_redirects: bool = True,240 ssl: SSLConfig = None,241 timeout: TimeoutConfig = None,242+ allow_redirects: bool = True,243+ history: typing.List[Response] = None,244 ) -> Response:247- options = {248- "stream": stream,249- "allow_redirects": allow_redirects,250- } # type: typing.Dict[str, typing.Any]245+ if history is None:246+ history = []247 252- if ssl is not None:253- options["ssl"] = ssl254- if timeout is not None:255- options["timeout"] = timeout248+ while True:249+ # We perform these checks here, so that calls to `response.next()`250+ # will raise redirect errors if appropriate.251+ if len(history) > self.max_redirects:252+ raise TooManyRedirects()253+ if request.url in [response.url for response in history]:254+ raise RedirectLoop()255 257- return await self.adapter.send(request, **options)256+ response = await self.dispatch.send(257+ request, stream=stream, ssl=ssl, timeout=timeout258+ )259+ response.history = list(history)260+ history = [response] + history261+ if not response.is_redirect:262+ break263 264+ if allow_redirects:265+ request = self.build_redirect_request(request, response)266+ else:267+268+ async def send_next() -> Response:269+ nonlocal request, response, ssl, allow_redirects, timeout, history270+ request = self.build_redirect_request(request, response)271+ response = await self.send(272+ request,273+ stream=stream,274+ allow_redirects=allow_redirects,275+ ssl=ssl,276+ timeout=timeout,277+ history=history,278+ )279+ return response280+281+ response.next = send_next # type: ignore282+ break283+284+ return response285+286+ def build_redirect_request(self, request: Request, response: Response) -> Request:287+ method = self.redirect_method(request, response)288+ url = self.redirect_url(request, response)289+ headers = self.redirect_headers(request, url)290+ content = self.redirect_content(request, method)291+ return Request(method=method, url=url, headers=headers, data=content)292+293+ def redirect_method(self, request: Request, response: Response) -> str:294+ """295+ When being redirected we may want to change the method of the request296+ based on certain specs or browser behavior.297+ """298+ method = request.method299+300+ # https://tools.ietf.org/html/rfc7231#section-6.4.4301+ if response.status_code == codes.see_other and method != "HEAD":302+ method = "GET"303+304+ # Do what the browsers do, despite standards...305+ # Turn 302s into GETs.306+ if response.status_code == codes.found and method != "HEAD":307+ method = "GET"308+309+ # If a POST is responded to with a 301, turn it into a GET.310+ # This bizarre behaviour is explained in 'requests' issue 1704.311+ if response.status_code == codes.moved_permanently and method == "POST":312+ method = "GET"313+314+ return method315+316+ def redirect_url(self, request: Request, response: Response) -> URL:317+ """318+ Return the URL for the redirect to follow.319+ """320+ location = response.headers["Location"]321+322+ url = URL(location, allow_relative=True)323+324+ # Facilitate relative 'Location' headers, as allowed by RFC 7231.325+ # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')326+ if url.is_relative_url:327+ url = url.resolve_with(request.url)328+329+ # Attach previous fragment if needed (RFC 7231 7.1.2)330+ if request.url.fragment and not url.fragment:331+ url = url.copy_with(fragment=request.url.fragment)332+333+ return url334+335+ def redirect_headers(self, request: Request, url: URL) -> Headers:336+ """337+ Strip Authorization headers when responses are redirected away from338+ the origin.339+ """340+ headers = Headers(request.headers)341+ if url.origin != request.url.origin:342+ del headers["Authorization"]343+ return headers344+345+ def redirect_content(self, request: Request, method: str) -> bytes:346+ """347+ Return the body that should be used for the redirect request.348+ """349+ if method != request.method and method == "GET":350+ return b""351+ if request.is_streaming:352+ raise RedirectBodyUnavailable()353+ return request.content354+355 async def close(self) -> None:260- await self.adapter.close()356+ await self.dispatch.close()357 358 async def __aenter__(self) -> "Client":359 return self360 7 unmodified linesmodified:httpcore/interfaces.py+17 added-8 removed
1 import typing2 from types import TracebackType3 4-from .config import TimeoutConfig4+from .config import SSLConfig, TimeoutConfig5 from .models import (6 URL,7+ Headers,8 HeaderTypes,9 QueryParamTypes,10 Request,11 RequestData,3 unmodified lines15 16 OptionalTimeout = typing.Optional[TimeoutConfig]17 18 18-class Adapter:19+class Dispatcher:20 """21 The base class for all adapter or dispatcher classes.22 23 Stubs out the interface, as well as providing a `.request()` convienence8 unmodified lines32 *,33 data: RequestData = b"",34 query_params: QueryParamTypes = None,35 headers: HeaderTypes = None,35- **options: typing.Any,36+ stream: bool = False,37+ ssl: SSLConfig = None,38+ timeout: TimeoutConfig = None39 ) -> Response:40 request = Request(41 method, url, data=data, query_params=query_params, headers=headers42 )43 self.prepare_request(request)41- response = await self.send(request, **options)44+ response = await self.send(request, stream=stream, ssl=ssl, timeout=timeout)45 return response46 47 def prepare_request(self, request: Request) -> None:45- raise NotImplementedError() # pragma: nocover48+ request.prepare()49 47- async def send(self, request: Request, **options: typing.Any) -> Response:50+ async def send(51+ self,52+ request: Request,53+ stream: bool = False,54+ ssl: SSLConfig = None,55+ timeout: TimeoutConfig = None,56+ ) -> Response:57 raise NotImplementedError() # pragma: nocover58 59 async def close(self) -> None:51- raise NotImplementedError() # pragma: nocover60+ pass # pragma: nocover61 53- async def __aenter__(self) -> "Adapter":62+ async def __aenter__(self) -> "Dispatcher":63 return self64 65 async def __aexit__(66 self,47 unmodified linesdeleted:tests/adapters/test_redirects.py-241 removed
1-import json2-from urllib.parse import parse_qs3-4-import pytest5-6-from httpcore import (7- URL,8- Adapter,9- RedirectAdapter,10- RedirectBodyUnavailable,11- RedirectLoop,12- Request,13- Response,14- TooManyRedirects,15- codes,16-)17-18-19-class MockDispatch(Adapter):20- def prepare_request(self, request: Request) -> None:21- pass22-23- async def send(self, request: Request, **options) -> Response:24- if request.url.path == "/redirect_301":25- status_code = codes.moved_permanently26- headers = {"location": "https://example.org/"}27- return Response(status_code, headers=headers, request=request)28-29- elif request.url.path == "/redirect_302":30- status_code = codes.found31- headers = {"location": "https://example.org/"}32- return Response(status_code, headers=headers, request=request)33-34- elif request.url.path == "/redirect_303":35- status_code = codes.see_other36- headers = {"location": "https://example.org/"}37- return Response(status_code, headers=headers, request=request)38-39- elif request.url.path == "/relative_redirect":40- headers = {"location": "/"}41- return Response(codes.see_other, headers=headers, request=request)42-43- elif request.url.path == "/no_scheme_redirect":44- headers = {"location": "//example.org/"}45- return Response(codes.see_other, headers=headers, request=request)46-47- elif request.url.path == "/multiple_redirects":48- params = parse_qs(request.url.query)49- count = int(params.get("count", "0")[0])50- redirect_count = count - 151- code = codes.see_other if count else codes.ok52- location = "/multiple_redirects"53- if redirect_count:54- location += "?count=" + str(redirect_count)55- headers = {"location": location} if count else {}56- return Response(code, headers=headers, request=request)57-58- if request.url.path == "/redirect_loop":59- headers = {"location": "/redirect_loop"}60- return Response(codes.see_other, headers=headers, request=request)61-62- elif request.url.path == "/cross_domain":63- headers = {"location": "https://example.org/cross_domain_target"}64- return Response(codes.see_other, headers=headers, request=request)65-66- elif request.url.path == "/cross_domain_target":67- headers = dict(request.headers.items())68- content = json.dumps({"headers": headers}).encode()69- return Response(codes.ok, content=content, request=request)70-71- elif request.url.path == "/redirect_body":72- await request.read()73- headers = {"location": "/redirect_body_target"}74- return Response(codes.permanent_redirect, headers=headers, request=request)75-76- elif request.url.path == "/redirect_body_target":77- content = await request.read()78- body = json.dumps({"body": content.decode()}).encode()79- return Response(codes.ok, content=body, request=request)80-81- return Response(codes.ok, content=b"Hello, world!", request=request)82-83-84-@pytest.mark.asyncio85-async def test_redirect_301():86- client = RedirectAdapter(MockDispatch())87- response = await client.request("POST", "https://example.org/redirect_301")88- assert response.status_code == codes.ok89- assert response.url == URL("https://example.org/")90- assert len(response.history) == 191-92-93-@pytest.mark.asyncio94-async def test_redirect_302():95- client = RedirectAdapter(MockDispatch())96- response = await client.request("POST", "https://example.org/redirect_302")97- assert response.status_code == codes.ok98- assert response.url == URL("https://example.org/")99- assert len(response.history) == 1100-101-102-@pytest.mark.asyncio103-async def test_redirect_303():104- client = RedirectAdapter(MockDispatch())105- response = await client.request("GET", "https://example.org/redirect_303")106- assert response.status_code == codes.ok107- assert response.url == URL("https://example.org/")108- assert len(response.history) == 1109-110-111-@pytest.mark.asyncio112-async def test_disallow_redirects():113- client = RedirectAdapter(MockDispatch())114- response = await client.request(115- "POST", "https://example.org/redirect_303", allow_redirects=False116- )117- assert response.status_code == codes.see_other118- assert response.url == URL("https://example.org/redirect_303")119- assert len(response.history) == 0120-121- response = await response.next()122- assert response.status_code == codes.ok123- assert response.url == URL("https://example.org/")124- assert len(response.history) == 1125-126-127-@pytest.mark.asyncio128-async def test_relative_redirect():129- client = RedirectAdapter(MockDispatch())130- response = await client.request("GET", "https://example.org/relative_redirect")131- assert response.status_code == codes.ok132- assert response.url == URL("https://example.org/")133- assert len(response.history) == 1134-135-136-@pytest.mark.asyncio137-async def test_no_scheme_redirect():138- client = RedirectAdapter(MockDispatch())139- response = await client.request("GET", "https://example.org/no_scheme_redirect")140- assert response.status_code == codes.ok141- assert response.url == URL("https://example.org/")142- assert len(response.history) == 1143-144-145-@pytest.mark.asyncio146-async def test_fragment_redirect():147- client = RedirectAdapter(MockDispatch())148- url = "https://example.org/relative_redirect#fragment"149- response = await client.request("GET", url)150- assert response.status_code == codes.ok151- assert response.url == URL("https://example.org/#fragment")152- assert len(response.history) == 1153-154-155-@pytest.mark.asyncio156-async def test_multiple_redirects():157- client = RedirectAdapter(MockDispatch())158- url = "https://example.org/multiple_redirects?count=20"159- response = await client.request("GET", url)160- assert response.status_code == codes.ok161- assert response.url == URL("https://example.org/multiple_redirects")162- assert len(response.history) == 20163-164-165-@pytest.mark.asyncio166-async def test_too_many_redirects():167- client = RedirectAdapter(MockDispatch())168- with pytest.raises(TooManyRedirects):169- await client.request("GET", "https://example.org/multiple_redirects?count=21")170-171-172-@pytest.mark.asyncio173-async def test_too_many_redirects_calling_next():174- client = RedirectAdapter(MockDispatch())175- url = "https://example.org/multiple_redirects?count=21"176- response = await client.request("GET", url, allow_redirects=False)177- with pytest.raises(TooManyRedirects):178- while response.is_redirect:179- response = await response.next()180-181-182-@pytest.mark.asyncio183-async def test_redirect_loop():184- client = RedirectAdapter(MockDispatch())185- with pytest.raises(RedirectLoop):186- await client.request("GET", "https://example.org/redirect_loop")187-188-189-@pytest.mark.asyncio190-async def test_redirect_loop_calling_next():191- client = RedirectAdapter(MockDispatch())192- url = "https://example.org/redirect_loop"193- response = await client.request("GET", url, allow_redirects=False)194- with pytest.raises(RedirectLoop):195- while response.is_redirect:196- response = await response.next()197-198-199-@pytest.mark.asyncio200-async def test_cross_domain_redirect():201- client = RedirectAdapter(MockDispatch())202- url = "https://example.com/cross_domain"203- headers = {"Authorization": "abc"}204- response = await client.request("GET", url, headers=headers)205- data = json.loads(response.content.decode())206- assert response.url == URL("https://example.org/cross_domain_target")207- assert data == {"headers": {}}208-209-210-@pytest.mark.asyncio211-async def test_same_domain_redirect():212- client = RedirectAdapter(MockDispatch())213- url = "https://example.org/cross_domain"214- headers = {"Authorization": "abc"}215- response = await client.request("GET", url, headers=headers)216- data = json.loads(response.content.decode())217- assert response.url == URL("https://example.org/cross_domain_target")218- assert data == {"headers": {"authorization": "abc"}}219-220-221-@pytest.mark.asyncio222-async def test_body_redirect():223- client = RedirectAdapter(MockDispatch())224- url = "https://example.org/redirect_body"225- data = b"Example request body"226- response = await client.request("POST", url, data=data)227- data = json.loads(response.content.decode())228- assert response.url == URL("https://example.org/redirect_body_target")229- assert data == {"body": "Example request body"}230-231-232-@pytest.mark.asyncio233-async def test_cannot_redirect_streaming_body():234- client = RedirectAdapter(MockDispatch())235- url = "https://example.org/redirect_body"236-237- async def streaming_body():238- yield b"Example request body"239-240- with pytest.raises(RedirectBodyUnavailable):241- await client.request("POST", url, data=streaming_body())added:tests/client/test_client.py+67 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.text == "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, data=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+ body = await response.read()29+ assert body == b"Hello, world!"30+ assert response.content == b"Hello, world!"31+32+33+@pytest.mark.asyncio34+async def test_access_content_stream_response(server):35+ async with httpcore.Client() as client:36+ response = await client.request("GET", "http://127.0.0.1:8000/", stream=True)37+ assert response.status_code == 20038+ with pytest.raises(httpcore.ResponseNotRead):39+ response.content40+41+42+@pytest.mark.asyncio43+async def test_stream_request(server):44+ async def hello_world():45+ yield b"Hello, "46+ yield b"world!"47+48+ async with httpcore.Client() as client:49+ response = await client.request(50+ "POST", "http://127.0.0.1:8000/", data=hello_world()51+ )52+ assert response.status_code == 20053+54+55+@pytest.mark.asyncio56+async def test_raise_for_status(server):57+ async with httpcore.Client() as client:58+ for status_code in (200, 400, 404, 500, 505):59+ response = await client.request(60+ "GET", f"http://127.0.0.1:8000/status/{status_code}"61+ )62+63+ if 400 <= status_code < 600:64+ with pytest.raises(httpcore.exceptions.HttpError):65+ response.raise_for_status()66+ else:67+ assert response.raise_for_status() is Noneadded:tests/client/test_redirects.py+246 added
1+import json2+from urllib.parse import parse_qs3+4+import pytest5+6+from httpcore import (7+ URL,8+ Client,9+ Dispatcher,10+ RedirectBodyUnavailable,11+ RedirectLoop,12+ Request,13+ Response,14+ SSLConfig,15+ TimeoutConfig,16+ TooManyRedirects,17+ codes,18+)19+20+21+class MockDispatch(Dispatcher):22+ async def send(23+ self,24+ request: Request,25+ stream: bool = False,26+ ssl: SSLConfig = None,27+ timeout: TimeoutConfig = None,28+ ) -> Response:29+ if request.url.path == "/redirect_301":30+ status_code = codes.moved_permanently31+ headers = {"location": "https://example.org/"}32+ return Response(status_code, headers=headers, request=request)33+34+ elif request.url.path == "/redirect_302":35+ status_code = codes.found36+ headers = {"location": "https://example.org/"}37+ return Response(status_code, headers=headers, request=request)38+39+ elif request.url.path == "/redirect_303":40+ status_code = codes.see_other41+ headers = {"location": "https://example.org/"}42+ return Response(status_code, headers=headers, request=request)43+44+ elif request.url.path == "/relative_redirect":45+ headers = {"location": "/"}46+ return Response(codes.see_other, headers=headers, request=request)47+48+ elif request.url.path == "/no_scheme_redirect":49+ headers = {"location": "//example.org/"}50+ return Response(codes.see_other, headers=headers, request=request)51+52+ elif request.url.path == "/multiple_redirects":53+ params = parse_qs(request.url.query)54+ count = int(params.get("count", "0")[0])55+ redirect_count = count - 156+ code = codes.see_other if count else codes.ok57+ location = "/multiple_redirects"58+ if redirect_count:59+ location += "?count=" + str(redirect_count)60+ headers = {"location": location} if count else {}61+ return Response(code, headers=headers, request=request)62+63+ if request.url.path == "/redirect_loop":64+ headers = {"location": "/redirect_loop"}65+ return Response(codes.see_other, headers=headers, request=request)66+67+ elif request.url.path == "/cross_domain":68+ headers = {"location": "https://example.org/cross_domain_target"}69+ return Response(codes.see_other, headers=headers, request=request)70+71+ elif request.url.path == "/cross_domain_target":72+ headers = dict(request.headers.items())73+ content = json.dumps({"headers": headers}).encode()74+ return Response(codes.ok, content=content, request=request)75+76+ elif request.url.path == "/redirect_body":77+ await request.read()78+ headers = {"location": "/redirect_body_target"}79+ return Response(codes.permanent_redirect, headers=headers, request=request)80+81+ elif request.url.path == "/redirect_body_target":82+ content = await request.read()83+ body = json.dumps({"body": content.decode()}).encode()84+ return Response(codes.ok, content=body, request=request)85+86+ return Response(codes.ok, content=b"Hello, world!", request=request)87+88+89+@pytest.mark.asyncio90+async def test_redirect_301():91+ client = Client(dispatch=MockDispatch())92+ response = await client.request("POST", "https://example.org/redirect_301")93+ assert response.status_code == codes.ok94+ assert response.url == URL("https://example.org/")95+ assert len(response.history) == 196+97+98+@pytest.mark.asyncio99+async def test_redirect_302():100+ client = Client(dispatch=MockDispatch())101+ response = await client.request("POST", "https://example.org/redirect_302")102+ assert response.status_code == codes.ok103+ assert response.url == URL("https://example.org/")104+ assert len(response.history) == 1105+106+107+@pytest.mark.asyncio108+async def test_redirect_303():109+ client = Client(dispatch=MockDispatch())110+ response = await client.request("GET", "https://example.org/redirect_303")111+ assert response.status_code == codes.ok112+ assert response.url == URL("https://example.org/")113+ assert len(response.history) == 1114+115+116+@pytest.mark.asyncio117+async def test_disallow_redirects():118+ client = Client(dispatch=MockDispatch())119+ response = await client.request(120+ "POST", "https://example.org/redirect_303", allow_redirects=False121+ )122+ assert response.status_code == codes.see_other123+ assert response.url == URL("https://example.org/redirect_303")124+ assert len(response.history) == 0125+126+ response = await response.next()127+ assert response.status_code == codes.ok128+ assert response.url == URL("https://example.org/")129+ assert len(response.history) == 1130+131+132+@pytest.mark.asyncio133+async def test_relative_redirect():134+ client = Client(dispatch=MockDispatch())135+ response = await client.request("GET", "https://example.org/relative_redirect")136+ assert response.status_code == codes.ok137+ assert response.url == URL("https://example.org/")138+ assert len(response.history) == 1139+140+141+@pytest.mark.asyncio142+async def test_no_scheme_redirect():143+ client = Client(dispatch=MockDispatch())144+ response = await client.request("GET", "https://example.org/no_scheme_redirect")145+ assert response.status_code == codes.ok146+ assert response.url == URL("https://example.org/")147+ assert len(response.history) == 1148+149+150+@pytest.mark.asyncio151+async def test_fragment_redirect():152+ client = Client(dispatch=MockDispatch())153+ url = "https://example.org/relative_redirect#fragment"154+ response = await client.request("GET", url)155+ assert response.status_code == codes.ok156+ assert response.url == URL("https://example.org/#fragment")157+ assert len(response.history) == 1158+159+160+@pytest.mark.asyncio161+async def test_multiple_redirects():162+ client = Client(dispatch=MockDispatch())163+ url = "https://example.org/multiple_redirects?count=20"164+ response = await client.request("GET", url)165+ assert response.status_code == codes.ok166+ assert response.url == URL("https://example.org/multiple_redirects")167+ assert len(response.history) == 20168+169+170+@pytest.mark.asyncio171+async def test_too_many_redirects():172+ client = Client(dispatch=MockDispatch())173+ with pytest.raises(TooManyRedirects):174+ await client.request("GET", "https://example.org/multiple_redirects?count=21")175+176+177+@pytest.mark.asyncio178+async def test_too_many_redirects_calling_next():179+ client = Client(dispatch=MockDispatch())180+ url = "https://example.org/multiple_redirects?count=21"181+ response = await client.request("GET", url, allow_redirects=False)182+ with pytest.raises(TooManyRedirects):183+ while response.is_redirect:184+ response = await response.next()185+186+187+@pytest.mark.asyncio188+async def test_redirect_loop():189+ client = Client(dispatch=MockDispatch())190+ with pytest.raises(RedirectLoop):191+ await client.request("GET", "https://example.org/redirect_loop")192+193+194+@pytest.mark.asyncio195+async def test_redirect_loop_calling_next():196+ client = Client(dispatch=MockDispatch())197+ url = "https://example.org/redirect_loop"198+ response = await client.request("GET", url, allow_redirects=False)199+ with pytest.raises(RedirectLoop):200+ while response.is_redirect:201+ response = await response.next()202+203+204+@pytest.mark.asyncio205+async def test_cross_domain_redirect():206+ client = Client(dispatch=MockDispatch())207+ url = "https://example.com/cross_domain"208+ headers = {"Authorization": "abc"}209+ response = await client.request("GET", url, headers=headers)210+ data = json.loads(response.content.decode())211+ assert response.url == URL("https://example.org/cross_domain_target")212+ assert "authorization" not in data["headers"]213+214+215+@pytest.mark.asyncio216+async def test_same_domain_redirect():217+ client = Client(dispatch=MockDispatch())218+ url = "https://example.org/cross_domain"219+ headers = {"Authorization": "abc"}220+ response = await client.request("GET", url, headers=headers)221+ data = json.loads(response.content.decode())222+ assert response.url == URL("https://example.org/cross_domain_target")223+ assert data["headers"]["authorization"] == "abc"224+225+226+@pytest.mark.asyncio227+async def test_body_redirect():228+ client = Client(dispatch=MockDispatch())229+ url = "https://example.org/redirect_body"230+ data = b"Example request body"231+ response = await client.request("POST", url, data=data)232+ data = json.loads(response.content.decode())233+ assert response.url == URL("https://example.org/redirect_body_target")234+ assert data == {"body": "Example request body"}235+236+237+@pytest.mark.asyncio238+async def test_cannot_redirect_streaming_body():239+ client = Client(dispatch=MockDispatch())240+ url = "https://example.org/redirect_body"241+242+ async def streaming_body():243+ yield b"Example request body"244+245+ with pytest.raises(RedirectBodyUnavailable):246+ await client.request("POST", url, data=streaming_body())modified:tests/dispatch/test_connections.py+9 added-7 removed
1 import pytest2 3-import httpcore3+from httpcore import HTTPConnection, Request4 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/")8+ conn = HTTPConnection(origin="http://127.0.0.1:8000/")9+ request = Request("GET", "http://127.0.0.1:8000/")10+ request.prepare()11+ response = await conn.send(request)12 assert response.status_code == 20013 assert response.content == b"Hello, world!"14 15 16 @pytest.mark.asyncio17 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- )18+ conn = HTTPConnection(origin="http://127.0.0.1:8000/")19+ request = Request("GET", "http://127.0.0.1:8000/", data=b"Hello, world!")20+ request.prepare()21+ response = await conn.send(request)22 assert response.status_code == 200modified:tests/dispatch/test_http2.py+28 added-10 removed
3 unmodified lines4 import h2.connection5 import h2.events6 import pytest7 8-import httpcore8+from httpcore import BaseReader, BaseWriter, HTTP2Connection, Request9 10 11-class MockServer(httpcore.BaseReader, httpcore.BaseWriter):11+class MockServer(BaseReader, BaseWriter):12 """13 This class exposes Reader and Writer style interfaces14 """15 65 unmodified lines81 82 @pytest.mark.asyncio83 async def test_http2_get_request():84 server = MockServer()85- async with httpcore.HTTP2Connection(reader=server, writer=server) as conn:86- response = await conn.request("GET", "http://example.org")85+ conn = HTTP2Connection(reader=server, writer=server)86+ request = Request("GET", "http://example.org")87+ request.prepare()88+89+ response = await conn.send(request)90+91 assert response.status_code == 20092 assert json.loads(response.content) == {"method": "GET", "path": "/", "body": ""}93 94 95 @pytest.mark.asyncio96 async def test_http2_post_request():97 server = MockServer()94- async with httpcore.HTTP2Connection(reader=server, writer=server) as conn:95- response = await conn.request("POST", "http://example.org", data=b"<data>")98+ conn = HTTP2Connection(reader=server, writer=server)99+ request = Request("POST", "http://example.org", data=b"<data>")100+ request.prepare()101+102+ response = await conn.send(request)103+104 assert response.status_code == 200105 assert json.loads(response.content) == {106 "method": "POST",107 "path": "/",3 unmodified lines111 112 @pytest.mark.asyncio113 async def test_http2_multiple_requests():114 server = MockServer()107- async with httpcore.HTTP2Connection(reader=server, writer=server) as conn:108- response_1 = await conn.request("GET", "http://example.org/1")109- response_2 = await conn.request("GET", "http://example.org/2")110- response_3 = await conn.request("GET", "http://example.org/3")115+ conn = HTTP2Connection(reader=server, writer=server)116+ request_1 = Request("GET", "http://example.org/1")117+ request_2 = Request("GET", "http://example.org/2")118+ request_3 = Request("GET", "http://example.org/3")119 120+ request_1.prepare()121+ request_2.prepare()122+ request_3.prepare()123+124+ response_1 = await conn.send(request_1)125+ response_2 = await conn.send(request_2)126+ response_3 = await conn.send(request_3)127+128 assert response_1.status_code == 200129 assert json.loads(response_1.content) == {"method": "GET", "path": "/1", "body": ""}130 131 assert response_2.status_code == 200132 assert json.loads(response_2.content) == {"method": "GET", "path": "/2", "body": ""}133 134 assert response_3.status_code == 200135 assert json.loads(response_3.content) == {"method": "GET", "path": "/3", "body": ""}136+137+ await conn.close()deleted:tests/test_client.py-67 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.text == "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, data=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- body = await response.read()29- assert body == b"Hello, world!"30- assert response.content == b"Hello, world!"31-32-33-@pytest.mark.asyncio34-async def test_access_content_stream_response(server):35- async with httpcore.Client() as client:36- response = await client.request("GET", "http://127.0.0.1:8000/", stream=True)37- assert response.status_code == 20038- with pytest.raises(httpcore.ResponseNotRead):39- response.content40-41-42-@pytest.mark.asyncio43-async def test_stream_request(server):44- async def hello_world():45- yield b"Hello, "46- yield b"world!"47-48- async with httpcore.Client() as client:49- response = await client.request(50- "POST", "http://127.0.0.1:8000/", data=hello_world()51- )52- assert response.status_code == 20053-54-55-@pytest.mark.asyncio56-async def test_raise_for_status(server):57- async with httpcore.Client() as client:58- for status_code in (200, 400, 404, 500, 505):59- response = await client.request(60- "GET", f"http://127.0.0.1:8000/status/{status_code}"61- )62-63- if 400 <= status_code < 600:64- with pytest.raises(httpcore.exceptions.HttpError):65- response.raise_for_status()66- else:67- assert response.raise_for_status() is None