Httpcore interface (#804)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* First pass as switching dispatchers over to httpcore interface * Updates for httpcore interface * headers in dispatch API as plain list of bytes * Integrate against httpcore 0.6 * Integrate against httpcore interface * Drop UDS, since not supported by httpcore * Fix base class for mock dispatchers in tests * Merge master and mark as potential '0.13.dev0' release
authored by Tom Christie · committed by GitHub · parent 631ba97 · Browse files · 35 files·+561 added−2457 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
35 files+561 added−2457 removed
- tests:+283 added−1121 removed
- other:+278 added−1336 removed
Provenance
- Commit
3046e92- Tree
acda447- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
631ba97
35 files changed+561 added−2457 removed
modified:httpx/_dispatch/asgi.py+32 added-27 removed
1-import typing1+from typing import Callable, Dict, List, Optional, Tuple2 3-from .._config import TimeoutTypes3+import httpcore4+5 from .._content_streams import ByteStream5-from .._models import Request, Response6-from .base import AsyncDispatcher6 7 9-class ASGIDispatch(AsyncDispatcher):8+class ASGIDispatch(httpcore.AsyncHTTPTransport):9 """10 A custom AsyncDispatcher that handles sending requests directly to an ASGI app.11 The simplest way to use this functionality is to use the `app` argument.12 26 unmodified lines39 """40 41 def __init__(42 self,44- app: typing.Callable,43+ app: Callable,44 raise_app_exceptions: bool = True,45 root_path: str = "",47- client: typing.Tuple[str, int] = ("127.0.0.1", 123),46+ client: Tuple[str, int] = ("127.0.0.1", 123),47 ) -> None:48 self.app = app49 self.raise_app_exceptions = raise_app_exceptions50 self.root_path = root_path51 self.client = client52 54- async def send(self, request: Request, timeout: TimeoutTypes = None) -> Response:53+ async def request(54+ self,55+ method: bytes,56+ url: Tuple[bytes, bytes, int, bytes],57+ headers: List[Tuple[bytes, bytes]] = None,58+ stream: httpcore.AsyncByteStream = None,59+ timeout: Dict[str, Optional[float]] = None,60+ ) -> Tuple[bytes, int, bytes, List[Tuple[bytes, bytes]], httpcore.AsyncByteStream]:61+ scheme, host, port, full_path = url62+ path, _, query = full_path.partition(b"?")63 scope = {64 "type": "http",65 "asgi": {"version": "3.0"},66 "http_version": "1.1",59- "method": request.method,60- "headers": request.headers.raw,61- "scheme": request.url.scheme,62- "path": request.url.path,63- "query_string": request.url.query.encode("ascii"),64- "server": request.url.host,67+ "method": method.decode(),68+ "headers": headers,69+ "scheme": scheme.decode("ascii"),70+ "path": path.decode("ascii"),71+ "query_string": query,72+ "server": (host.decode("ascii"), port),73 "client": self.client,74 "root_path": self.root_path,75 }76 status_code = None69- headers = None77+ response_headers = None78 body_parts = []79 response_started = False80 response_complete = False81 74- request_body_chunks = request.stream.__aiter__()82+ headers = [] if headers is None else headers83+ stream = ByteStream(b"") if stream is None else stream84 85+ request_body_chunks = stream.__aiter__()86+87 async def receive() -> dict:88 try:89 body = await request_body_chunks.__anext__()90 except StopAsyncIteration:91 return {"type": "http.request", "body": b"", "more_body": False}92 return {"type": "http.request", "body": body, "more_body": True}93 94 async def send(message: dict) -> None:84- nonlocal status_code, headers, body_parts95+ nonlocal status_code, response_headers, body_parts96 nonlocal response_started, response_complete97 98 if message["type"] == "http.response.start":99 assert not response_started100 101 status_code = message["status"]91- headers = message.get("headers", [])102+ response_headers = message.get("headers", [])103 response_started = True104 105 elif message["type"] == "http.response.body":106 assert not response_complete107 body = message.get("body", b"")108 more_body = message.get("more_body", False)109 99- if body and request.method != "HEAD":110+ if body and method != b"HEAD":111 body_parts.append(body)112 113 if not more_body:114 response_complete = True5 unmodified lines120 raise121 122 assert response_complete123 assert status_code is not None113- assert headers is not None124+ assert response_headers is not None125 126 stream = ByteStream(b"".join(body_parts))127 117- return Response(118- status_code=status_code,119- http_version="HTTP/1.1",120- headers=headers,121- stream=stream,122- request=request,123- )128+ return (b"HTTP/1.1", status_code, b"", response_headers, stream)deleted:httpx/_dispatch/base.py-64 removed
1-import typing2-from types import TracebackType3-4-from .._config import Timeout5-from .._models import (6- HeaderTypes,7- QueryParamTypes,8- Request,9- RequestData,10- Response,11- URLTypes,12-)13-14-15-class SyncDispatcher:16- """17- Base class for Dispatcher classes, that handle sending the request.18- """19-20- def send(self, request: Request, timeout: Timeout = None) -> Response:21- raise NotImplementedError() # pragma: nocover22-23- def close(self) -> None:24- pass # pragma: nocover25-26-27-class AsyncDispatcher:28- """29- Base class for AsyncDispatcher classes, that handle sending the request.30-31- Stubs out the interface, as well as providing a `.request()` convenience32- implementation, to make it easy to use or test stand-alone AsyncDispatchers,33- without requiring a complete `AsyncClient` instance.34- """35-36- async def request(37- self,38- method: str,39- url: URLTypes,40- *,41- data: RequestData = b"",42- params: QueryParamTypes = None,43- headers: HeaderTypes = None,44- timeout: Timeout = None,45- ) -> Response:46- request = Request(method, url, data=data, params=params, headers=headers)47- return await self.send(request, timeout=timeout)48-49- async def send(self, request: Request, timeout: Timeout = None) -> Response:50- raise NotImplementedError() # pragma: nocover51-52- async def close(self) -> None:53- pass # pragma: nocover54-55- async def __aenter__(self) -> "AsyncDispatcher":56- return self57-58- async def __aexit__(59- self,60- exc_type: typing.Type[BaseException] = None,61- exc_value: BaseException = None,62- traceback: TracebackType = None,63- ) -> None:64- await self.close()deleted:httpx/_dispatch/connection_pool.py-221 removed
1-import typing2-3-from .._backends.base import BaseSemaphore, ConcurrencyBackend, lookup_backend4-from .._config import (5- DEFAULT_POOL_LIMITS,6- CertTypes,7- PoolLimits,8- SSLConfig,9- Timeout,10- VerifyTypes,11-)12-from .._exceptions import PoolTimeout13-from .._models import Origin, Request, Response14-from .._utils import get_logger15-from .base import AsyncDispatcher16-from .connection import HTTPConnection17-18-CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]19-20-21-logger = get_logger(__name__)22-23-24-class NullSemaphore(BaseSemaphore):25- async def acquire(self, timeout: float = None) -> None:26- return27-28- def release(self) -> None:29- return30-31-32-class ConnectionStore:33- """34- We need to maintain collections of connections in a way that allows us to:35-36- * Lookup connections by origin.37- * Iterate over connections by insertion time.38- * Return the total number of connections.39- """40-41- def __init__(self) -> None:42- self.all: typing.Dict[HTTPConnection, float] = {}43- self.by_origin: typing.Dict[Origin, typing.Dict[HTTPConnection, float]] = {}44-45- def pop_by_origin(46- self, origin: Origin, http2_only: bool = False47- ) -> typing.Optional[HTTPConnection]:48- try:49- connections = self.by_origin[origin]50- except KeyError:51- return None52-53- connection = next(reversed(list(connections.keys())))54- if http2_only and not connection.is_http2:55- return None56-57- del connections[connection]58- if not connections:59- del self.by_origin[origin]60- del self.all[connection]61-62- return connection63-64- def add(self, connection: HTTPConnection) -> None:65- self.all[connection] = 0.066- try:67- self.by_origin[connection.origin][connection] = 0.068- except KeyError:69- self.by_origin[connection.origin] = {connection: 0.0}70-71- def remove(self, connection: HTTPConnection) -> None:72- del self.all[connection]73- del self.by_origin[connection.origin][connection]74- if not self.by_origin[connection.origin]:75- del self.by_origin[connection.origin]76-77- def clear(self) -> None:78- self.all.clear()79- self.by_origin.clear()80-81- def __iter__(self) -> typing.Iterator[HTTPConnection]:82- return iter(self.all.keys())83-84- def __len__(self) -> int:85- return len(self.all)86-87-88-class ConnectionPool(AsyncDispatcher):89- KEEP_ALIVE_EXPIRY = 5.090-91- def __init__(92- self,93- *,94- verify: VerifyTypes = True,95- cert: CertTypes = None,96- trust_env: bool = None,97- pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,98- http2: bool = False,99- backend: typing.Union[str, ConcurrencyBackend] = "auto",100- uds: typing.Optional[str] = None,101- ):102- self.ssl = SSLConfig(verify=verify, cert=cert, trust_env=trust_env, http2=http2)103- self.pool_limits = pool_limits104- self.is_closed = False105- self.uds = uds106-107- self.keepalive_connections = ConnectionStore()108- self.active_connections = ConnectionStore()109-110- self.backend = lookup_backend(backend)111- self.next_keepalive_check = 0.0112-113- @property114- def max_connections(self) -> BaseSemaphore:115- # We do this lazily, to make sure backend autodetection always116- # runs within an async context.117- if not hasattr(self, "_max_connections"):118- limit = self.pool_limits.hard_limit119- if limit:120- self._max_connections = self.backend.create_semaphore(121- limit, exc_class=PoolTimeout122- )123- else:124- self._max_connections = NullSemaphore()125-126- return self._max_connections127-128- @property129- def num_connections(self) -> int:130- return len(self.keepalive_connections) + len(self.active_connections)131-132- async def check_keepalive_expiry(self) -> None:133- now = self.backend.time()134- if now < self.next_keepalive_check:135- return136- self.next_keepalive_check = now + 1.0137-138- # Iterate through all the keep alive connections.139- # We create a list here to avoid any 'changed during iteration' errors.140- keepalives = list(self.keepalive_connections.all.keys())141- for connection in keepalives:142- if connection.expires_at is not None and now > connection.expires_at:143- self.keepalive_connections.remove(connection)144- self.max_connections.release()145- await connection.close()146-147- async def send(self, request: Request, timeout: Timeout = None) -> Response:148- await self.check_keepalive_expiry()149- connection = await self.acquire_connection(150- origin=Origin(request.url), timeout=timeout151- )152- try:153- response = await connection.send(request, timeout=timeout)154- except BaseException as exc:155- self.active_connections.remove(connection)156- self.max_connections.release()157- raise exc158-159- return response160-161- async def acquire_connection(162- self, origin: Origin, timeout: Timeout = None163- ) -> HTTPConnection:164- logger.trace(f"acquire_connection origin={origin!r}")165- connection = self.pop_connection(origin)166-167- if connection is None:168- pool_timeout = None if timeout is None else timeout.pool_timeout169-170- await self.max_connections.acquire(timeout=pool_timeout)171- connection = HTTPConnection(172- origin,173- ssl=self.ssl,174- backend=self.backend,175- release_func=self.release_connection,176- uds=self.uds,177- )178- logger.trace(f"new_connection connection={connection!r}")179- else:180- logger.trace(f"reuse_connection connection={connection!r}")181-182- self.active_connections.add(connection)183-184- return connection185-186- async def release_connection(self, connection: HTTPConnection) -> None:187- logger.trace(f"release_connection connection={connection!r}")188- if connection.is_closed:189- self.active_connections.remove(connection)190- self.max_connections.release()191- elif (192- self.pool_limits.soft_limit is not None193- and self.num_connections > self.pool_limits.soft_limit194- ):195- self.active_connections.remove(connection)196- self.max_connections.release()197- await connection.close()198- else:199- now = self.backend.time()200- connection.expires_at = now + self.KEEP_ALIVE_EXPIRY201- self.active_connections.remove(connection)202- self.keepalive_connections.add(connection)203-204- async def close(self) -> None:205- self.is_closed = True206- connections = list(self.keepalive_connections)207- self.keepalive_connections.clear()208- for connection in connections:209- self.max_connections.release()210- await connection.close()211-212- def pop_connection(self, origin: Origin) -> typing.Optional[HTTPConnection]:213- connection = self.active_connections.pop_by_origin(origin, http2_only=True)214- if connection is None:215- connection = self.keepalive_connections.pop_by_origin(origin)216-217- if connection is not None and connection.is_connection_dropped():218- self.max_connections.release()219- connection = None220-221- return connectiondeleted:httpx/_dispatch/connection.py-149 removed
1-import functools2-import typing3-4-import h115-6-from .._backends.base import ConcurrencyBackend, lookup_backend7-from .._config import SSLConfig, Timeout8-from .._models import URL, Origin, Request, Response9-from .._utils import get_logger10-from .base import AsyncDispatcher11-from .http2 import HTTP2Connection12-from .http11 import HTTP11Connection13-14-# Callback signature: async def callback(conn: HTTPConnection) -> None15-ReleaseCallback = typing.Callable[["HTTPConnection"], typing.Awaitable[None]]16-17-18-logger = get_logger(__name__)19-20-21-class HTTPConnection(AsyncDispatcher):22- def __init__(23- self,24- origin: typing.Union[str, Origin],25- ssl: SSLConfig = None,26- backend: typing.Union[str, ConcurrencyBackend] = "auto",27- release_func: typing.Optional[ReleaseCallback] = None,28- uds: typing.Optional[str] = None,29- ):30- self.origin = Origin(origin) if isinstance(origin, str) else origin31- self.ssl = SSLConfig() if ssl is None else ssl32- self.backend = lookup_backend(backend)33- self.release_func = release_func34- self.uds = uds35- self.connection: typing.Union[None, HTTP11Connection, HTTP2Connection] = None36- self.expires_at: typing.Optional[float] = None37-38- async def send(self, request: Request, timeout: Timeout = None) -> Response:39- timeout = Timeout() if timeout is None else timeout40-41- if self.connection is None:42- self.connection = await self.connect(timeout=timeout)43-44- return await self.connection.send(request, timeout=timeout)45-46- async def connect(47- self, timeout: Timeout48- ) -> typing.Union[HTTP11Connection, HTTP2Connection]:49- host = self.origin.host50- port = self.origin.port51- ssl_context = None if not self.origin.is_ssl else self.ssl.ssl_context52-53- if self.release_func is None:54- on_release = None55- else:56- on_release = functools.partial(self.release_func, self)57-58- if self.uds is None:59- logger.trace(60- f"start_connect tcp host={host!r} port={port!r} timeout={timeout!r}"61- )62- socket = await self.backend.open_tcp_stream(63- host, port, ssl_context, timeout64- )65- else:66- logger.trace(67- f"start_connect uds path={self.uds!r} host={host!r} timeout={timeout!r}"68- )69- socket = await self.backend.open_uds_stream(70- self.uds, host, ssl_context, timeout71- )72-73- http_version = socket.get_http_version()74- logger.trace(f"connected http_version={http_version!r}")75-76- if http_version == "HTTP/2":77- return HTTP2Connection(socket, self.backend, on_release=on_release)78- return HTTP11Connection(socket, on_release=on_release)79-80- async def tunnel_start_tls(81- self, origin: Origin, proxy_url: URL, timeout: Timeout = None,82- ) -> None:83- """84- Upgrade this connection to use TLS, assuming it represents a TCP tunnel.85- """86- timeout = Timeout() if timeout is None else timeout87-88- # First, check that we are in the correct state to start TLS, i.e. we've89- # just agreed to switch protocols with the server via HTTP/1.1.90- assert isinstance(self.connection, HTTP11Connection)91- h11_connection = self.connection92- assert h11_connection is not None93- assert h11_connection.h11_state.our_state == h11.SWITCHED_PROTOCOL94-95- # Store this information here so that we can transfer96- # it to the new internal connection object after97- # the old one goes to 'SWITCHED_PROTOCOL'.98- # Note that the negotiated 'http_version' may change after the TLS upgrade.99- http_version = "HTTP/1.1"100- socket = h11_connection.socket101- on_release = h11_connection.on_release102-103- if origin.is_ssl:104- # Pull the socket stream off the internal HTTP connection object,105- # and run start_tls().106- ssl_context = self.ssl.ssl_context107-108- logger.trace(f"tunnel_start_tls proxy_url={proxy_url!r} origin={origin!r}")109- socket = await socket.start_tls(110- hostname=origin.host, ssl_context=ssl_context, timeout=timeout111- )112- http_version = socket.get_http_version()113- logger.trace(114- f"tunnel_tls_complete "115- f"proxy_url={proxy_url!r} "116- f"origin={origin!r} "117- f"http_version={http_version!r}"118- )119- else:120- # User requested the use of a tunnel, but they're performing a plain-text121- # HTTP request. Don't try to upgrade to TLS in this case.122- pass123-124- if http_version == "HTTP/2":125- self.connection = HTTP2Connection(126- socket, self.backend, on_release=on_release127- )128- else:129- self.connection = HTTP11Connection(socket, on_release=on_release)130-131- async def close(self) -> None:132- logger.trace("close_connection")133- if self.connection is not None:134- await self.connection.close()135-136- @property137- def is_http2(self) -> bool:138- return self.connection is not None and self.connection.is_http2139-140- @property141- def is_closed(self) -> bool:142- return self.connection is not None and self.connection.is_closed143-144- def is_connection_dropped(self) -> bool:145- return self.connection is not None and self.connection.is_connection_dropped()146-147- def __repr__(self) -> str:148- class_name = self.__class__.__name__149- return f"{class_name}(origin={self.origin!r})"deleted:httpx/_dispatch/http11.py-206 removed
1-import typing2-3-import h114-5-from .._backends.base import BaseSocketStream6-from .._config import Timeout7-from .._content_streams import AsyncIteratorStream8-from .._exceptions import ConnectionClosed, ProtocolError9-from .._models import Request, Response10-from .._utils import get_logger11-12-H11Event = typing.Union[13- h11.Request,14- h11.Response,15- h11.InformationalResponse,16- h11.Data,17- h11.EndOfMessage,18- h11.ConnectionClosed,19-]20-21-22-# Callback signature: async def callback() -> None23-# In practice the callback will be a functools partial, which binds24-# the `ConnectionPool.release_connection(conn: HTTPConnection)` method.25-OnReleaseCallback = typing.Callable[[], typing.Awaitable[None]]26-27-28-logger = get_logger(__name__)29-30-31-class HTTP11Connection:32- READ_NUM_BYTES = 409633-34- def __init__(35- self,36- socket: BaseSocketStream,37- on_release: typing.Optional[OnReleaseCallback] = None,38- ):39- self.socket = socket40- self.on_release = on_release41- self.h11_state = h11.Connection(our_role=h11.CLIENT)42-43- @property44- def is_http2(self) -> bool:45- return False46-47- async def send(self, request: Request, timeout: Timeout = None) -> Response:48- timeout = Timeout() if timeout is None else timeout49-50- await self._send_request(request, timeout)51- await self._send_request_body(request, timeout)52- http_version, status_code, headers = await self._receive_response(timeout)53- stream = AsyncIteratorStream(54- aiterator=self._receive_response_data(timeout),55- close_func=self.response_closed,56- )57-58- return Response(59- status_code=status_code,60- http_version=http_version,61- headers=headers,62- stream=stream,63- request=request,64- )65-66- async def close(self) -> None:67- event = h11.ConnectionClosed()68- try:69- logger.trace(f"send_event event={event!r}")70- self.h11_state.send(event)71- except h11.LocalProtocolError: # pragma: no cover72- # Premature client disconnect73- pass74- await self.socket.close()75-76- async def _send_request(self, request: Request, timeout: Timeout) -> None:77- """78- Send the request method, URL, and headers to the network.79- """80- logger.trace(81- f"send_headers method={request.method!r} "82- f"target={request.url.full_path!r} "83- f"headers={request.headers!r}"84- )85-86- method = request.method.encode("ascii")87- target = request.url.full_path.encode("ascii")88- headers = request.headers.raw89- event = h11.Request(method=method, target=target, headers=headers)90- await self._send_event(event, timeout)91-92- async def _send_request_body(self, request: Request, timeout: Timeout) -> None:93- """94- Send the request body to the network.95- """96- try:97- # Send the request body.98- async for chunk in request.stream:99- logger.trace(f"send_data data=Data(<{len(chunk)} bytes>)")100- event = h11.Data(data=chunk)101- await self._send_event(event, timeout)102-103- # Finalize sending the request.104- event = h11.EndOfMessage()105- await self._send_event(event, timeout)106- except OSError: # pragma: nocover107- # Once we've sent the initial part of the request we don't actually108- # care about connection errors that occur when sending the body.109- # Ignore these, and defer to any exceptions on reading the response.110- self.h11_state.send_failed()111-112- async def _send_event(self, event: H11Event, timeout: Timeout) -> None:113- """114- Send a single `h11` event to the network, waiting for the data to115- drain before returning.116- """117- bytes_to_send = self.h11_state.send(event)118- await self.socket.write(bytes_to_send, timeout)119-120- async def _receive_response(121- self, timeout: Timeout122- ) -> typing.Tuple[str, int, typing.List[typing.Tuple[bytes, bytes]]]:123- """124- Read the response status and headers from the network.125- """126- while True:127- event = await self._receive_event(timeout)128- if isinstance(event, h11.InformationalResponse):129- continue130- else:131- assert isinstance(event, h11.Response)132- break # pragma: no cover133- http_version = "HTTP/%s" % event.http_version.decode("latin-1", errors="ignore")134- return http_version, event.status_code, event.headers135-136- async def _receive_response_data(137- self, timeout: Timeout138- ) -> typing.AsyncIterator[bytes]:139- """140- Read the response data from the network.141- """142- while True:143- event = await self._receive_event(timeout)144- if isinstance(event, h11.Data):145- yield bytes(event.data)146- else:147- assert isinstance(event, h11.EndOfMessage) or event is h11.PAUSED148- break # pragma: no cover149-150- async def _receive_event(self, timeout: Timeout) -> H11Event:151- """152- Read a single `h11` event, reading more data from the network if needed.153- """154- while True:155- try:156- event = self.h11_state.next_event()157- except h11.RemoteProtocolError as e:158- logger.debug(159- "h11.RemoteProtocolError exception "160- + f"their_state={self.h11_state.their_state} "161- + f"error_status_hint={e.error_status_hint}"162- )163- if self.socket.is_connection_dropped():164- raise ConnectionClosed(e)165- raise ProtocolError(e)166-167- if isinstance(event, h11.Data):168- logger.trace(f"receive_event event=Data(<{len(event.data)} bytes>)")169- else:170- logger.trace(f"receive_event event={event!r}")171-172- if event is h11.NEED_DATA:173- try:174- data = await self.socket.read(self.READ_NUM_BYTES, timeout)175- except OSError: # pragma: nocover176- data = b""177- self.h11_state.receive_data(data)178- else:179- assert event is not h11.NEED_DATA180- break # pragma: no cover181- return event182-183- async def response_closed(self) -> None:184- logger.trace(185- f"response_closed "186- f"our_state={self.h11_state.our_state!r} "187- f"their_state={self.h11_state.their_state}"188- )189- if (190- self.h11_state.our_state is h11.DONE191- and self.h11_state.their_state is h11.DONE192- ):193- # Get ready for another request/response cycle.194- self.h11_state.start_next_cycle()195- else:196- await self.close()197-198- if self.on_release is not None:199- await self.on_release()200-201- @property202- def is_closed(self) -> bool:203- return self.h11_state.our_state in (h11.CLOSED, h11.ERROR)204-205- def is_connection_dropped(self) -> bool:206- return self.socket.is_connection_dropped()deleted:httpx/_dispatch/http2.py-298 removed
1-import typing2-3-import h2.connection4-import h2.events5-from h2.config import H2Configuration6-from h2.settings import SettingCodes, Settings7-8-from .._backends.base import (9- BaseLock,10- BaseSocketStream,11- ConcurrencyBackend,12- lookup_backend,13-)14-from .._config import Timeout15-from .._content_streams import AsyncIteratorStream16-from .._exceptions import ProtocolError17-from .._models import Request, Response18-from .._utils import get_logger19-20-logger = get_logger(__name__)21-22-23-class HTTP2Connection:24- READ_NUM_BYTES = 409625- CONFIG = H2Configuration(validate_inbound_headers=False)26-27- def __init__(28- self,29- socket: BaseSocketStream,30- backend: typing.Union[str, ConcurrencyBackend] = "auto",31- on_release: typing.Callable = None,32- ):33- self.socket = socket34- self.backend = lookup_backend(backend)35- self.on_release = on_release36- self.state = h2.connection.H2Connection(config=self.CONFIG)37-38- self.streams = {} # type: typing.Dict[int, HTTP2Stream]39- self.events = {} # type: typing.Dict[int, typing.List[h2.events.Event]]40-41- self.sent_connection_init = False42-43- @property44- def is_http2(self) -> bool:45- return True46-47- @property48- def init_lock(self) -> BaseLock:49- # We do this lazily, to make sure backend autodetection always50- # runs within an async context.51- if not hasattr(self, "_initialization_lock"):52- self._initialization_lock = self.backend.create_lock()53- return self._initialization_lock54-55- async def send(self, request: Request, timeout: Timeout = None) -> Response:56- timeout = Timeout() if timeout is None else timeout57-58- async with self.init_lock:59- if not self.sent_connection_init:60- # The very first stream is responsible for initiating the connection.61- await self.send_connection_init(timeout)62- self.sent_connection_init = True63- stream_id = self.state.get_next_available_stream_id()64-65- stream = HTTP2Stream(stream_id=stream_id, connection=self)66- self.streams[stream_id] = stream67- self.events[stream_id] = []68- return await stream.send(request, timeout)69-70- async def send_connection_init(self, timeout: Timeout) -> None:71- """72- The HTTP/2 connection requires some initial setup before we can start73- using individual request/response streams on it.74- """75-76- # Need to set these manually here instead of manipulating via77- # __setitem__() otherwise the H2Connection will emit SettingsUpdate78- # frames in addition to sending the undesired defaults.79- self.state.local_settings = Settings(80- client=True,81- initial_values={82- # Disable PUSH_PROMISE frames from the server since we don't do anything83- # with them for now. Maybe when we support caching?84- SettingCodes.ENABLE_PUSH: 0,85- # These two are taken from h2 for safe defaults86- SettingCodes.MAX_CONCURRENT_STREAMS: 100,87- SettingCodes.MAX_HEADER_LIST_SIZE: 65536,88- },89- )90-91- # Some websites (*cough* Yahoo *cough*) balk at this setting being92- # present in the initial handshake since it's not defined in the original93- # RFC despite the RFC mandating ignoring settings you don't know about.94- del self.state.local_settings[h2.settings.SettingCodes.ENABLE_CONNECT_PROTOCOL]95-96- self.state.initiate_connection()97- self.state.increment_flow_control_window(2 ** 24)98- data_to_send = self.state.data_to_send()99- await self.socket.write(data_to_send, timeout)100-101- @property102- def is_closed(self) -> bool:103- return False104-105- def is_connection_dropped(self) -> bool:106- return self.socket.is_connection_dropped()107-108- async def close(self) -> None:109- await self.socket.close()110-111- async def wait_for_outgoing_flow(self, stream_id: int, timeout: Timeout) -> int:112- """113- Returns the maximum allowable outgoing flow for a given stream.114-115- If the allowable flow is zero, then waits on the network until116- WindowUpdated frames have increased the flow rate.117-118- https://tools.ietf.org/html/rfc7540#section-6.9119- """120- local_flow = self.state.local_flow_control_window(stream_id)121- connection_flow = self.state.max_outbound_frame_size122- flow = min(local_flow, connection_flow)123- while flow == 0:124- await self.receive_events(timeout)125- local_flow = self.state.local_flow_control_window(stream_id)126- connection_flow = self.state.max_outbound_frame_size127- flow = min(local_flow, connection_flow)128- return flow129-130- async def wait_for_event(self, stream_id: int, timeout: Timeout) -> h2.events.Event:131- """132- Returns the next event for a given stream.133-134- If no events are available yet, then waits on the network until135- an event is available.136- """137- while not self.events[stream_id]:138- await self.receive_events(timeout)139- return self.events[stream_id].pop(0)140-141- async def receive_events(self, timeout: Timeout) -> None:142- """143- Read some data from the network, and update the H2 state.144- """145- data = await self.socket.read(self.READ_NUM_BYTES, timeout)146- events = self.state.receive_data(data)147- for event in events:148- event_stream_id = getattr(event, "stream_id", 0)149- logger.trace(f"receive_event stream_id={event_stream_id} event={event!r}")150-151- if hasattr(event, "error_code"):152- raise ProtocolError(event)153-154- if event_stream_id in self.events:155- self.events[event_stream_id].append(event)156-157- data_to_send = self.state.data_to_send()158- await self.socket.write(data_to_send, timeout)159-160- async def send_headers(161- self,162- stream_id: int,163- headers: typing.List[typing.Tuple[bytes, bytes]],164- end_stream: bool,165- timeout: Timeout,166- ) -> None:167- self.state.send_headers(stream_id, headers, end_stream=end_stream)168- self.state.increment_flow_control_window(2 ** 24, stream_id=stream_id)169- data_to_send = self.state.data_to_send()170- await self.socket.write(data_to_send, timeout)171-172- async def send_data(self, stream_id: int, chunk: bytes, timeout: Timeout) -> None:173- self.state.send_data(stream_id, chunk)174- data_to_send = self.state.data_to_send()175- await self.socket.write(data_to_send, timeout)176-177- async def end_stream(self, stream_id: int, timeout: Timeout) -> None:178- self.state.end_stream(stream_id)179- data_to_send = self.state.data_to_send()180- await self.socket.write(data_to_send, timeout)181-182- async def acknowledge_received_data(183- self, stream_id: int, amount: int, timeout: Timeout184- ) -> None:185- self.state.acknowledge_received_data(amount, stream_id)186- data_to_send = self.state.data_to_send()187- await self.socket.write(data_to_send, timeout)188-189- async def close_stream(self, stream_id: int) -> None:190- del self.streams[stream_id]191- del self.events[stream_id]192-193- if not self.streams and self.on_release is not None:194- await self.on_release()195-196-197-class HTTP2Stream:198- def __init__(self, stream_id: int, connection: HTTP2Connection) -> None:199- self.stream_id = stream_id200- self.connection = connection201-202- async def send(self, request: Request, timeout: Timeout) -> Response:203- # Send the request.204- has_body = (205- "Content-Length" in request.headers206- or "Transfer-Encoding" in request.headers207- )208-209- await self.send_headers(request, has_body, timeout)210- if has_body:211- await self.send_body(request, timeout)212-213- # Receive the response.214- status_code, headers = await self.receive_response(timeout)215- stream = AsyncIteratorStream(216- aiterator=self.body_iter(timeout), close_func=self.close217- )218-219- return Response(220- status_code=status_code,221- http_version="HTTP/2",222- headers=headers,223- stream=stream,224- request=request,225- )226-227- async def send_headers(228- self, request: Request, has_body: bool, timeout: Timeout229- ) -> None:230- headers = [231- (b":method", request.method.encode("ascii")),232- (b":authority", request.url.authority.encode("ascii")),233- (b":scheme", request.url.scheme.encode("ascii")),234- (b":path", request.url.full_path.encode("ascii")),235- ] + [236- (k, v)237- for k, v in request.headers.raw238- if k not in (b"host", b"transfer-encoding")239- ]240- end_stream = not has_body241-242- logger.trace(243- f"send_headers "244- f"stream_id={self.stream_id} "245- f"method={request.method!r} "246- f"target={request.url.full_path!r} "247- f"headers={headers!r}"248- )249- await self.connection.send_headers(self.stream_id, headers, end_stream, timeout)250-251- async def send_body(self, request: Request, timeout: Timeout) -> None:252- logger.trace(f"send_body stream_id={self.stream_id}")253- async for data in request.stream:254- while data:255- max_flow = await self.connection.wait_for_outgoing_flow(256- self.stream_id, timeout257- )258- chunk_size = min(len(data), max_flow)259- chunk, data = data[:chunk_size], data[chunk_size:]260- await self.connection.send_data(self.stream_id, chunk, timeout)261-262- await self.connection.end_stream(self.stream_id, timeout)263-264- async def receive_response(265- self, timeout: Timeout266- ) -> typing.Tuple[int, typing.List[typing.Tuple[bytes, bytes]]]:267- """268- Read the response status and headers from the network.269- """270- while True:271- event = await self.connection.wait_for_event(self.stream_id, timeout)272- if isinstance(event, h2.events.ResponseReceived):273- break274-275- status_code = 200276- headers = []277- for k, v in event.headers:278- if k == b":status":279- status_code = int(v.decode("ascii", errors="ignore"))280- elif not k.startswith(b":"):281- headers.append((k, v))282-283- return (status_code, headers)284-285- async def body_iter(self, timeout: Timeout) -> typing.AsyncIterator[bytes]:286- while True:287- event = await self.connection.wait_for_event(self.stream_id, timeout)288- if isinstance(event, h2.events.DataReceived):289- amount = event.flow_controlled_length290- await self.connection.acknowledge_received_data(291- self.stream_id, amount, timeout292- )293- yield event.data294- elif isinstance(event, (h2.events.StreamEnded, h2.events.StreamReset)):295- break296-297- async def close(self) -> None:298- await self.connection.close_stream(self.stream_id)deleted:httpx/_dispatch/proxy_http.py-208 removed
1-import enum2-import typing3-import warnings4-from base64 import b64encode5-6-from .._backends.base import ConcurrencyBackend7-from .._config import (8- DEFAULT_POOL_LIMITS,9- CertTypes,10- PoolLimits,11- SSLConfig,12- Timeout,13- VerifyTypes,14-)15-from .._exceptions import ProxyError16-from .._models import URL, Headers, HeaderTypes, Origin, Request, Response, URLTypes17-from .._utils import get_logger18-from .connection import HTTPConnection19-from .connection_pool import ConnectionPool20-21-logger = get_logger(__name__)22-23-24-class HTTPProxyMode(enum.Enum):25- # This enum is pending deprecation in order to reduce API surface area,26- # but is currently still around for 0.8 backwards compat.27- DEFAULT = "DEFAULT"28- FORWARD_ONLY = "FORWARD_ONLY"29- TUNNEL_ONLY = "TUNNEL_ONLY"30-31-32-DEFAULT_MODE = "DEFAULT"33-FORWARD_ONLY = "FORWARD_ONLY"34-TUNNEL_ONLY = "TUNNEL_ONLY"35-36-37-class HTTPProxy(ConnectionPool):38- """A proxy that sends requests to the recipient server39- on behalf of the connecting client.40- """41-42- def __init__(43- self,44- proxy_url: URLTypes,45- *,46- proxy_headers: HeaderTypes = None,47- proxy_mode: str = "DEFAULT",48- verify: VerifyTypes = True,49- cert: CertTypes = None,50- trust_env: bool = None,51- pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,52- http2: bool = False,53- backend: typing.Union[str, ConcurrencyBackend] = "auto",54- ):55-56- if isinstance(proxy_mode, HTTPProxyMode): # pragma: nocover57- warnings.warn(58- "The 'HTTPProxyMode' enum is pending deprecation. "59- "Use a plain string instead. proxy_mode='FORWARD_ONLY', or "60- "proxy_mode='TUNNEL_ONLY'."61- )62- proxy_mode = proxy_mode.value63- assert proxy_mode in ("DEFAULT", "FORWARD_ONLY", "TUNNEL_ONLY")64-65- self.tunnel_ssl = SSLConfig(66- verify=verify, cert=cert, trust_env=trust_env, http2=False67- )68-69- super(HTTPProxy, self).__init__(70- verify=verify,71- cert=cert,72- pool_limits=pool_limits,73- backend=backend,74- trust_env=trust_env,75- http2=http2,76- )77-78- self.proxy_url = URL(proxy_url)79- self.proxy_mode = proxy_mode80- self.proxy_headers = Headers(proxy_headers)81-82- url = self.proxy_url83- if url.username or url.password:84- self.proxy_headers.setdefault(85- "Proxy-Authorization",86- self.build_auth_header(url.username, url.password),87- )88- # Remove userinfo from the URL authority, e.g.:89- # 'username:password@proxy_host:proxy_port' -> 'proxy_host:proxy_port'90- credentials, _, authority = url.authority.rpartition("@")91- self.proxy_url = url.copy_with(authority=authority)92-93- def build_auth_header(self, username: str, password: str) -> str:94- userpass = (username.encode("utf-8"), password.encode("utf-8"))95- token = b64encode(b":".join(userpass)).decode().strip()96- return f"Basic {token}"97-98- async def acquire_connection(99- self, origin: Origin, timeout: Timeout = None100- ) -> HTTPConnection:101- if self.should_forward_origin(origin):102- logger.trace(103- f"forward_connection proxy_url={self.proxy_url!r} origin={origin!r}"104- )105- return await super().acquire_connection(Origin(self.proxy_url), timeout)106- else:107- logger.trace(108- f"tunnel_connection proxy_url={self.proxy_url!r} origin={origin!r}"109- )110- return await self.tunnel_connection(origin, timeout)111-112- async def tunnel_connection(113- self, origin: Origin, timeout: Timeout = None114- ) -> HTTPConnection:115- """Creates a new HTTPConnection via the CONNECT method116- usually reserved for proxying HTTPS connections.117- """118- connection = self.pop_connection(origin)119-120- if connection is None:121- connection = await self.request_tunnel_proxy_connection(origin)122-123- # After we receive the 2XX response from the proxy that our124- # tunnel is open we switch the connection's origin125- # to the original so the tunnel can be re-used.126- self.active_connections.remove(connection)127- connection.origin = origin128- self.active_connections.add(connection)129-130- await connection.tunnel_start_tls(131- origin=origin, proxy_url=self.proxy_url, timeout=timeout,132- )133- else:134- self.active_connections.add(connection)135-136- return connection137-138- async def request_tunnel_proxy_connection(self, origin: Origin) -> HTTPConnection:139- """Creates an HTTPConnection by setting up a TCP tunnel"""140- proxy_headers = self.proxy_headers.copy()141- proxy_headers.setdefault("Accept", "*/*")142- proxy_request = Request(143- method="CONNECT", url=self.proxy_url.copy_with(), headers=proxy_headers144- )145- proxy_request.url.full_path = f"{origin.host}:{origin.port}"146-147- await self.max_connections.acquire()148-149- connection = HTTPConnection(150- Origin(self.proxy_url),151- ssl=self.tunnel_ssl,152- backend=self.backend,153- release_func=self.release_connection,154- )155- self.active_connections.add(connection)156-157- # See if our tunnel has been opened successfully158- proxy_response = await connection.send(proxy_request)159- logger.trace(160- f"tunnel_response "161- f"proxy_url={self.proxy_url!r} "162- f"origin={origin!r} "163- f"response={proxy_response!r}"164- )165- if not (200 <= proxy_response.status_code <= 299):166- await proxy_response.aread()167- raise ProxyError(168- f"Non-2XX response received from HTTP proxy "169- f"({proxy_response.status_code})",170- request=proxy_request,171- response=proxy_response,172- )173- else:174- # Hack to ingest the response, without closing it.175- async for chunk in proxy_response._raw_stream:176- pass177-178- return connection179-180- def should_forward_origin(self, origin: Origin) -> bool:181- """Determines if the given origin should182- be forwarded or tunneled. If 'proxy_mode' is 'DEFAULT'183- then the proxy will forward all 'HTTP' requests and184- tunnel all 'HTTPS' requests.185- """186- return (187- self.proxy_mode == DEFAULT_MODE and not origin.is_ssl188- ) or self.proxy_mode == FORWARD_ONLY189-190- async def send(self, request: Request, timeout: Timeout = None) -> Response:191- if self.should_forward_origin(Origin(request.url)):192- # Change the request to have the target URL193- # as its full_path and switch the proxy URL194- # for where the request will be sent.195- target_url = str(request.url)196- request.url = self.proxy_url.copy_with()197- request.url.full_path = target_url198- for name, value in self.proxy_headers.items():199- request.headers.setdefault(name, value)200-201- return await super().send(request=request, timeout=timeout)202-203- def __repr__(self) -> str:204- return (205- f"HTTPProxy(proxy_url={self.proxy_url!r} "206- f"proxy_headers={self.proxy_headers!r} "207- f"proxy_mode={self.proxy_mode!r})"208- )modified:httpx/_dispatch/urllib3.py+60 added-27 removed
1 import math2 import socket3 import ssl4-import typing4+from typing import Dict, Iterator, List, Optional, Tuple, Union5 6+import httpcore7 import urllib38 from urllib3.exceptions import MaxRetryError, SSLError9 10 from .._config import (1 unmodified line12 CertTypes,13 PoolLimits,14 Proxy,15 SSLConfig,15- Timeout,16 VerifyTypes,17 )18-from .._content_streams import IteratorStream19-from .._models import Request, Response18+from .._content_streams import ByteStream, IteratorStream19 from .._utils import as_network_error21-from .base import SyncDispatcher20 21 24-class URLLib3Dispatcher(SyncDispatcher):22+class URLLib3Dispatcher(httpcore.SyncHTTPTransport):23 def __init__(24 self,25 *,26 proxy: Proxy = None,32 unmodified lines59 )60 61 def init_pool_manager(62 self,65- proxy: typing.Optional[Proxy],63+ proxy: Optional[Proxy],64 ssl_context: ssl.SSLContext,65 num_pools: int,66 maxsize: int,67 block: bool,70- ) -> typing.Union[urllib3.PoolManager, urllib3.ProxyManager]:68+ ) -> Union[urllib3.PoolManager, urllib3.ProxyManager]:69 if proxy is None:70 return urllib3.PoolManager(71 ssl_context=ssl_context,72 num_pools=num_pools,9 unmodified lines82 maxsize=maxsize,83 block=block,84 )85 88- def send(self, request: Request, timeout: Timeout = None) -> Response:89- timeout = Timeout() if timeout is None else timeout86+ def request(87+ self,88+ method: bytes,89+ url: Tuple[bytes, bytes, int, bytes],90+ headers: List[Tuple[bytes, bytes]] = None,91+ stream: httpcore.SyncByteStream = None,92+ timeout: Dict[str, Optional[float]] = None,93+ ) -> Tuple[bytes, int, bytes, List[Tuple[bytes, bytes]], httpcore.SyncByteStream]:94+ headers = [] if headers is None else headers95+ stream = ByteStream(b"") if stream is None else stream96+ timeout = {} if timeout is None else timeout97+98 urllib3_timeout = urllib3.util.Timeout(91- connect=timeout.connect_timeout, read=timeout.read_timeout99+ connect=timeout.get("connect"), read=timeout.get("read")100 )93- chunked = request.headers.get("Transfer-Encoding") == "chunked"94- content_length = int(request.headers.get("Content-Length", "0"))95- body = request.stream if chunked or content_length else None101 102+ chunked = False103+ content_length = 0104+ for header_key, header_value in headers:105+ header_key = header_key.lower()106+ if header_key == b"transfer-encoding":107+ chunked = header_value == b"chunked"108+ if header_key == b"content-length":109+ content_length = int(header_value.decode("ascii"))110+ body = stream if chunked or content_length else None111+112+ scheme, host, port, path = url113+ default_scheme = {80: b"http", 443: "https"}.get(port)114+ if scheme == default_scheme:115+ url_str = "%s://%s%s" % (116+ scheme.decode("ascii"),117+ host.decode("ascii"),118+ path.decode("ascii"),119+ )120+ else:121+ url_str = "%s://%s:%d%s" % (122+ scheme.decode("ascii"),123+ host.decode("ascii"),124+ port,125+ path.decode("ascii"),126+ )127+128 with as_network_error(MaxRetryError, SSLError, socket.error):129 conn = self.pool.urlopen(99- method=request.method,100- url=str(request.url),101- headers=dict(request.headers),130+ method=method.decode(),131+ url=url_str,132+ headers=dict(133+ [134+ (key.decode("ascii"), value.decode("ascii"))135+ for key, value in headers136+ ]137+ ),138 body=body,139 redirect=False,140 assert_same_host=False,141 retries=0,142 preload_content=False,143 chunked=chunked,144 timeout=urllib3_timeout,109- pool_timeout=timeout.pool_timeout,145+ pool_timeout=timeout.get("pool"),146 )147 112- def response_bytes() -> typing.Iterator[bytes]:148+ def response_bytes() -> Iterator[bytes]:149 with as_network_error(socket.error):150 for chunk in conn.stream(4096, decode_content=False):151 yield chunk152 117- return Response(118- status_code=conn.status,119- http_version="HTTP/1.1",120- headers=list(conn.headers.items()),121- stream=IteratorStream(122- iterator=response_bytes(), close_func=conn.release_conn153+ status_code = conn.status154+ headers = list(conn.headers.items())155+ response_stream = IteratorStream(156+ iterator=response_bytes(), close_func=conn.release_conn123- ),124- request=request,157 )158+ return (b"HTTP/1.1", status_code, conn.reason, headers, response_stream)159 160 def close(self) -> None:161 self.pool.clear()modified:httpx/_dispatch/wsgi.py+42 added-24 removed
1 import io2 import itertools3 import typing4 5-from .._config import TimeoutTypes6-from .._content_streams import IteratorStream7-from .._models import Request, Response8-from .base import SyncDispatcher5+import httpcore6 7+from .._content_streams import ByteStream, IteratorStream8 9+10 def _skip_leading_empty_chunks(body: typing.Iterable) -> typing.Iterable:11 body = iter(body)12 for chunk in body:13 if chunk:14 return itertools.chain([chunk], body)15 return []16 17 19-class WSGIDispatch(SyncDispatcher):18+class WSGIDispatch(httpcore.SyncHTTPTransport):19 """21- A custom SyncDispatcher that handles sending requests directly to an WSGI app.20+ A custom transport that handles sending requests directly to an WSGI app.21 The simplest way to use this functionality is to use the `app` argument.22 23 ```24 client = httpx.Client(app=app)34 unmodified lines59 self.raise_app_exceptions = raise_app_exceptions60 self.script_name = script_name61 self.remote_addr = remote_addr62 64- def send(self, request: Request, timeout: TimeoutTypes = None) -> Response:63+ def request(64+ self,65+ method: bytes,66+ url: typing.Tuple[bytes, bytes, int, bytes],67+ headers: typing.List[typing.Tuple[bytes, bytes]] = None,68+ stream: httpcore.SyncByteStream = None,69+ timeout: typing.Dict[str, typing.Optional[float]] = None,70+ ) -> typing.Tuple[71+ bytes,72+ int,73+ bytes,74+ typing.List[typing.Tuple[bytes, bytes]],75+ httpcore.SyncByteStream,76+ ]:77+ headers = [] if headers is None else headers78+ stream = ByteStream(b"") if stream is None else stream79+80+ scheme, host, port, full_path = url81+ path, _, query = full_path.partition(b"?")82 environ = {83 "wsgi.version": (1, 0),67- "wsgi.url_scheme": request.url.scheme,68- "wsgi.input": io.BytesIO(request.read()),84+ "wsgi.url_scheme": scheme.decode("ascii"),85+ "wsgi.input": io.BytesIO(b"".join([chunk for chunk in stream])),86 "wsgi.errors": io.BytesIO(),87 "wsgi.multithread": True,88 "wsgi.multiprocess": False,89 "wsgi.run_once": False,73- "REQUEST_METHOD": request.method,90+ "REQUEST_METHOD": method.decode(),91 "SCRIPT_NAME": self.script_name,75- "PATH_INFO": request.url.path,76- "QUERY_STRING": request.url.query,77- "SERVER_NAME": request.url.host,78- "SERVER_PORT": str(request.url.port),92+ "PATH_INFO": path.decode("ascii"),93+ "QUERY_STRING": query.decode("ascii"),94+ "SERVER_NAME": host.decode("ascii"),95+ "SERVER_PORT": str(port),96 "REMOTE_ADDR": self.remote_addr,97 }81- for key, value in request.headers.items():82- key = key.upper().replace("-", "_")98+ for header_key, header_value in headers:99+ key = header_key.decode("ascii").upper().replace("-", "_")100 if key not in ("CONTENT_TYPE", "CONTENT_LENGTH"):101 key = "HTTP_" + key85- environ[key] = value102+ environ[key] = header_value.decode("ascii")103 104 seen_status = None105 seen_response_headers = None106 seen_exc_info = None15 unmodified lines122 assert seen_response_headers is not None123 if seen_exc_info and self.raise_app_exceptions:124 raise seen_exc_info[1]125 109- return Response(110- status_code=int(seen_status.split()[0]),111- http_version="HTTP/1.1",112- headers=seen_response_headers,113- stream=IteratorStream(chunk for chunk in result),114- request=request,115- )126+ status_code = int(seen_status.split()[0])127+ headers = [128+ (key.encode("ascii"), value.encode("ascii"))129+ for key, value in seen_response_headers130+ ]131+ stream = IteratorStream(chunk for chunk in result)132+133+ return (b"HTTP/1.1", status_code, b"", headers, stream)modified:httpx/__init__.py-4 removed
4 unmodified lines5 from ._config import PoolLimits, Proxy, Timeout6 from ._dispatch.asgi import ASGIDispatch7 from ._dispatch.wsgi import WSGIDispatch8 from ._exceptions import (9- ConnectionClosed,9 ConnectTimeout,10 CookieConflict,11 DecodingError,12 HTTPError,8 unmodified lines21 RequestNotRead,22 ResponseClosed,23 ResponseNotRead,24 StreamConsumed,26- TimeoutException,25 TooManyRedirects,26 WriteTimeout,27 )28 from ._models import URL, Cookies, Headers, QueryParams, Request, Response24 unmodified lines53 "Proxy",54 "Timeout",55 "ConnectTimeout",56 "CookieConflict",59- "ConnectionClosed",57 "DecodingError",58 "HTTPError",59 "InvalidURL",60 "NetworkError",14 unmodified lines75 "Cookies",76 "Headers",77 "QueryParams",78 "Request",82- "TimeoutException",79 "Response",80 "DigestAuth",81 "WSGIDispatch",82 ]modified:httpx/__version__.py+1 added-1 removed
1 __title__ = "httpx"2 __description__ = "A next generation HTTP client, for Python 3."3-__version__ = "0.12.1"3+__version__ = "0.13.dev0"modified:httpx/_client.py+106 added-51 removed
1 unmodified line2 import typing3 from types import TracebackType4 5 import hstspreload6+import httpcore7 8 from ._auth import Auth, AuthTypes, BasicAuth, FunctionAuth9 from ._config import (10 DEFAULT_MAX_REDIRECTS,3 unmodified lines14 CertTypes,15 PoolLimits,16 ProxiesTypes,17 Proxy,18+ SSLConfig,19 Timeout,20 TimeoutTypes,21 UnsetType,22 VerifyTypes,23 )24 from ._content_streams import ContentStream25 from ._dispatch.asgi import ASGIDispatch24-from ._dispatch.base import AsyncDispatcher, SyncDispatcher25-from ._dispatch.connection_pool import ConnectionPool26-from ._dispatch.proxy_http import HTTPProxy27-from ._dispatch.urllib3 import URLLib3Dispatcher26 from ._dispatch.wsgi import WSGIDispatch27 from ._exceptions import HTTPError, InvalidURL, RequestBodyUnavailable, TooManyRedirects28 from ._models import (29 URL,63 unmodified lines93 return {}94 elif isinstance(proxies, (str, URL, Proxy)):95 proxy = Proxy(url=proxies) if isinstance(proxies, (str, URL)) else proxies96 return {"all": proxy}99- elif isinstance(proxies, AsyncDispatcher): # pragma: nocover97+ elif isinstance(proxies, httpcore.AsyncHTTPTransport): # pragma: nocover98 raise RuntimeError(99 "Passing a dispatcher instance to 'proxies=' is no longer "100 "supported. Use `httpx.Proxy() instead.`"101 )2 unmodified lines104 for key, value in proxies.items():105 if isinstance(value, (str, URL, Proxy)):106 proxy = Proxy(url=value) if isinstance(value, (str, URL)) else value107 new_proxies[str(key)] = proxy110- elif isinstance(value, AsyncDispatcher): # pragma: nocover108+ elif isinstance(value, httpcore.AsyncHTTPTransport): # pragma: nocover109 raise RuntimeError(110 "Passing a dispatcher instance to 'proxies=' is "111 "no longer supported. Use `httpx.Proxy() instead.`"112 )330 unmodified lines443 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,444 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,445 max_redirects: int = DEFAULT_MAX_REDIRECTS,446 base_url: URLTypes = None,449- dispatch: SyncDispatcher = None,447+ dispatch: httpcore.SyncHTTPTransport = None,448 app: typing.Callable = None,449 trust_env: bool = True,450 ):451 super().__init__(16 unmodified lines468 dispatch=dispatch,469 app=app,470 trust_env=trust_env,471 )474- self.proxies: typing.Dict[str, SyncDispatcher] = {472+ self.proxies: typing.Dict[str, httpcore.SyncHTTPTransport] = {473 key: self.init_proxy_dispatch(474 proxy,475 verify=verify,476 cert=cert,7 unmodified lines484 self,485 verify: VerifyTypes = True,486 cert: CertTypes = None,487 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,490- dispatch: SyncDispatcher = None,488+ dispatch: httpcore.SyncHTTPTransport = None,489 app: typing.Callable = None,490 trust_env: bool = True,493- ) -> SyncDispatcher:491+ ) -> httpcore.SyncHTTPTransport:492 if dispatch is not None:493 return dispatch494 495 if app is not None:496 return WSGIDispatch(app=app)497 500- return URLLib3Dispatcher(501- verify=verify, cert=cert, pool_limits=pool_limits, trust_env=trust_env,498+ ssl_context = SSLConfig(499+ verify=verify, cert=cert, trust_env=trust_env500+ ).ssl_context501+ max_keepalive = pool_limits.soft_limit502+ max_connections = pool_limits.hard_limit503+504+ return httpcore.SyncConnectionPool(505+ ssl_context=ssl_context,506+ max_keepalive=max_keepalive,507+ max_connections=max_connections,508 )509 510 def init_proxy_dispatch(511 self,1 unmodified line513 verify: VerifyTypes = True,514 cert: CertTypes = None,515 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,516 trust_env: bool = True,511- ) -> SyncDispatcher:512- return URLLib3Dispatcher(513- proxy=proxy,514- verify=verify,515- cert=cert,516- pool_limits=pool_limits,517- trust_env=trust_env,517+ ) -> httpcore.SyncHTTPTransport:518+ ssl_context = SSLConfig(519+ verify=verify, cert=cert, trust_env=trust_env520+ ).ssl_context521+ max_keepalive = pool_limits.soft_limit522+ max_connections = pool_limits.hard_limit523+524+ return httpcore.SyncHTTPProxy(525+ proxy_origin=proxy.url.raw[:3],526+ proxy_headers=proxy.headers.raw,527+ proxy_mode=proxy.mode,528+ ssl_context=ssl_context,529+ max_keepalive=max_keepalive,530+ max_connections=max_connections,531 )532 520- def dispatcher_for_url(self, url: URL) -> SyncDispatcher:533+ def dispatcher_for_url(self, url: URL) -> httpcore.SyncHTTPTransport:534 """522- Returns the SyncDispatcher instance that should be used for a given URL.535+ Returns the transport instance that should be used for a given URL.536 This will either be the standard connection pool, or a proxy.537 """538 if self.proxies and not should_not_be_proxied(url):539 is_default_port = (url.scheme == "http" and url.port == 80) or (139 unmodified lines679 response.read()680 request = next_request681 history.append(response)682 670- def send_single_request(self, request: Request, timeout: Timeout,) -> Response:683+ def send_single_request(self, request: Request, timeout: Timeout) -> Response:684 """685 Sends a single request, without handling any redirections.686 """687 688 dispatcher = self.dispatcher_for_url(request.url)689 690 try:678- response = dispatcher.send(request, timeout=timeout)691+ (692+ http_version,693+ status_code,694+ reason_phrase,695+ headers,696+ stream,697+ ) = dispatcher.request(698+ request.method.encode(),699+ request.url.raw,700+ headers=request.headers.raw,701+ stream=request.stream,702+ timeout=timeout.as_dict(),703+ )704 except HTTPError as exc:705 # Add the original request to any HTTPError unless706 # there'a already a request attached in the case of707 # a ProxyError.708 if exc._request is None:709 exc._request = request710 raise711+ response = Response(712+ status_code,713+ http_version=http_version.decode("ascii"),714+ headers=headers,715+ stream=stream, # type: ignore716+ request=request,717+ )718 719 self.cookies.extract_cookies(response)720 721 status = f"{response.status_code} {response.reason_phrase}"237 unmodified lines959 * **app** - *(optional)* An ASGI application to send requests to,960 rather than sending actual network requests.961 * **trust_env** - *(optional)* Enables or disables usage of environment962 variables for configuration.931- * **uds** - *(optional)* A path to a Unix domain socket to connect through.963 """964 965 def __init__(966 self,9 unmodified lines976 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,977 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,978 max_redirects: int = DEFAULT_MAX_REDIRECTS,979 base_url: URLTypes = None,949- dispatch: AsyncDispatcher = None,980+ dispatch: httpcore.AsyncHTTPTransport = None,981 app: typing.Callable = None,982 trust_env: bool = True,952- uds: str = None,983 ):984 super().__init__(985 auth=auth,986 params=params,14 unmodified lines1001 pool_limits=pool_limits,1002 dispatch=dispatch,1003 app=app,1004 trust_env=trust_env,975- uds=uds,1005 )977- self.proxies: typing.Dict[str, AsyncDispatcher] = {1006+ self.proxies: typing.Dict[str, httpcore.AsyncHTTPTransport] = {1007 key: self.init_proxy_dispatch(1008 proxy,1009 verify=verify,1010 cert=cert,9 unmodified lines1020 verify: VerifyTypes = True,1021 cert: CertTypes = None,1022 http2: bool = False,1023 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,995- dispatch: AsyncDispatcher = None,1024+ dispatch: httpcore.AsyncHTTPTransport = None,1025 app: typing.Callable = None,1026 trust_env: bool = True,998- uds: str = None,999- ) -> AsyncDispatcher:1027+ ) -> httpcore.AsyncHTTPTransport:1028 if dispatch is not None:1029 return dispatch1030 1031 if app is not None:1032 return ASGIDispatch(app=app)1033 1006- return ConnectionPool(1007- verify=verify,1008- cert=cert,1034+ ssl_context = SSLConfig(1035+ verify=verify, cert=cert, trust_env=trust_env1036+ ).ssl_context1037+ max_keepalive = pool_limits.soft_limit1038+ max_connections = pool_limits.hard_limit1039+1040+ return httpcore.AsyncConnectionPool(1041+ ssl_context=ssl_context,1042+ max_keepalive=max_keepalive,1043+ max_connections=max_connections,1044 http2=http2,1010- pool_limits=pool_limits,1011- trust_env=trust_env,1012- uds=uds,1045 )1046 1047 def init_proxy_dispatch(1048 self,2 unmodified lines1051 cert: CertTypes = None,1052 http2: bool = False,1053 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,1054 trust_env: bool = True,1023- ) -> AsyncDispatcher:1024- return HTTPProxy(1025- proxy_url=proxy.url,1026- proxy_headers=proxy.headers,1055+ ) -> httpcore.AsyncHTTPTransport:1056+ ssl_context = SSLConfig(1057+ verify=verify, cert=cert, trust_env=trust_env1058+ ).ssl_context1059+ max_keepalive = pool_limits.soft_limit1060+ max_connections = pool_limits.hard_limit1061+1062+ return httpcore.AsyncHTTPProxy(1063+ proxy_origin=proxy.url.raw[:3],1064+ proxy_headers=proxy.headers.raw,1065 proxy_mode=proxy.mode,1028- verify=verify,1029- cert=cert,1030- http2=http2,1031- pool_limits=pool_limits,1032- trust_env=trust_env,1066+ ssl_context=ssl_context,1067+ max_keepalive=max_keepalive,1068+ max_connections=max_connections,1069 )1070 1035- def dispatcher_for_url(self, url: URL) -> AsyncDispatcher:1071+ def dispatcher_for_url(self, url: URL) -> httpcore.AsyncHTTPTransport:1072 """1037- Returns the AsyncDispatcher instance that should be used for a given URL.1073+ Returns the transport instance that should be used for a given URL.1074 This will either be the standard connection pool, or a proxy.1075 """1076 if self.proxies and not should_not_be_proxied(url):1077 is_default_port = (url.scheme == "http" and url.port == 80) or (150 unmodified lines1228 1229 dispatcher = self.dispatcher_for_url(request.url)1230 1231 try:1196- response = await dispatcher.send(request, timeout=timeout)1232+ (1233+ http_version,1234+ status_code,1235+ reason_phrase,1236+ headers,1237+ stream,1238+ ) = await dispatcher.request(1239+ request.method.encode(),1240+ request.url.raw,1241+ headers=request.headers.raw,1242+ stream=request.stream,1243+ timeout=timeout.as_dict(),1244+ )1245 except HTTPError as exc:1246 # Add the original request to any HTTPError unless1247 # there'a already a request attached in the case of1248 # a ProxyError.1249 if exc._request is None:1250 exc._request = request1251 raise1252+ response = Response(1253+ status_code,1254+ http_version=http_version.decode("ascii"),1255+ headers=headers,1256+ stream=stream, # type: ignore1257+ request=request,1258+ )1259 1260 self.cookies.extract_cookies(response)1261 1262 status = f"{response.status_code} {response.reason_phrase}"174 unmodified lines1437 timeout=timeout,1438 )1439 1440 async def aclose(self) -> None:1386- await self.dispatch.close()1441+ await self.dispatch.aclose()1442 for proxy in self.proxies.values():1388- await proxy.close()1443+ await proxy.aclose()1444 1445 async def __aenter__(self) -> "AsyncClient":1446 return self1447 70 unmodified linesmodified:httpx/_config.py+8 added
251 unmodified lines252 self.pool_timeout = (253 timeout if isinstance(pool_timeout, UnsetType) else pool_timeout254 )255 256+ def as_dict(self) -> typing.Dict[str, typing.Optional[float]]:257+ return {258+ "connect": self.connect_timeout,259+ "read": self.read_timeout,260+ "write": self.write_timeout,261+ "pool": self.pool_timeout,262+ }263+264 def __eq__(self, other: typing.Any) -> bool:265 return (266 isinstance(other, self.__class__)267 and self.connect_timeout == other.connect_timeout99 unmodified linesmodified:httpx/_content_streams.py+3 added-1 removed
5 unmodified lines6 from json import dumps as json_dumps7 from pathlib import Path8 from urllib.parse import urlencode9 10+import httpcore11+12 from ._exceptions import StreamConsumed13 from ._types import StrOrBytes14 from ._utils import format_form_param15 20 unmodified lines36 ],37 ]38 39 38-class ContentStream:40+class ContentStream(httpcore.AsyncByteStream, httpcore.SyncByteStream):41 def get_headers(self) -> typing.Dict[str, str]:42 """43 Return a dictionary of headers that are implied by the encoding.44 """309 unmodified linesmodified:httpx/_exceptions.py+15 added-50 removed
1 import typing2 3+import httpcore4+5 if typing.TYPE_CHECKING:6 from ._models import Request, Response # pragma: nocover7 8 18 unmodified lines27 28 29 # Timeout exceptions...30 31+ConnectTimeout = httpcore.ConnectTimeout32+ReadTimeout = httpcore.ReadTimeout33+WriteTimeout = httpcore.WriteTimeout34+PoolTimeout = httpcore.PoolTimeout35 30-class TimeoutException(HTTPError):31- """32- A base class for all timeouts.33- """36 37+# Core networking exceptions...38 36-class ConnectTimeout(TimeoutException):37- """38- Timeout while establishing a connection.39- """39+NetworkError = httpcore.NetworkError40+ReadError = httpcore.ReadError41+WriteError = httpcore.WriteError42+ConnectError = httpcore.ConnectError43+CloseError = httpcore.CloseError44 45 42-class ReadTimeout(TimeoutException):43- """44- Timeout while reading response data.45- """46+# Other transport exceptions...47 48+ProxyError = httpcore.ProxyError49+ProtocolError = httpcore.ProtocolError50 48-class WriteTimeout(TimeoutException):49- """50- Timeout while writing request data.51- """51 53-54-class PoolTimeout(TimeoutException):55- """56- Timeout while waiting to acquire a connection from the pool.57- """58-59-60-class ProxyError(HTTPError):61- """62- Error from within a proxy63- """64-65-52 # HTTP exceptions...53 54 69-class ProtocolError(HTTPError):70- """71- Malformed HTTP.72- """73-74-55 class DecodingError(HTTPError):56 """57 Decoding of the response failed.58 """59 60 81-# Network exceptions...82-83-84-class NetworkError(HTTPError):85- """86- A failure occurred while trying to access the network.87- """88-89-90-class ConnectionClosed(NetworkError):91- """92- Expected more data from peer, but connection was closed.93- """94-95-61 # Redirect exceptions...62 63 64 class RedirectError(HTTPError):76 unmodified linesmodified:httpx/_models.py+9 added
173 unmodified lines174 def fragment(self) -> str:175 return self._uri_reference.fragment or ""176 177 @property178+ def raw(self) -> typing.Tuple[bytes, bytes, int, bytes]:179+ return (180+ self.scheme.encode("ascii"),181+ self.host.encode("ascii"),182+ self.port,183+ self.full_path.encode("ascii"),184+ )185+186+ @property187 def is_ssl(self) -> bool:188 return self.scheme == "https"189 190 @property1027 unmodified linesmodified:tests/client/test_async_client.py-12 removed
146 unmodified lines147 )148 149 assert response.status_code == 200150 assert response.content == data151-152-153-@pytest.mark.usefixtures("async_environment")154-async def test_uds(uds_server):155- url = uds_server.url156- uds = uds_server.config.uds157- assert uds is not None158- async with httpx.AsyncClient(uds=uds) as client:159- response = await client.get(url)160- assert response.status_code == 200161- assert response.text == "Hello, world!"162- assert response.encoding == "iso-8859-1"modified:tests/client/test_auth.py+58 added-37 removed
1 import hashlib2-import json2 import os3 import typing4 5+import httpcore6 import pytest7 8 from httpx import (9 URL,10 AsyncClient,11 Auth,12 DigestAuth,13+ Headers,14 ProtocolError,15 Request,16 RequestBodyUnavailable,17 Response,18 )18-from httpx._config import CertTypes, TimeoutTypes, VerifyTypes19-from httpx._dispatch.base import AsyncDispatcher19+from httpx._content_streams import ContentStream, JSONStream20 21 22+def get_header_value(headers, key, default=None):23+ lookup = key.encode("ascii").lower()24+ for header_key, header_value in headers:25+ if header_key.lower() == lookup:26+ return header_value.decode("ascii")27+ return default28+29+22-class MockDispatch(AsyncDispatcher):23- def __init__(self, auth_header: str = "", status_code: int = 200) -> None:30+class MockDispatch(httpcore.AsyncHTTPTransport):31+ def __init__(self, auth_header: bytes = b"", status_code: int = 200) -> None:32 self.auth_header = auth_header33 self.status_code = status_code34 27- async def send(35+ async def request(36 self,29- request: Request,30- verify: VerifyTypes = None,31- cert: CertTypes = None,32- timeout: TimeoutTypes = None,33- ) -> Response:34- headers = [("www-authenticate", self.auth_header)] if self.auth_header else []35- body = json.dumps({"auth": request.headers.get("Authorization")}).encode()36- return Response(37- self.status_code, headers=headers, content=body, request=request37+ method: bytes,38+ url: typing.Tuple[bytes, bytes, int, bytes],39+ headers: typing.List[typing.Tuple[bytes, bytes]],40+ stream: ContentStream,41+ timeout: typing.Dict[str, typing.Optional[float]] = None,42+ ) -> typing.Tuple[43+ bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream44+ ]:45+ authorization = get_header_value(headers, "Authorization")46+ response_headers = (47+ [(b"www-authenticate", self.auth_header)] if self.auth_header else []48 )49+ response_stream = JSONStream({"auth": authorization})50+ return b"HTTP/1.1", self.status_code, b"", response_headers, response_stream51 52 41-class MockDigestAuthDispatch(AsyncDispatcher):53+class MockDigestAuthDispatch(httpcore.AsyncHTTPTransport):54 def __init__(55 self,56 algorithm: str = "SHA-256",57 send_response_after_attempt: int = 1,5 unmodified lines63 self.qop = qop64 self._regenerate_nonce = regenerate_nonce65 self._response_count = 066 55- async def send(67+ async def request(68 self,57- request: Request,58- verify: VerifyTypes = None,59- cert: CertTypes = None,60- timeout: TimeoutTypes = None,61- ) -> Response:69+ method: bytes,70+ url: typing.Tuple[bytes, bytes, int, bytes],71+ headers: typing.List[typing.Tuple[bytes, bytes]],72+ stream: ContentStream,73+ timeout: typing.Dict[str, typing.Optional[float]] = None,74+ ) -> typing.Tuple[75+ bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream76+ ]:77 if self._response_count < self.send_response_after_attempt:63- return self.challenge_send(request)78+ return self.challenge_send(method, url, headers, stream)79 65- body = json.dumps({"auth": request.headers.get("Authorization")}).encode()66- return Response(200, content=body, request=request)80+ authorization = get_header_value(headers, "Authorization")81+ body = JSONStream({"auth": authorization})82+ return b"HTTP/1.1", 200, b"", [], body83 68- def challenge_send(self, request: Request) -> Response:84+ def challenge_send(85+ self, method: bytes, url: URL, headers: Headers, stream: ContentStream,86+ ) -> typing.Tuple[int, bytes, Headers, ContentStream]:87 self._response_count += 188 nonce = (89 hashlib.sha256(os.urandom(8)).hexdigest()90 if self._regenerate_nonce14 unmodified lines105 if value106 )107 108 headers = [91- ("www-authenticate", 'Digest realm="httpx@example.org", ' + challenge_str)109+ (110+ b"www-authenticate",111+ b'Digest realm="httpx@example.org", ' + challenge_str.encode("ascii"),112+ )113 ]93- return Response(401, headers=headers, content=b"", request=request)114+ return b"HTTP/1.1", 401, b"", headers, ContentStream()115 116 117 @pytest.mark.asyncio118 async def test_basic_auth() -> None:135 unmodified lines254 @pytest.mark.asyncio255 async def test_digest_auth_200_response_including_digest_auth_header() -> None:256 url = "https://example.org/"257 auth = DigestAuth(username="tomchristie", password="password123")237- auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'258+ auth_header = b'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'259 260 client = AsyncClient(261 dispatch=MockDispatch(auth_header=auth_header, status_code=200)262 )8 unmodified lines271 async def test_digest_auth_401_response_without_digest_auth_header() -> None:272 url = "https://example.org/"273 auth = DigestAuth(username="tomchristie", password="password123")274 254- client = AsyncClient(dispatch=MockDispatch(auth_header="", status_code=401))275+ client = AsyncClient(dispatch=MockDispatch(auth_header=b"", status_code=401))276 response = await client.get(url, auth=auth)277 278 assert response.status_code == 401279 assert response.json() == {"auth": None}122 unmodified lines402 403 @pytest.mark.parametrize(404 "auth_header",405 [385- 'Digest realm="httpx@example.org", qop="auth"', # missing fields386- 'realm="httpx@example.org", qop="auth"', # not starting with Digest387- 'DigestZ realm="httpx@example.org", qop="auth"'388- 'qop="auth,auth-int",nonce="abc",opaque="xyz"',389- 'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list406+ b'Digest realm="httpx@example.org", qop="auth"', # missing fields407+ b'realm="httpx@example.org", qop="auth"', # not starting with Digest408+ b'DigestZ realm="httpx@example.org", qop="auth"'409+ b'qop="auth,auth-int",nonce="abc",opaque="xyz"',410+ b'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list411 ],412 )413 @pytest.mark.asyncio414 async def test_digest_auth_raises_protocol_error_on_malformed_header(394- auth_header: str,415+ auth_header: bytes,416 ) -> None:417 url = "https://example.org/"418 auth = DigestAuth(username="tomchristie", password="password123")419 client = AsyncClient(39 unmodified lines459 yield request460 461 url = "https://example.org/"462 auth = RepeatAuth(repeat=2)442- client = AsyncClient(dispatch=MockDispatch(auth_header="abc"))463+ client = AsyncClient(dispatch=MockDispatch(auth_header=b"abc"))464 465 response = await client.get(url, auth=auth)466 assert response.status_code == 200467 assert response.json() == {"auth": "Repeat abc.abc"}60 unmodified linesmodified:tests/client/test_cookies.py+32 added-18 removed
1-import json1+import typing2 from http.cookiejar import Cookie, CookieJar3 4+import httpcore5 import pytest6 6-from httpx import AsyncClient, Cookies, Request, Response7-from httpx._config import CertTypes, TimeoutTypes, VerifyTypes8-from httpx._dispatch.base import AsyncDispatcher7+from httpx import AsyncClient, Cookies8+from httpx._content_streams import ByteStream, ContentStream, JSONStream9 10 11-class MockDispatch(AsyncDispatcher):12- async def send(11+def get_header_value(headers, key, default=None):12+ lookup = key.encode("ascii").lower()13+ for header_key, header_value in headers:14+ if header_key.lower() == lookup:15+ return header_value.decode("ascii")16+ return default17+18+19+class MockDispatch(httpcore.AsyncHTTPTransport):20+ async def request(21 self,14- request: Request,15- verify: VerifyTypes = None,16- cert: CertTypes = None,17- timeout: TimeoutTypes = None,18- ) -> Response:19- if request.url.path.startswith("/echo_cookies"):20- body = json.dumps({"cookies": request.headers.get("Cookie")}).encode()21- return Response(200, content=body, request=request)22- elif request.url.path.startswith("/set_cookie"):23- headers = {"set-cookie": "example-name=example-value"}24- return Response(200, headers=headers, request=request)22+ method: bytes,23+ url: typing.Tuple[bytes, bytes, int, bytes],24+ headers: typing.List[typing.Tuple[bytes, bytes]],25+ stream: ContentStream,26+ timeout: typing.Dict[str, typing.Optional[float]] = None,27+ ) -> typing.Tuple[28+ bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream29+ ]:30+ host, scheme, port, path = url31+ if path.startswith(b"/echo_cookies"):32+ cookie = get_header_value(headers, "cookie")33+ body = JSONStream({"cookies": cookie})34+ return b"HTTP/1.1", 200, b"OK", [], body35+ elif path.startswith(b"/set_cookie"):36+ headers = [(b"set-cookie", b"example-name=example-value")]37+ body = ByteStream(b"")38+ return b"HTTP/1.1", 200, b"OK", headers, body39 else:26- raise NotImplementedError # pragma: no cover40+ raise NotImplementedError() # pragma: no cover41 42 43 @pytest.mark.asyncio44 async def test_set_cookie() -> None:134 unmodified linesmodified:tests/client/test_headers.py+19 added-15 removed
1 #!/usr/bin/env python32 3-import json3+import typing4 5+import httpcore6 import pytest7 7-from httpx import AsyncClient, Headers, Request, Response, __version__8-from httpx._config import CertTypes, TimeoutTypes, VerifyTypes9-from httpx._dispatch.base import AsyncDispatcher8+from httpx import AsyncClient, Headers, __version__9+from httpx._content_streams import ContentStream, JSONStream10 11 12-class MockDispatch(AsyncDispatcher):13- async def send(12+class MockDispatch(httpcore.AsyncHTTPTransport):13+ async def request(14 self,15- request: Request,16- verify: VerifyTypes = None,17- cert: CertTypes = None,18- timeout: TimeoutTypes = None,19- ) -> Response:20- if request.url.path.startswith("/echo_headers"):21- request_headers = dict(request.headers.items())22- body = json.dumps({"headers": request_headers}).encode()23- return Response(200, content=body, request=request)15+ method: bytes,16+ url: typing.Tuple[bytes, bytes, int, bytes],17+ headers: typing.List[typing.Tuple[bytes, bytes]],18+ stream: ContentStream,19+ timeout: typing.Dict[str, typing.Optional[float]] = None,20+ ) -> typing.Tuple[21+ bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream22+ ]:23+ headers_dict = dict(24+ [(key.decode("ascii"), value.decode("ascii")) for key, value in headers]25+ )26+ body = JSONStream({"headers": headers_dict})27+ return b"HTTP/1.1", 200, b"OK", [], body28 29 30 @pytest.mark.asyncio31 async def test_client_header():151 unmodified linesmodified:tests/client/test_proxies.py+3 added-3 removed
22 unmodified lines23 client = httpx.AsyncClient(proxies=proxies)24 25 for proxy_key, url in expected_proxies:26 assert proxy_key in client.proxies27- assert client.proxies[proxy_key].proxy_url == url27+ assert client.proxies[proxy_key].proxy_origin == httpx.URL(url).raw[:3]28 29 assert len(expected_proxies) == len(client.proxies)30 31 48 unmodified lines80 81 if expected is None:82 assert dispatcher is client.dispatch83 else:84- assert dispatcher.proxy_url == expected84+ assert dispatcher.proxy_origin == httpx.URL(expected).raw[:3]85 86 87 def test_unsupported_proxy_scheme():88 with pytest.raises(ValueError):25 unmodified lines114 115 if expected is None:116 assert dispatcher == client.dispatch117 else:118- assert dispatcher.proxy_url == expected118+ assert dispatcher.proxy_origin == httpx.URL(expected).raw[:3]modified:tests/client/test_queryparams.py+17 added-14 removed
1-import json1+import typing2 3+import httpcore4 import pytest5 5-from httpx import URL, AsyncClient, QueryParams, Request, Response6-from httpx._config import CertTypes, TimeoutTypes, VerifyTypes7-from httpx._dispatch.base import AsyncDispatcher6+from httpx import URL, AsyncClient, Headers, QueryParams7+from httpx._content_streams import ContentStream, JSONStream8 9 10-class MockDispatch(AsyncDispatcher):11- async def send(10+class MockDispatch(httpcore.AsyncHTTPTransport):11+ async def request(12 self,13- request: Request,14- verify: VerifyTypes = None,15- cert: CertTypes = None,16- timeout: TimeoutTypes = None,17- ) -> Response:18- if request.url.path.startswith("/echo_queryparams"):19- body = json.dumps({"ok": "ok"}).encode()20- return Response(200, content=body, request=request)13+ method: bytes,14+ url: typing.Tuple[bytes, bytes, int, bytes],15+ headers: typing.List[typing.Tuple[bytes, bytes]],16+ stream: ContentStream,17+ timeout: typing.Dict[str, typing.Optional[float]] = None,18+ ) -> typing.Tuple[19+ bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream20+ ]:21+ headers = Headers()22+ body = JSONStream({"ok": "ok"})23+ return b"HTTP/1.1", 200, b"OK", headers, body24 25 26 def test_client_queryparams():27 client = AsyncClient(params={"a": "b"})27 unmodified linesmodified:tests/client/test_redirects.py+135 added-97 removed
1 import json2+import typing3 from urllib.parse import parse_qs4 5+import httpcore6 import pytest7 8 from httpx import (9 URL,10 AsyncClient,11 NotRedirectResponse,10- Request,12 RequestBodyUnavailable,12- Response,13 TooManyRedirects,14 codes,15 )16-from httpx._config import CertTypes, TimeoutTypes, VerifyTypes17-from httpx._content_streams import AsyncIteratorStream18-from httpx._dispatch.base import AsyncDispatcher16+from httpx._content_streams import AsyncIteratorStream, ByteStream, ContentStream17 18 21-class MockDispatch(AsyncDispatcher):22- async def send(19+def get_header_value(headers, key, default=None):20+ lookup = key.encode("ascii").lower()21+ for header_key, header_value in headers:22+ if header_key.lower() == lookup:23+ return header_value.decode("ascii")24+ return default25+26+27+class MockDispatch(httpcore.AsyncHTTPTransport):28+ async def request(29 self,24- request: Request,25- verify: VerifyTypes = None,26- cert: CertTypes = None,27- timeout: TimeoutTypes = None,28- ) -> Response:29- if request.url.path == "/no_redirect":30- return Response(codes.OK, request=request)30+ method: bytes,31+ url: typing.Tuple[bytes, bytes, int, bytes],32+ headers: typing.List[typing.Tuple[bytes, bytes]],33+ stream: ContentStream,34+ timeout: typing.Dict[str, typing.Optional[float]] = None,35+ ) -> typing.Tuple[36+ bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream37+ ]:38+ scheme, host, port, path = url39+ path, _, query = path.partition(b"?")40+ if path == b"/no_redirect":41+ return b"HTTP/1.1", codes.OK, b"OK", [], ByteStream(b"")42 32- elif request.url.path == "/redirect_301":43+ elif path == b"/redirect_301":44 45 async def body():46 yield b"<a href='https://example.org/'>here</a>"47 48 status_code = codes.MOVED_PERMANENTLY38- headers = {"location": "https://example.org/"}49+ headers = [(b"location", b"https://example.org/")]50 stream = AsyncIteratorStream(aiterator=body())40- return Response(41- status_code, stream=stream, headers=headers, request=request42- )51+ return b"HTTP/1.1", status_code, b"Moved Permanently", headers, stream52 44- elif request.url.path == "/redirect_302":53+ elif path == b"/redirect_302":54 status_code = codes.FOUND46- headers = {"location": "https://example.org/"}47- return Response(status_code, headers=headers, request=request)55+ headers = [(b"location", b"https://example.org/")]56+ return b"HTTP/1.1", status_code, b"Found", headers, ByteStream(b"")57 49- elif request.url.path == "/redirect_303":58+ elif path == b"/redirect_303":59 status_code = codes.SEE_OTHER51- headers = {"location": "https://example.org/"}52- return Response(status_code, headers=headers, request=request)60+ headers = [(b"location", b"https://example.org/")]61+ return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")62 54- elif request.url.path == "/relative_redirect":55- headers = {"location": "/"}56- return Response(codes.SEE_OTHER, headers=headers, request=request)63+ elif path == b"/relative_redirect":64+ status_code = codes.SEE_OTHER65+ headers = [(b"location", b"/")]66+ return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")67 58- elif request.url.path == "/malformed_redirect":59- headers = {"location": "https://:443/"}60- return Response(codes.SEE_OTHER, headers=headers, request=request)68+ elif path == b"/malformed_redirect":69+ status_code = codes.SEE_OTHER70+ headers = [(b"location", b"https://:443/")]71+ return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")72 62- elif request.url.path == "/no_scheme_redirect":63- headers = {"location": "//example.org/"}64- return Response(codes.SEE_OTHER, headers=headers, request=request)73+ elif path == b"/no_scheme_redirect":74+ status_code = codes.SEE_OTHER75+ headers = [(b"location", b"//example.org/")]76+ return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")77 66- elif request.url.path == "/multiple_redirects":67- params = parse_qs(request.url.query)78+ elif path == b"/multiple_redirects":79+ params = parse_qs(query.decode("ascii"))80 count = int(params.get("count", "0")[0])81 redirect_count = count - 182 code = codes.SEE_OTHER if count else codes.OK83+ phrase = b"See Other" if count else b"OK"71- location = "/multiple_redirects"84+ location = b"/multiple_redirects"85 if redirect_count:73- location += "?count=" + str(redirect_count)74- headers = {"location": location} if count else {}75- return Response(code, headers=headers, request=request)86+ location += b"?count=" + str(redirect_count).encode("ascii")87+ headers = [(b"location", location)] if count else []88+ return b"HTTP/1.1", code, phrase, headers, ByteStream(b"")89 77- if request.url.path == "/redirect_loop":78- headers = {"location": "/redirect_loop"}79- return Response(codes.SEE_OTHER, headers=headers, request=request)90+ if path == b"/redirect_loop":91+ code = codes.SEE_OTHER92+ headers = [(b"location", b"/redirect_loop")]93+ return b"HTTP/1.1", code, b"See Other", headers, ByteStream(b"")94 81- elif request.url.path == "/cross_domain":82- headers = {"location": "https://example.org/cross_domain_target"}83- return Response(codes.SEE_OTHER, headers=headers, request=request)95+ elif path == b"/cross_domain":96+ code = codes.SEE_OTHER97+ headers = [(b"location", b"https://example.org/cross_domain_target")]98+ return b"HTTP/1.1", code, b"See Other", headers, ByteStream(b"")99 85- elif request.url.path == "/cross_domain_target":86- headers = dict(request.headers.items())87- content = json.dumps({"headers": headers}).encode()88- return Response(codes.OK, content=content, request=request)100+ elif path == b"/cross_domain_target":101+ headers_dict = dict(102+ [(key.decode("ascii"), value.decode("ascii")) for key, value in headers]103+ )104+ content = ByteStream(json.dumps({"headers": headers_dict}).encode())105+ return b"HTTP/1.1", 200, b"OK", [], content106 90- elif request.url.path == "/redirect_body":91- body = b"".join([part async for part in request.stream])92- headers = {"location": "/redirect_body_target"}93- return Response(codes.PERMANENT_REDIRECT, headers=headers, request=request)107+ elif path == b"/redirect_body":108+ _ = b"".join([part async for part in stream])109+ code = codes.PERMANENT_REDIRECT110+ headers = [(b"location", b"/redirect_body_target")]111+ return b"HTTP/1.1", code, b"Permanent Redirect", headers, ByteStream(b"")112 95- elif request.url.path == "/redirect_no_body":96- content = b"".join([part async for part in request.stream])97- headers = {"location": "/redirect_body_target"}98- return Response(codes.SEE_OTHER, headers=headers, request=request)113+ elif path == b"/redirect_no_body":114+ _ = b"".join([part async for part in stream])115+ code = codes.SEE_OTHER116+ headers = [(b"location", b"/redirect_body_target")]117+ return b"HTTP/1.1", code, b"See Other", headers, ByteStream(b"")118 100- elif request.url.path == "/redirect_body_target":101- content = b"".join([part async for part in request.stream])102- headers = dict(request.headers.items())103- body = json.dumps({"body": content.decode(), "headers": headers}).encode()104- return Response(codes.OK, content=body, request=request)119+ elif path == b"/redirect_body_target":120+ content = b"".join([part async for part in stream])121+ headers_dict = dict(122+ [(key.decode("ascii"), value.decode("ascii")) for key, value in headers]123+ )124+ body = ByteStream(125+ json.dumps({"body": content.decode(), "headers": headers_dict}).encode()126+ )127+ return b"HTTP/1.1", 200, b"OK", [], body128 106- elif request.url.path == "/cross_subdomain":107- if request.headers["host"] != "www.example.org":108- headers = {"location": "https://www.example.org/cross_subdomain"}109- return Response(110- codes.PERMANENT_REDIRECT, headers=headers, request=request129+ elif path == b"/cross_subdomain":130+ host = get_header_value(headers, "host")131+ if host != "www.example.org":132+ headers = [(b"location", b"https://www.example.org/cross_subdomain")]133+ return (134+ b"HTTP/1.1",135+ codes.PERMANENT_REDIRECT,136+ b"Permanent Redirect",137+ headers,138+ ByteStream(b""),139 )140 else:113- return Response(codes.OK, content=b"Hello, world!", request=request)141+ return b"HTTP/1.1", 200, b"OK", [], ByteStream(b"Hello, world!")142 115- return Response(codes.OK, content=b"Hello, world!", request=request)143+ return b"HTTP/1.1", 200, b"OK", [], ByteStream(b"Hello, world!")144 145 146 @pytest.mark.usefixtures("async_environment")147 async def test_no_redirect():205 unmodified lines353 response = await client.get(url)354 assert response.url == URL("https://www.example.org/cross_subdomain")355 356 329-class MockCookieDispatch(AsyncDispatcher):330- async def send(357+class MockCookieDispatch(httpcore.AsyncHTTPTransport):358+ async def request(359 self,332- request: Request,333- verify: VerifyTypes = None,334- cert: CertTypes = None,335- timeout: TimeoutTypes = None,336- ) -> Response:337- if request.url.path == "/":338- if "cookie" in request.headers:360+ method: bytes,361+ url: typing.Tuple[bytes, bytes, int, bytes],362+ headers: typing.List[typing.Tuple[bytes, bytes]],363+ stream: ContentStream,364+ timeout: typing.Dict[str, typing.Optional[float]] = None,365+ ) -> typing.Tuple[366+ bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream367+ ]:368+ scheme, host, port, path = url369+ if path == b"/":370+ cookie = get_header_value(headers, "Cookie")371+ if cookie is not None:372 content = b"Logged in"373 else:374 content = b"Not logged in"342- return Response(codes.OK, content=content, request=request)375+ return b"HTTP/1.1", 200, b"OK", [], ByteStream(content)376 344- elif request.url.path == "/login":377+ elif path == b"/login":378 status_code = codes.SEE_OTHER346- headers = {347- "location": "/",348- "set-cookie": (349- "session=eyJ1c2VybmFtZSI6ICJ0b21; path=/; Max-Age=1209600; "350- "httponly; samesite=lax"379+ headers = [380+ (b"location", b"/"),381+ (382+ b"set-cookie",383+ (384+ b"session=eyJ1c2VybmFtZSI6ICJ0b21; path=/; Max-Age=1209600; "385+ b"httponly; samesite=lax"386+ ),387 ),352- }388+ ]389+ return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")390 354- return Response(status_code, headers=headers, request=request)355-356- elif request.url.path == "/logout":391+ elif path == b"/logout":392 status_code = codes.SEE_OTHER358- headers = {359- "location": "/",360- "set-cookie": (361- "session=null; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; "362- "httponly; samesite=lax"393+ headers = [394+ (b"location", b"/"),395+ (396+ b"set-cookie",397+ (398+ b"session=null; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; "399+ b"httponly; samesite=lax"400+ ),401 ),364- }365- return Response(status_code, headers=headers, request=request)402+ ]403+ return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")404 405 406 @pytest.mark.usefixtures("async_environment")407 async def test_redirect_cookie_behavior():26 unmodified linesdeleted:tests/dispatch/__init__.py
deleted:tests/dispatch/test_connection_pools.py-246 removed
1-import pytest2-3-import httpx4-from httpx._dispatch.connection_pool import ConnectionPool5-6-7-@pytest.mark.usefixtures("async_environment")8-async def test_keepalive_connections(server):9- """10- Connections should default to staying in a keep-alive state.11- """12- async with ConnectionPool() as http:13- response = await http.request("GET", server.url)14- await response.aread()15- assert len(http.active_connections) == 016- assert len(http.keepalive_connections) == 117-18- response = await http.request("GET", server.url)19- await response.aread()20- assert len(http.active_connections) == 021- assert len(http.keepalive_connections) == 122-23-24-@pytest.mark.usefixtures("async_environment")25-async def test_keepalive_timeout(server):26- """27- Keep-alive connections should timeout.28- """29- async with ConnectionPool() as http:30- response = await http.request("GET", server.url)31- await response.aread()32- assert len(http.active_connections) == 033- assert len(http.keepalive_connections) == 134-35- http.next_keepalive_check = 0.036- await http.check_keepalive_expiry()37-38- assert len(http.active_connections) == 039- assert len(http.keepalive_connections) == 140-41- async with ConnectionPool() as http:42- http.KEEP_ALIVE_EXPIRY = 0.043-44- response = await http.request("GET", server.url)45- await response.aread()46- assert len(http.active_connections) == 047- assert len(http.keepalive_connections) == 148-49- http.next_keepalive_check = 0.050- await http.check_keepalive_expiry()51-52- assert len(http.active_connections) == 053- assert len(http.keepalive_connections) == 054-55-56-@pytest.mark.usefixtures("async_environment")57-async def test_differing_connection_keys(server):58- """59- Connections to differing connection keys should result in multiple connections.60- """61- async with ConnectionPool() as http:62- response = await http.request("GET", server.url)63- await response.aread()64- assert len(http.active_connections) == 065- assert len(http.keepalive_connections) == 166-67- response = await http.request("GET", "http://localhost:8000/")68- await response.aread()69- assert len(http.active_connections) == 070- assert len(http.keepalive_connections) == 271-72-73-@pytest.mark.usefixtures("async_environment")74-async def test_soft_limit(server):75- """76- The soft_limit config should limit the maximum number of keep-alive connections.77- """78- pool_limits = httpx.PoolLimits(soft_limit=1)79-80- async with ConnectionPool(pool_limits=pool_limits) as http:81- response = await http.request("GET", server.url)82- await response.aread()83- assert len(http.active_connections) == 084- assert len(http.keepalive_connections) == 185-86- response = await http.request("GET", "http://localhost:8000/")87- await response.aread()88- assert len(http.active_connections) == 089- assert len(http.keepalive_connections) == 190-91-92-@pytest.mark.usefixtures("async_environment")93-async def test_streaming_response_holds_connection(server):94- """95- A streaming request should hold the connection open until the response is read.96- """97- async with ConnectionPool() as http:98- response = await http.request("GET", server.url)99- assert len(http.active_connections) == 1100- assert len(http.keepalive_connections) == 0101-102- await response.aread()103-104- assert len(http.active_connections) == 0105- assert len(http.keepalive_connections) == 1106-107-108-@pytest.mark.usefixtures("async_environment")109-async def test_multiple_concurrent_connections(server):110- """111- Multiple concurrent requests should open multiple concurrent connections.112- """113- async with ConnectionPool() as http:114- response_a = await http.request("GET", server.url)115- assert len(http.active_connections) == 1116- assert len(http.keepalive_connections) == 0117-118- response_b = await http.request("GET", server.url)119- assert len(http.active_connections) == 2120- assert len(http.keepalive_connections) == 0121-122- await response_b.aread()123- assert len(http.active_connections) == 1124- assert len(http.keepalive_connections) == 1125-126- await response_a.aread()127- assert len(http.active_connections) == 0128- assert len(http.keepalive_connections) == 2129-130-131-@pytest.mark.usefixtures("async_environment")132-async def test_close_connections(server):133- """134- Using a `Connection: close` header should close the connection.135- """136- headers = [(b"connection", b"close")]137- async with ConnectionPool() as http:138- response = await http.request("GET", server.url, headers=headers)139- await response.aread()140- assert len(http.active_connections) == 0141- assert len(http.keepalive_connections) == 0142-143-144-@pytest.mark.usefixtures("async_environment")145-async def test_standard_response_close(server):146- """147- A standard close should keep the connection open.148- """149- async with ConnectionPool() as http:150- response = await http.request("GET", server.url)151- await response.aread()152- await response.aclose()153- assert len(http.active_connections) == 0154- assert len(http.keepalive_connections) == 1155-156-157-@pytest.mark.usefixtures("async_environment")158-async def test_premature_response_close(server):159- """160- A premature close should close the connection.161- """162- async with ConnectionPool() as http:163- response = await http.request("GET", server.url)164- await response.aclose()165- assert len(http.active_connections) == 0166- assert len(http.keepalive_connections) == 0167-168-169-@pytest.mark.usefixtures("async_environment")170-async def test_keepalive_connection_closed_by_server_is_reestablished(server):171- """172- Upon keep-alive connection closed by remote a new connection173- should be reestablished.174- """175- async with ConnectionPool() as http:176- response = await http.request("GET", server.url)177- await response.aread()178-179- # Shutdown the server to close the keep-alive connection180- await server.restart()181-182- response = await http.request("GET", server.url)183- await response.aread()184- assert len(http.active_connections) == 0185- assert len(http.keepalive_connections) == 1186-187-188-@pytest.mark.usefixtures("async_environment")189-async def test_keepalive_http2_connection_closed_by_server_is_reestablished(server):190- """191- Upon keep-alive connection closed by remote a new connection192- should be reestablished.193- """194- async with ConnectionPool() as http:195- response = await http.request("GET", server.url)196- await response.aread()197-198- # Shutdown the server to close the keep-alive connection199- await server.restart()200-201- response = await http.request("GET", server.url)202- await response.aread()203- assert len(http.active_connections) == 0204- assert len(http.keepalive_connections) == 1205-206-207-@pytest.mark.usefixtures("async_environment")208-async def test_connection_closed_free_semaphore_on_acquire(server):209- """210- Verify that max_connections semaphore is released211- properly on a disconnected connection.212- """213- async with ConnectionPool(pool_limits=httpx.PoolLimits(hard_limit=1)) as http:214- response = await http.request("GET", server.url)215- await response.aread()216-217- # Close the connection so we're forced to recycle it218- await server.restart()219-220- response = await http.request("GET", server.url)221- assert response.status_code == 200222-223-224-@pytest.mark.usefixtures("async_environment")225-async def test_connection_pool_closed_close_keepalive_and_free_semaphore(server):226- """227- Closing the connection pool should close remaining keepalive connections and228- release the max_connections semaphore.229- """230- http = ConnectionPool(pool_limits=httpx.PoolLimits(hard_limit=1))231-232- async with http:233- response = await http.request("GET", server.url)234- await response.aread()235- assert response.status_code == 200236- assert len(http.keepalive_connections) == 1237-238- assert len(http.keepalive_connections) == 0239-240- # Perform a second round of requests to make sure the max_connections semaphore241- # was released properly.242-243- async with http:244- response = await http.request("GET", server.url)245- await response.aread()246- assert response.status_code == 200deleted:tests/dispatch/test_connections.py-44 removed
1-import pytest2-3-import httpx4-from httpx._config import SSLConfig5-from httpx._dispatch.connection import HTTPConnection6-7-8-@pytest.mark.usefixtures("async_environment")9-async def test_get(server):10- async with HTTPConnection(origin=server.url) as conn:11- response = await conn.request("GET", server.url)12- await response.aread()13- assert response.status_code == 20014- assert response.content == b"Hello, world!"15-16-17-@pytest.mark.usefixtures("async_environment")18-async def test_post(server):19- async with HTTPConnection(origin=server.url) as conn:20- response = await conn.request("GET", server.url, data=b"Hello, world!")21- assert response.status_code == 20022-23-24-@pytest.mark.usefixtures("async_environment")25-async def test_premature_close(server):26- with pytest.raises(httpx.ConnectionClosed):27- async with HTTPConnection(origin=server.url) as conn:28- response = await conn.request(29- "GET", server.url.copy_with(path="/premature_close")30- )31- await response.aread()32-33-34-@pytest.mark.usefixtures("async_environment")35-async def test_https_get_with_ssl(https_server, ca_cert_pem_file):36- """37- An HTTPS request, with SSL configuration set on the client.38- """39- ssl = SSLConfig(verify=ca_cert_pem_file)40- async with HTTPConnection(origin=https_server.url, ssl=ssl) as conn:41- response = await conn.request("GET", https_server.url)42- await response.aread()43- assert response.status_code == 20044- assert response.content == b"Hello, world!"deleted:tests/dispatch/test_http2.py-158 removed
1-import json2-import socket3-4-import h2.connection5-import h2.events6-import pytest7-from h2.settings import SettingCodes8-9-from httpx import AsyncClient, Response, TimeoutException10-from httpx._dispatch.connection_pool import ConnectionPool11-12-from .utils import MockHTTP2Backend13-14-15-async def app(request):16- method = request.method17- path = request.url.path18- body = b"".join([part async for part in request.stream])19- content = json.dumps(20- {"method": method, "path": path, "body": body.decode()}21- ).encode()22- headers = {"Content-Length": str(len(content))}23- return Response(200, headers=headers, content=content, request=request)24-25-26-@pytest.mark.asyncio27-async def test_http2_get_request():28- backend = MockHTTP2Backend(app=app)29- dispatch = ConnectionPool(backend=backend, http2=True)30-31- async with AsyncClient(dispatch=dispatch) as client:32- response = await client.get("http://example.org")33-34- assert response.status_code == 20035- assert json.loads(response.content) == {"method": "GET", "path": "/", "body": ""}36-37-38-@pytest.mark.asyncio39-async def test_http2_post_request():40- backend = MockHTTP2Backend(app=app)41- dispatch = ConnectionPool(backend=backend, http2=True)42-43- async with AsyncClient(dispatch=dispatch) as client:44- response = await client.post("http://example.org", data=b"<data>")45-46- assert response.status_code == 20047- assert json.loads(response.content) == {48- "method": "POST",49- "path": "/",50- "body": "<data>",51- }52-53-54-@pytest.mark.asyncio55-async def test_http2_large_post_request():56- backend = MockHTTP2Backend(app=app)57- dispatch = ConnectionPool(backend=backend, http2=True)58-59- data = b"a" * 10000060- async with AsyncClient(dispatch=dispatch) as client:61- response = await client.post("http://example.org", data=data)62- assert response.status_code == 20063- assert json.loads(response.content) == {64- "method": "POST",65- "path": "/",66- "body": data.decode(),67- }68-69-70-@pytest.mark.asyncio71-async def test_http2_multiple_requests():72- backend = MockHTTP2Backend(app=app)73- dispatch = ConnectionPool(backend=backend, http2=True)74-75- async with AsyncClient(dispatch=dispatch) as client:76- response_1 = await client.get("http://example.org/1")77- response_2 = await client.get("http://example.org/2")78- response_3 = await client.get("http://example.org/3")79-80- assert response_1.status_code == 20081- assert json.loads(response_1.content) == {"method": "GET", "path": "/1", "body": ""}82-83- assert response_2.status_code == 20084- assert json.loads(response_2.content) == {"method": "GET", "path": "/2", "body": ""}85-86- assert response_3.status_code == 20087- assert json.loads(response_3.content) == {"method": "GET", "path": "/3", "body": ""}88-89-90-@pytest.mark.asyncio91-async def test_http2_reconnect():92- """93- If a connection has been dropped between requests, then we should94- be seemlessly reconnected.95- """96- backend = MockHTTP2Backend(app=app)97- dispatch = ConnectionPool(backend=backend, http2=True)98-99- async with AsyncClient(dispatch=dispatch) as client:100- response_1 = await client.get("http://example.org/1")101- backend.server.close_connection = True102- response_2 = await client.get("http://example.org/2")103-104- assert response_1.status_code == 200105- assert json.loads(response_1.content) == {"method": "GET", "path": "/1", "body": ""}106-107- assert response_2.status_code == 200108- assert json.loads(response_2.content) == {"method": "GET", "path": "/2", "body": ""}109-110-111-@pytest.mark.asyncio112-async def test_http2_settings_in_handshake():113- backend = MockHTTP2Backend(app=app)114- dispatch = ConnectionPool(backend=backend, http2=True)115-116- async with AsyncClient(dispatch=dispatch) as client:117- await client.get("http://example.org")118-119- h2_conn = backend.server.conn120-121- assert isinstance(h2_conn, h2.connection.H2Connection)122- expected_settings = {123- SettingCodes.HEADER_TABLE_SIZE: 4096,124- SettingCodes.ENABLE_PUSH: 0,125- SettingCodes.MAX_CONCURRENT_STREAMS: 100,126- SettingCodes.INITIAL_WINDOW_SIZE: 65535,127- SettingCodes.MAX_FRAME_SIZE: 16384,128- SettingCodes.MAX_HEADER_LIST_SIZE: 65536,129- # This one's here because h2 helpfully populates remote_settings130- # with default values even if the peer doesn't send the setting.131- SettingCodes.ENABLE_CONNECT_PROTOCOL: 0,132- }133- assert dict(h2_conn.remote_settings) == expected_settings134-135- # We don't expect the ENABLE_CONNECT_PROTOCOL to be in the handshake136- expected_settings.pop(SettingCodes.ENABLE_CONNECT_PROTOCOL)137-138- assert len(backend.server.settings_changed) == 1139- settings = backend.server.settings_changed[0]140-141- assert isinstance(settings, h2.events.RemoteSettingsChanged)142- assert len(settings.changed_settings) == len(expected_settings)143- for setting_code, changed_setting in settings.changed_settings.items():144- assert isinstance(changed_setting, h2.settings.ChangedSetting)145- assert changed_setting.new_value == expected_settings[setting_code]146-147-148-@pytest.mark.usefixtures("async_environment")149-async def test_http2_live_request():150- async with AsyncClient(http2=True) as client:151- try:152- resp = await client.get("https://nghttp2.org/httpbin/anything")153- except TimeoutException: # pragma: nocover154- pytest.xfail(reason="nghttp2.org appears to be unresponsive")155- except socket.gaierror: # pragma: nocover156- pytest.xfail(reason="You appear to be offline")157- assert resp.status_code == 200158- assert resp.http_version == "HTTP/2"deleted:tests/dispatch/test_proxy_http.py-207 removed
1-import pytest2-3-import httpx4-from httpx._dispatch.proxy_http import HTTPProxy5-6-from .utils import MockRawSocketBackend7-8-9-@pytest.mark.asyncio10-async def test_proxy_tunnel_success():11- raw_io = MockRawSocketBackend(12- data_to_send=(13- [14- b"HTTP/1.1 200 OK\r\n"15- b"Date: Sun, 10 Oct 2010 23:26:07 GMT\r\n"16- b"Server: proxy-server\r\n"17- b"\r\n",18- b"HTTP/1.1 404 Not Found\r\n"19- b"Date: Sun, 10 Oct 2010 23:26:07 GMT\r\n"20- b"Server: origin-server\r\n"21- b"\r\n",22- ]23- ),24- )25- async with HTTPProxy(26- proxy_url="http://127.0.0.1:8000", backend=raw_io, proxy_mode="TUNNEL_ONLY",27- ) as proxy:28- response = await proxy.request("GET", "http://example.com")29-30- assert response.status_code == 40431- assert response.headers["Server"] == "origin-server"32-33- assert response.request.method == "GET"34- assert response.request.url == "http://example.com"35- assert response.request.headers["Host"] == "example.com"36-37- recv = raw_io.received_data38- assert len(recv) == 339- assert recv[0] == b"--- CONNECT(127.0.0.1, 8000) ---"40- assert recv[1].startswith(41- b"CONNECT example.com:80 HTTP/1.1\r\nhost: 127.0.0.1:8000\r\n"42- )43- assert recv[2].startswith(b"GET / HTTP/1.1\r\nhost: example.com\r\n")44-45-46-@pytest.mark.asyncio47-@pytest.mark.parametrize("status_code", [300, 304, 308, 401, 500])48-async def test_proxy_tunnel_non_2xx_response(status_code):49- raw_io = MockRawSocketBackend(50- data_to_send=(51- [52- b"HTTP/1.1 %d Not Good\r\n" % status_code,53- b"Date: Sun, 10 Oct 2010 23:26:07 GMT\r\n"54- b"Server: proxy-server\r\n"55- b"\r\n",56- ]57- ),58- )59-60- with pytest.raises(httpx.ProxyError) as e:61- async with HTTPProxy(62- proxy_url="http://127.0.0.1:8000", backend=raw_io, proxy_mode="TUNNEL_ONLY",63- ) as proxy:64- await proxy.request("GET", "http://example.com")65-66- # ProxyError.request should be the CONNECT request not the original request67- assert e.value.request.method == "CONNECT"68- assert e.value.request.headers["Host"] == "127.0.0.1:8000"69- assert e.value.request.url.full_path == "example.com:80"70-71- # ProxyError.response should be the CONNECT response72- assert e.value.response.status_code == status_code73- assert e.value.response.headers["Server"] == "proxy-server"74-75- # Verify that the request wasn't sent after receiving an error from CONNECT76- recv = raw_io.received_data77- assert len(recv) == 278- assert recv[0] == b"--- CONNECT(127.0.0.1, 8000) ---"79- assert recv[1].startswith(80- b"CONNECT example.com:80 HTTP/1.1\r\nhost: 127.0.0.1:8000\r\n"81- )82-83-84-@pytest.mark.asyncio85-async def test_proxy_tunnel_start_tls():86- raw_io = MockRawSocketBackend(87- data_to_send=(88- [89- # Tunnel Response90- b"HTTP/1.1 200 OK\r\n"91- b"Date: Sun, 10 Oct 2010 23:26:07 GMT\r\n"92- b"Server: proxy-server\r\n"93- b"\r\n",94- # Response 195- b"HTTP/1.1 404 Not Found\r\n"96- b"Date: Sun, 10 Oct 2010 23:26:07 GMT\r\n"97- b"Server: origin-server\r\n"98- b"Connection: keep-alive\r\n"99- b"Content-Length: 0\r\n"100- b"\r\n",101- # Response 2102- b"HTTP/1.1 200 OK\r\n"103- b"Date: Sun, 10 Oct 2010 23:26:07 GMT\r\n"104- b"Server: origin-server\r\n"105- b"Connection: keep-alive\r\n"106- b"Content-Length: 0\r\n"107- b"\r\n",108- ]109- ),110- )111- async with HTTPProxy(112- proxy_url="http://127.0.0.1:8000", backend=raw_io, proxy_mode="TUNNEL_ONLY",113- ) as proxy:114- resp = await proxy.request("GET", "https://example.com")115-116- assert resp.status_code == 404117- assert resp.headers["Server"] == "origin-server"118-119- assert resp.request.method == "GET"120- assert resp.request.url == "https://example.com"121- assert resp.request.headers["Host"] == "example.com"122-123- await resp.aread()124-125- # Make another request to see that the tunnel is re-used.126- resp = await proxy.request("GET", "https://example.com/target")127-128- assert resp.status_code == 200129- assert resp.headers["Server"] == "origin-server"130-131- assert resp.request.method == "GET"132- assert resp.request.url == "https://example.com/target"133- assert resp.request.headers["Host"] == "example.com"134-135- await resp.aread()136-137- recv = raw_io.received_data138- assert len(recv) == 5139- assert recv[0] == b"--- CONNECT(127.0.0.1, 8000) ---"140- assert recv[1].startswith(141- b"CONNECT example.com:443 HTTP/1.1\r\nhost: 127.0.0.1:8000\r\n"142- )143- assert recv[2] == b"--- START_TLS(example.com) ---"144- assert recv[3].startswith(b"GET / HTTP/1.1\r\nhost: example.com\r\n")145- assert recv[4].startswith(b"GET /target HTTP/1.1\r\nhost: example.com\r\n")146-147-148-@pytest.mark.asyncio149-@pytest.mark.parametrize("proxy_mode", ["FORWARD_ONLY", "DEFAULT"])150-async def test_proxy_forwarding(proxy_mode):151- raw_io = MockRawSocketBackend(152- data_to_send=(153- [154- b"HTTP/1.1 200 OK\r\n"155- b"Date: Sun, 10 Oct 2010 23:26:07 GMT\r\n"156- b"Server: origin-server\r\n"157- b"\r\n"158- ]159- ),160- )161- async with HTTPProxy(162- proxy_url="http://127.0.0.1:8000",163- backend=raw_io,164- proxy_mode=proxy_mode,165- proxy_headers={"Proxy-Authorization": "test", "Override": "2"},166- ) as proxy:167- response = await proxy.request(168- "GET", "http://example.com", headers={"override": "1"}169- )170-171- assert response.status_code == 200172- assert response.headers["Server"] == "origin-server"173-174- assert response.request.method == "GET"175- assert response.request.url == "http://127.0.0.1:8000"176- assert response.request.url.full_path == "http://example.com"177- assert response.request.headers["Host"] == "example.com"178-179- recv = raw_io.received_data180- assert len(recv) == 2181- assert recv[0] == b"--- CONNECT(127.0.0.1, 8000) ---"182- assert recv[1].startswith(183- b"GET http://example.com HTTP/1.1\r\nhost: example.com\r\n"184- )185- assert b"proxy-authorization: test" in recv[1]186- assert b"override: 1" in recv[1]187-188-189-def test_proxy_url_with_username_and_password():190- proxy = HTTPProxy("http://user:password@example.com:1080")191-192- assert proxy.proxy_url == "http://example.com:1080"193- assert proxy.proxy_headers["Proxy-Authorization"] == "Basic dXNlcjpwYXNzd29yZA=="194-195-196-def test_proxy_repr():197- proxy = HTTPProxy(198- "http://127.0.0.1:1080",199- proxy_headers={"Custom": "Header"},200- proxy_mode="DEFAULT",201- )202-203- assert repr(proxy) == (204- "HTTPProxy(proxy_url=URL('http://127.0.0.1:1080') "205- "proxy_headers=Headers({'custom': 'Header'}) "206- "proxy_mode='DEFAULT')"207- )deleted:tests/dispatch/utils.py-204 removed
1-import ssl2-import typing3-4-import h2.config5-import h2.connection6-import h2.events7-8-from httpx import Request, Timeout9-from httpx._backends.base import BaseSocketStream, lookup_backend10-11-12-class MockHTTP2Backend:13- def __init__(self, app):14- self.app = app15- self.backend = lookup_backend()16- self.server = None17-18- async def open_tcp_stream(19- self,20- hostname: str,21- port: int,22- ssl_context: typing.Optional[ssl.SSLContext],23- timeout: Timeout,24- ) -> BaseSocketStream:25- self.server = MockHTTP2Server(self.app, backend=self.backend)26- return self.server27-28- # Defer all other attributes and methods to the underlying backend.29- def __getattr__(self, name: str) -> typing.Any:30- return getattr(self.backend, name)31-32-33-class MockHTTP2Server(BaseSocketStream):34- def __init__(self, app, backend: MockHTTP2Backend):35- config = h2.config.H2Configuration(client_side=False)36- self.conn = h2.connection.H2Connection(config=config)37- self.app = app38- self.backend = backend39- self.buffer = b""40- self.requests = {}41- self.close_connection = False42- self.return_data = {}43- self.settings_changed = []44-45- # Socket stream interface46-47- def get_http_version(self) -> str:48- return "HTTP/2"49-50- async def read(self, n, timeout, flag=None) -> bytes:51- send, self.buffer = self.buffer[:n], self.buffer[n:]52- return send53-54- async def write(self, data: bytes, timeout) -> None:55- if not data:56- return57- events = self.conn.receive_data(data)58- self.buffer += self.conn.data_to_send()59- for event in events:60- if isinstance(event, h2.events.RequestReceived):61- self.request_received(event.headers, event.stream_id)62- elif isinstance(event, h2.events.DataReceived):63- self.receive_data(event.data, event.stream_id)64- # This should send an UPDATE_WINDOW for both the stream and the65- # connection increasing it by the amount66- # consumed keeping the flow control window constant67- flow_control_consumed = event.flow_controlled_length68- if flow_control_consumed > 0:69- self.conn.increment_flow_control_window(flow_control_consumed)70- self.buffer += self.conn.data_to_send()71- self.conn.increment_flow_control_window(72- flow_control_consumed, event.stream_id73- )74- self.buffer += self.conn.data_to_send()75- elif isinstance(event, h2.events.StreamEnded):76- await self.stream_complete(event.stream_id)77- elif isinstance(event, h2.events.RemoteSettingsChanged):78- self.settings_changed.append(event)79-80- async def close(self) -> None:81- pass82-83- def is_connection_dropped(self) -> bool:84- return self.close_connection85-86- # Server implementation87-88- def request_received(self, headers, stream_id):89- """90- Handler for when the initial part of the HTTP request is received.91- """92- if stream_id not in self.requests:93- self.requests[stream_id] = []94- self.requests[stream_id].append({"headers": headers, "data": b""})95-96- def receive_data(self, data, stream_id):97- """98- Handler for when a data part of the HTTP request is received.99- """100- self.requests[stream_id][-1]["data"] += data101-102- async def stream_complete(self, stream_id):103- """104- Handler for when the HTTP request is completed.105- """106- request = self.requests[stream_id].pop(0)107- if not self.requests[stream_id]:108- del self.requests[stream_id]109-110- headers_dict = dict(request["headers"])111-112- method = headers_dict[b":method"].decode("ascii")113- url = "%s://%s%s" % (114- headers_dict[b":scheme"].decode("ascii"),115- headers_dict[b":authority"].decode("ascii"),116- headers_dict[b":path"].decode("ascii"),117- )118- headers = [(k, v) for k, v in request["headers"] if not k.startswith(b":")]119- data = request["data"]120-121- # Call out to the app.122- request = Request(method, url, headers=headers, data=data)123- response = await self.app(request)124-125- # Write the response to the buffer.126- status_code_bytes = str(response.status_code).encode("ascii")127- response_headers = [(b":status", status_code_bytes)] + response.headers.raw128-129- self.conn.send_headers(stream_id, response_headers)130- self.buffer += self.conn.data_to_send()131- self.return_data[stream_id] = response.content132- self.send_return_data(stream_id)133-134- def send_return_data(self, stream_id):135- while self.return_data[stream_id]:136- flow_control = self.conn.local_flow_control_window(stream_id)137- chunk_size = min(138- len(self.return_data[stream_id]),139- flow_control,140- self.conn.max_outbound_frame_size,141- )142- if chunk_size > 0:143- chunk, self.return_data[stream_id] = (144- self.return_data[stream_id][:chunk_size],145- self.return_data[stream_id][chunk_size:],146- )147- self.conn.send_data(stream_id, chunk)148- self.buffer += self.conn.data_to_send()149- self.conn.end_stream(stream_id)150- self.buffer += self.conn.data_to_send()151-152-153-class MockRawSocketBackend:154- def __init__(self, data_to_send=b""):155- self.backend = lookup_backend()156- self.data_to_send = data_to_send157- self.received_data = []158- self.stream = MockRawSocketStream(self)159-160- async def open_tcp_stream(161- self,162- hostname: str,163- port: int,164- ssl_context: typing.Optional[ssl.SSLContext],165- timeout: Timeout,166- ) -> BaseSocketStream:167- self.received_data.append(168- b"--- CONNECT(%s, %d) ---" % (hostname.encode(), port)169- )170- return self.stream171-172- # Defer all other attributes and methods to the underlying backend.173- def __getattr__(self, name: str) -> typing.Any:174- return getattr(self.backend, name)175-176-177-class MockRawSocketStream(BaseSocketStream):178- def __init__(self, backend: MockRawSocketBackend):179- self.backend = backend180-181- async def start_tls(182- self, hostname: str, ssl_context: ssl.SSLContext, timeout: Timeout183- ) -> BaseSocketStream:184- self.backend.received_data.append(b"--- START_TLS(%s) ---" % hostname.encode())185- return MockRawSocketStream(self.backend)186-187- def get_http_version(self) -> str:188- return "HTTP/1.1"189-190- async def write(self, data: bytes, timeout) -> None:191- if not data:192- return193- self.backend.received_data.append(data)194-195- async def read(self, n, timeout, flag=None) -> bytes:196- if not self.backend.data_to_send:197- return b""198- return self.backend.data_to_send.pop(0)199-200- def is_connection_dropped(self) -> bool:201- return False202-203- async def close(self) -> None:204- passmodified:tests/conftest.py-25 removed
294 unmodified lines295 yield from serve_in_thread(server)296 297 298 @pytest.fixture(scope=SERVER_SCOPE)299-def uds_server():300- uds = "test_server.sock"301- config = Config(app=app, lifespan="off", loop="asyncio", uds=uds)302- server = TestServer(config=config)303- yield from serve_in_thread(server)304- os.remove(uds)305-306-307-@pytest.fixture(scope=SERVER_SCOPE)299 def https_server(cert_pem_file, cert_private_key_file):300 config = Config(301 app=app,302 lifespan="off",4 unmodified lines307 loop="asyncio",308 )309 server = TestServer(config=config)310 yield from serve_in_thread(server)320-321-322-@pytest.fixture(scope=SERVER_SCOPE)323-def https_uds_server(cert_pem_file, cert_private_key_file):324- uds = "https_test_server.sock"325- config = Config(326- app=app,327- lifespan="off",328- ssl_certfile=cert_pem_file,329- ssl_keyfile=cert_private_key_file,330- uds=uds,331- loop="asyncio",332- )333- server = TestServer(config=config)334- yield from serve_in_thread(server)335- os.remove(uds)modified:tests/test_concurrency.py-27 removed
55 unmodified lines56 await stream.close()57 58 59 @pytest.mark.usefixtures("async_environment")60-async def test_start_tls_on_uds_socket_stream(https_uds_server):61- backend = lookup_backend()62- ctx = SSLConfig().load_ssl_context_no_verify()63- timeout = Timeout(5)64-65- stream = await backend.open_uds_stream(66- https_uds_server.config.uds, https_uds_server.url.host, None, timeout67- )68-69- try:70- assert stream.is_connection_dropped() is False71- assert get_cipher(stream) is None72-73- stream = await stream.start_tls(https_uds_server.url.host, ctx, timeout)74- assert stream.is_connection_dropped() is False75- assert get_cipher(stream) is not None76-77- await stream.write(b"GET / HTTP/1.1\r\n\r\n", timeout)78-79- response = await read_response(stream, timeout, should_contain=b"Hello, world")80- assert response.startswith(b"HTTP/1.1 200 OK\r\n")81-82- finally:83- await stream.close()84-85-86-@pytest.mark.usefixtures("async_environment")60 async def test_concurrent_read(server):61 """62 Regression test for: https://github.com/encode/httpx/issues/52763 """32 unmodified linesmodified:tests/test_multipart.py+19 added-12 removed
1 import binascii2 import cgi3 import io4 import os5+import typing6 from unittest import mock7 8+import httpcore9 import pytest10 11 import httpx10-from httpx._config import CertTypes, TimeoutTypes, VerifyTypes11-from httpx._content_streams import encode12-from httpx._dispatch.base import AsyncDispatcher12+from httpx._content_streams import AsyncIteratorStream, encode13 from httpx._utils import format_form_param14 15 16-class MockDispatch(AsyncDispatcher):17- async def send(16+class MockDispatch(httpcore.AsyncHTTPTransport):17+ async def request(18 self,19- request: httpx.Request,20- verify: VerifyTypes = None,21- cert: CertTypes = None,22- timeout: TimeoutTypes = None,23- ) -> httpx.Response:24- content = b"".join([part async for part in request.stream])25- return httpx.Response(200, content=content, request=request)19+ method: bytes,20+ url: typing.Tuple[bytes, bytes, int, bytes],21+ headers: typing.List[typing.Tuple[bytes, bytes]] = None,22+ stream: httpcore.AsyncByteStream = None,23+ timeout: typing.Dict[str, typing.Optional[float]] = None,24+ ) -> typing.Tuple[25+ bytes,26+ int,27+ bytes,28+ typing.List[typing.Tuple[bytes, bytes]],29+ httpcore.AsyncByteStream,30+ ]:31+ content = AsyncIteratorStream(aiterator=(part async for part in stream))32+ return b"HTTP/1.1", 200, b"OK", [], content33 34 35 @pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))36 @pytest.mark.asyncio169 unmodified linesmodified:tests/test_utils.py-2 removed
96 unmodified lines97 response = await client.get(server.url)98 assert response.status_code == 20099 stderr = capsys.readouterr().err100 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr101- assert "httpx._dispatch.connection_pool" not in stderr101 102 103 @pytest.mark.asyncio104 async def test_logs_trace(server, capsys):2 unmodified lines107 response = await client.get(server.url)108 assert response.status_code == 200109 stderr = capsys.readouterr().err110 assert 'HTTP Request: GET http://127.0.0.1:8000/ "HTTP/1.1 200 OK"' in stderr112- assert "httpx._dispatch.connection_pool" in stderr111 112 113 @pytest.mark.asyncio114 async def test_logs_redirect_chain(server, capsys):171 unmodified linesmodified:setup.cfg+1 added-1 removed
9 unmodified lines10 combine_as_imports = True11 force_grid_wrap = 012 include_trailing_comma = True13 known_first_party = httpx,tests14-known_third_party = brotli,certifi,chardet,cryptography,h11,h2,hstspreload,pytest,rfc3986,setuptools,sniffio,trio,trustme,urllib3,uvicorn14+known_third_party = brotli,certifi,chardet,cryptography,hstspreload,httpcore,pytest,rfc3986,setuptools,sniffio,trio,trustme,urllib3,uvicorn15 line_length = 8816 multi_line_output = 317 18 [tool:pytest]3 unmodified linesmodified:setup.py+1 added-4 removed
56 unmodified lines57 install_requires=[58 "certifi",59 "hstspreload",60 "chardet==3.*",61- "h11>=0.8,<0.10",62- "h2==3.*",61 "idna==2.*",62 "rfc3986>=1.3,<2",65- "sniffio==1.*",66- "urllib3==1.*",63+ "httpcore==0.7.*",64 ],65 classifiers=[66 "Development Status :: 4 - Beta",67 "Environment :: Web Environment",13 unmodified lines