Skip to content
Myr

Merge pull request #55 from encode/drop-adapters

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Drop 'adapters'

authored by Tom Christie · committed by GitHub · parents 84b9691, d6628ca · 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

18 files+559 added−623 removed

deleted:httpcore/adapters/__init__.py-4 removed
1"""2Adapter classes layer additional behavior over the raw dispatching of the3HTTP request/response.4"""
deleted:httpcore/adapters/authentication.py-18 removed
1import typing23from ..interfaces import Adapter4from ..models import Request, Response567class AuthenticationAdapter(Adapter):8 def __init__(self, dispatch: Adapter):9 self.dispatch = dispatch1011 def prepare_request(self, request: Request) -> None:12 self.dispatch.prepare_request(request)1314 async def send(self, request: Request, **options: typing.Any) -> Response:15 return await self.dispatch.send(request, **options)1617 async def close(self) -> None:18 await self.dispatch.close()
deleted:httpcore/adapters/cookies.py-18 removed
1import typing23from ..interfaces import Adapter4from ..models import Request, Response567class CookieAdapter(Adapter):8 def __init__(self, dispatch: Adapter):9 self.dispatch = dispatch1011 def prepare_request(self, request: Request) -> None:12 self.dispatch.prepare_request(request)1314 async def send(self, request: Request, **options: typing.Any) -> Response:15 return await self.dispatch.send(request, **options)1617 async def close(self) -> None:18 await self.dispatch.close()
deleted:httpcore/adapters/environment.py-27 removed
1import typing23from ..interfaces import Adapter4from ..models import Request, Response567class EnvironmentAdapter(Adapter):8 def __init__(self, dispatch: Adapter, trust_env: bool = True):9 self.dispatch = dispatch10 self.trust_env = trust_env1112 def prepare_request(self, request: Request) -> None:13 self.dispatch.prepare_request(request)1415 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)1920 async def close(self) -> None:21 await self.dispatch.close()2223 def merge_environment_options(self, options: dict) -> None:24 """25 Add environment options.26 """27 #  TODO
deleted:httpcore/adapters/redirects.py-130 removed
1import typing23from ..config import DEFAULT_MAX_REDIRECTS4from ..constants import codes5from ..exceptions import RedirectBodyUnavailable, RedirectLoop, TooManyRedirects6from ..interfaces import Adapter7from ..models import URL, Headers, Request, Response8910class RedirectAdapter(Adapter):11 def __init__(self, dispatch: Adapter, max_redirects: int = DEFAULT_MAX_REDIRECTS):12 self.dispatch = dispatch13 self.max_redirects = max_redirects1415 def prepare_request(self, request: Request) -> None:16 self.dispatch.prepare_request(request)1718 async def send(self, request: Request, **options: typing.Any) -> Response:19 allow_redirects = options.pop("allow_redirects", True) # type: bool2021 # 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]2526 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()3334 response = await self.dispatch.send(request, **options)35 response.history = list(history)36 if not response.is_redirect:37 break3839 history.insert(0, response)40 seen_urls.add(request.url)4142 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"] = history4849 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 response5455 response.next = send_next # type: ignore56 break5758 return response5960 async def close(self) -> None:61 await self.dispatch.close()6263 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)6970 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.method7677 # https://tools.ietf.org/html/rfc7231#section-6.4.478 if response.status_code == codes.see_other and method != "HEAD":79 method = "GET"8081 # 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"8586 # 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"9091 return method9293 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"]9899 url = URL(location, allow_relative=True)100101 # 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)105106 # 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)109110 return url111112 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 headers121122 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.content
modified:httpcore/dispatch/connection_pool.py+12 added-7 removed
11 unmodified lines
12 TimeoutConfig,13)14from ..decoders import ACCEPT_ENCODING15from ..exceptions import PoolTimeout16from ..interfaces import Adapter16from ..interfaces import Dispatcher17from ..models import Origin, Request, Response18from .connection import HTTPConnection1920CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]
61 unmodified lines
82 def __len__(self) -> int:83 return len(self.all)848586class ConnectionPool(Adapter):86class ConnectionPool(Dispatcher):87 def __init__(88 self,89 *,90 ssl: SSLConfig = DEFAULT_SSL_CONFIG,
12 unmodified lines
103 @property104 def num_connections(self) -> int:105 return len(self.keepalive_connections) + len(self.active_connections)106107 def prepare_request(self, request: Request) -> None:108 request.prepare()109110 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 exc
41 unmodified lines
modified:httpcore/dispatch/connection.py+23 added-14 removed
11 unmodified lines
12 TimeoutConfig,13)14from ..constants import Protocol15from ..exceptions import ConnectTimeout16from ..interfaces import Adapter16from ..interfaces import Dispatcher17from ..models import Origin, Request, Response18from .http2 import HTTP2Connection19from .http11 import HTTP11Connection2021# Callback signature: async def callback(conn: HTTPConnection) -> None22ReleaseCallback = typing.Callable[["HTTPConnection"], typing.Awaitable[None]]232425class HTTPConnection(Adapter):25class HTTPConnection(Dispatcher):26 def __init__(27 self,28 origin: typing.Union[str, Origin],29 ssl: SSLConfig = DEFAULT_SSL_CONFIG,
6 unmodified lines
36 self.release_func = release_func37 self.h11_connection = None # type: typing.Optional[HTTP11Connection]38 self.h2_connection = None # type: typing.Optional[HTTP2Connection]3940 def prepare_request(self, request: Request) -> None:41 request.prepare()4243 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)4950 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 )5960 return response6155 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.timeout6970 host = self.origin.host71 port = self.origin.port72 ssl_context = await ssl.load_ssl_context() if self.origin.is_ssl else None
31 unmodified lines
modified:httpcore/dispatch/http11.py+5 added-10 removed
7 unmodified lines
8 SSLConfig,9 TimeoutConfig,10)11from ..exceptions import ConnectTimeout, ReadTimeout12from ..interfaces import Adapter, BaseReader, BaseWriter12from ..interfaces import BaseReader, BaseWriter, Dispatcher13from ..models import Request, Response1415H11Event = typing.Union[16 h11.Request,
12 unmodified lines
29# the `ConnectionPool.release_connection(conn: HTTPConnection)` method.30OnReleaseCallback = typing.Callable[[], typing.Awaitable[None]]313233class HTTP11Connection(Adapter):33class HTTP11Connection:34 READ_NUM_BYTES = 40963536 def __init__(37 self,
5 unmodified lines
43 self.writer = writer44 self.on_release = on_release45 self.h11_state = h11.Connection(our_role=h11.CLIENT)4647 def prepare_request(self, request: Request) -> None:48 request.prepare()4950 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)5447 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.raw
89 unmodified lines
modified:httpcore/dispatch/http2.py+5 added-10 removed
9 unmodified lines
10 SSLConfig,11 TimeoutConfig,12)13from ..exceptions import ConnectTimeout, ReadTimeout14from ..interfaces import Adapter, BaseReader, BaseWriter14from ..interfaces import BaseReader, BaseWriter, Dispatcher15from ..models import Request, Response1617OptionalTimeout = typing.Optional[TimeoutConfig]181920class HTTP2Connection(Adapter):20class HTTP2Connection:21 READ_NUM_BYTES = 40962223 def __init__(24 self, reader: BaseReader, writer: BaseWriter, on_release: typing.Callable = None
4 unmodified lines
29 self.h2_state = h2.connection.H2Connection()30 self.events = {} # type: typing.Dict[int, typing.List[h2.events.Event]]31 self.initialized = False3233 def prepare_request(self, request: Request) -> None:34 request.prepare()3536 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)4033 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 lines
modified:httpcore/__init__.py+1 added-2 removed
1from .adapters.redirects import RedirectAdapter1from .backends.sync import SyncClient2from .client import Client3from .config import PoolLimits, SSLConfig, TimeoutConfig4from .constants import Protocol, codes
15 unmodified lines
20 StreamConsumed,21 Timeout,22 TooManyRedirects,23)25from .interfaces import Adapter, BaseReader, BaseWriter24from .interfaces import BaseReader, BaseWriter, Dispatcher25from .models import URL, Headers, Origin, QueryParams, Request, Response2627__version__ = "0.2.1"
modified:httpcore/client.py+146 added-50 removed
1import typing2from types import TracebackType34from .adapters.authentication import AuthenticationAdapter5from .adapters.cookies import CookieAdapter6from .adapters.environment import EnvironmentAdapter7from .adapters.redirects import RedirectAdapter4from .config import (5 DEFAULT_MAX_REDIRECTS,6 DEFAULT_POOL_LIMITS,7 DEFAULT_SSL_CONFIG,
1 unmodified line
9 PoolLimits,10 SSLConfig,11 TimeoutConfig,12)13from .constants import codes14from .dispatch.connection_pool import ConnectionPool15from .exceptions import RedirectBodyUnavailable, RedirectLoop, TooManyRedirects16from .interfaces import Dispatcher17from .models import (18 URL,19 Headers,20 HeaderTypes,21 QueryParamTypes,22 Request,23 RequestData,
8 unmodified lines
32 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)4047 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 = dispatch4344 async def get(45 self,46 url: URLTypes,
155 unmodified lines
202 ssl=ssl,203 timeout=timeout,204 )205206 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 response231232 def prepare_request(self, request: Request) -> None:236 self.adapter.prepare_request(request)233 request.prepare()234235 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 = []247252 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()255257 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 break263264 if allow_redirects:265 request = self.build_redirect_request(request, response)266 else:267268 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 response280281 response.next = send_next # type: ignore282 break283284 return response285286 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)292293 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.method299300 # https://tools.ietf.org/html/rfc7231#section-6.4.4301 if response.status_code == codes.see_other and method != "HEAD":302 method = "GET"303304 # 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"308309 # 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"313314 return method315316 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"]321322 url = URL(location, allow_relative=True)323324 # 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)328329 # 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)332333 return url334335 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 headers344345 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.content354355 async def close(self) -> None:260 await self.adapter.close()356 await self.dispatch.close()357358 async def __aenter__(self) -> "Client":359 return self360
7 unmodified lines
modified:httpcore/interfaces.py+17 added-8 removed
1import typing2from types import TracebackType34from .config import TimeoutConfig4from .config import SSLConfig, TimeoutConfig5from .models import (6 URL,7 Headers,8 HeaderTypes,9 QueryParamTypes,10 Request,11 RequestData,
3 unmodified lines
1516OptionalTimeout = typing.Optional[TimeoutConfig]171818class Adapter:19class Dispatcher:20 """21 The base class for all adapter or dispatcher classes.2223 Stubs out the interface, as well as providing a `.request()` convienence
8 unmodified lines
32 *,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 response4647 def prepare_request(self, request: Request) -> None:45 raise NotImplementedError() # pragma: nocover48 request.prepare()4947 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: nocover5859 async def close(self) -> None:51 raise NotImplementedError() # pragma: nocover60 pass # pragma: nocover6153 async def __aenter__(self) -> "Adapter":62 async def __aenter__(self) -> "Dispatcher":63 return self6465 async def __aexit__(66 self,
47 unmodified lines
deleted:tests/adapters/test_redirects.py-241 removed
1import json2from urllib.parse import parse_qs34import pytest56from httpcore import (7 URL,8 Adapter,9 RedirectAdapter,10 RedirectBodyUnavailable,11 RedirectLoop,12 Request,13 Response,14 TooManyRedirects,15 codes,16)171819class MockDispatch(Adapter):20 def prepare_request(self, request: Request) -> None:21 pass2223 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)2829 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)3334 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)3839 elif request.url.path == "/relative_redirect":40 headers = {"location": "/"}41 return Response(codes.see_other, headers=headers, request=request)4243 elif request.url.path == "/no_scheme_redirect":44 headers = {"location": "//example.org/"}45 return Response(codes.see_other, headers=headers, request=request)4647 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)5758 if request.url.path == "/redirect_loop":59 headers = {"location": "/redirect_loop"}60 return Response(codes.see_other, headers=headers, request=request)6162 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)6566 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)7071 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)7576 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)8081 return Response(codes.ok, content=b"Hello, world!", request=request)828384@pytest.mark.asyncio85async 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) == 1919293@pytest.mark.asyncio94async 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) == 1100101102@pytest.mark.asyncio103async 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) == 1109110111@pytest.mark.asyncio112async 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) == 0120121 response = await response.next()122 assert response.status_code == codes.ok123 assert response.url == URL("https://example.org/")124 assert len(response.history) == 1125126127@pytest.mark.asyncio128async 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) == 1134135136@pytest.mark.asyncio137async 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) == 1143144145@pytest.mark.asyncio146async 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) == 1153154155@pytest.mark.asyncio156async 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) == 20163164165@pytest.mark.asyncio166async 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")170171172@pytest.mark.asyncio173async 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()180181182@pytest.mark.asyncio183async def test_redirect_loop():184 client = RedirectAdapter(MockDispatch())185 with pytest.raises(RedirectLoop):186 await client.request("GET", "https://example.org/redirect_loop")187188189@pytest.mark.asyncio190async 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()197198199@pytest.mark.asyncio200async 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": {}}208209210@pytest.mark.asyncio211async 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"}}219220221@pytest.mark.asyncio222async 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"}230231232@pytest.mark.asyncio233async def test_cannot_redirect_streaming_body():234 client = RedirectAdapter(MockDispatch())235 url = "https://example.org/redirect_body"236237 async def streaming_body():238 yield b"Example request body"239240 with pytest.raises(RedirectBodyUnavailable):241 await client.request("POST", url, data=streaming_body())
added:tests/client/test_client.py+67 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.text == "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, data=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 body = await response.read()29 assert body == b"Hello, world!"30 assert response.content == b"Hello, world!"313233@pytest.mark.asyncio34async 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.content404142@pytest.mark.asyncio43async def test_stream_request(server):44 async def hello_world():45 yield b"Hello, "46 yield b"world!"4748 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 == 200535455@pytest.mark.asyncio56async 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 )6263 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
added:tests/client/test_redirects.py+246 added
1import json2from urllib.parse import parse_qs34import pytest56from 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)192021class 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)3334 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)3839 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)4344 elif request.url.path == "/relative_redirect":45 headers = {"location": "/"}46 return Response(codes.see_other, headers=headers, request=request)4748 elif request.url.path == "/no_scheme_redirect":49 headers = {"location": "//example.org/"}50 return Response(codes.see_other, headers=headers, request=request)5152 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)6263 if request.url.path == "/redirect_loop":64 headers = {"location": "/redirect_loop"}65 return Response(codes.see_other, headers=headers, request=request)6667 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)7071 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)7576 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)8081 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)8586 return Response(codes.ok, content=b"Hello, world!", request=request)878889@pytest.mark.asyncio90async 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) == 1969798@pytest.mark.asyncio99async 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) == 1105106107@pytest.mark.asyncio108async 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) == 1114115116@pytest.mark.asyncio117async 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) == 0125126 response = await response.next()127 assert response.status_code == codes.ok128 assert response.url == URL("https://example.org/")129 assert len(response.history) == 1130131132@pytest.mark.asyncio133async 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) == 1139140141@pytest.mark.asyncio142async 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) == 1148149150@pytest.mark.asyncio151async 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) == 1158159160@pytest.mark.asyncio161async 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) == 20168169170@pytest.mark.asyncio171async 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")175176177@pytest.mark.asyncio178async 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()185186187@pytest.mark.asyncio188async def test_redirect_loop():189 client = Client(dispatch=MockDispatch())190 with pytest.raises(RedirectLoop):191 await client.request("GET", "https://example.org/redirect_loop")192193194@pytest.mark.asyncio195async 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()202203204@pytest.mark.asyncio205async 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"]213214215@pytest.mark.asyncio216async 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"224225226@pytest.mark.asyncio227async 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"}235236237@pytest.mark.asyncio238async def test_cannot_redirect_streaming_body():239 client = Client(dispatch=MockDispatch())240 url = "https://example.org/redirect_body"241242 async def streaming_body():243 yield b"Example request body"244245 with pytest.raises(RedirectBodyUnavailable):246 await client.request("POST", url, data=streaming_body())
modified:tests/dispatch/test_connections.py+9 added-7 removed
1import pytest23import httpcore3from httpcore import HTTPConnection, Request456@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/")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!"141516@pytest.mark.asyncio17async 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 == 200
modified:tests/dispatch/test_http2.py+28 added-10 removed
3 unmodified lines
4import h2.connection5import h2.events6import pytest78import httpcore8from httpcore import BaseReader, BaseWriter, HTTP2Connection, Request91011class MockServer(httpcore.BaseReader, httpcore.BaseWriter):11class MockServer(BaseReader, BaseWriter):12 """13 This class exposes Reader and Writer style interfaces14 """15
65 unmodified lines
8182@pytest.mark.asyncio83async 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()8889 response = await conn.send(request)9091 assert response.status_code == 20092 assert json.loads(response.content) == {"method": "GET", "path": "/", "body": ""}939495@pytest.mark.asyncio96async 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()101102 response = await conn.send(request)103104 assert response.status_code == 200105 assert json.loads(response.content) == {106 "method": "POST",107 "path": "/",
3 unmodified lines
111112@pytest.mark.asyncio113async 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")119120 request_1.prepare()121 request_2.prepare()122 request_3.prepare()123124 response_1 = await conn.send(request_1)125 response_2 = await conn.send(request_2)126 response_3 = await conn.send(request_3)127128 assert response_1.status_code == 200129 assert json.loads(response_1.content) == {"method": "GET", "path": "/1", "body": ""}130131 assert response_2.status_code == 200132 assert json.loads(response_2.content) == {"method": "GET", "path": "/2", "body": ""}133134 assert response_3.status_code == 200135 assert json.loads(response_3.content) == {"method": "GET", "path": "/3", "body": ""}136137 await conn.close()
deleted:tests/test_client.py-67 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.text == "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, data=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 body = await response.read()29 assert body == b"Hello, world!"30 assert response.content == b"Hello, world!"313233@pytest.mark.asyncio34async 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.content404142@pytest.mark.asyncio43async def test_stream_request(server):44 async def hello_world():45 yield b"Hello, "46 yield b"world!"4748 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 == 200535455@pytest.mark.asyncio56async 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 )6263 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