Skip to content
Myr

Support alternate concurrency backends from client & rejig tests

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

authored by Tom Christie · committed by Tom Christie · parent 2694c48 · Browse files · 5 files+141 added−106 removed
This commit

State

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

Diff stats

5 files+141 added−106 removed

  • tests:+132 added−103 removed
  • other:+9 added−3 removed

5 files+141 added−106 removed

modified:httpcore/__init__.py+2 added-1 removed
1from .client import AsyncClient, Client2from .concurrency import AsyncioBackend3from .config import PoolLimits, SSLConfig, TimeoutConfig4from .dispatch.connection import HTTPConnection5from .dispatch.connection_pool import ConnectionPool6from .dispatch.http2 import HTTP2Connection
12 unmodified lines
19 StreamConsumed,20 Timeout,21 TooManyRedirects,22)22from .interfaces import BaseReader, BaseWriter, Dispatcher, Protocol23from .interfaces import BaseReader, BaseWriter, ConcurrencyBackend, Dispatcher, Protocol24from .models import URL, Headers, Origin, QueryParams, Request, Response25from .status_codes import codes2627__version__ = "0.2.1"
modified:httpcore/client.py+7 added-2 removed
11 unmodified lines
12 TimeoutConfig,13)14from .dispatch.connection_pool import ConnectionPool15from .exceptions import RedirectBodyUnavailable, RedirectLoop, TooManyRedirects16from .interfaces import Dispatcher16from .interfaces import ConcurrencyBackend, Dispatcher17from .models import (18 URL,19 Headers,20 HeaderTypes,
14 unmodified lines
35 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,36 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,37 max_redirects: int = DEFAULT_MAX_REDIRECTS,38 dispatch: Dispatcher = None,39 backend: ConcurrencyBackend = None,40 ):41 if dispatch is None:41 dispatch = ConnectionPool(ssl=ssl, timeout=timeout, pool_limits=pool_limits)42 dispatch = ConnectionPool(43 ssl=ssl, timeout=timeout, pool_limits=pool_limits, backend=backend44 )4546 self.max_redirects = max_redirects47 self.dispatch = dispatch48
330 unmodified lines
379 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,380 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,381 max_redirects: int = DEFAULT_MAX_REDIRECTS,382 dispatch: Dispatcher = None,383 backend: ConcurrencyBackend = None,384 ) -> None:385 self._client = AsyncClient(386 ssl=ssl,387 timeout=timeout,388 pool_limits=pool_limits,389 max_redirects=max_redirects,390 dispatch=dispatch,391 backend=backend,392 )393 self._loop = asyncio.new_event_loop()394395 def request(
216 unmodified lines
added:tests/dispatch/__init__.py
modified:tests/dispatch/test_http2.py+24 added-103 removed
1import json23import h2.config4import h2.connection5import h2.events3import pytest48from httpcore import BaseReader, BaseWriter, HTTP2Connection, Request5from httpcore import Client, Response6from .utils import MockHTTP2Backend7811class MockServer(BaseReader, BaseWriter):12 """13 This class exposes Reader and Writer style interfaces14 """9def app(request):10 content = json.dumps({11 "method": request.method,12 "path": request.url.path,13 "body": request.content.decode(),14 }).encode()15 headers = {'Content-Length': str(len(content))}16 return Response(200, headers=headers, content=content)1716 def __init__(self):17 config = h2.config.H2Configuration(client_side=False)18 self.conn = h2.connection.H2Connection(config=config)19 self.buffer = b""20 self.requests = {}1822 # BaseReader interface19def test_http2_get_request():20 backend = MockHTTP2Backend(app=app)2124 async def read(self, n, timeout) -> bytes:25 send, self.buffer = self.buffer[:n], self.buffer[n:]26 return send22 with Client(backend=backend) as client:23 response = client.get("http://example.org")2428 # BaseWriter interface2930 def write_no_block(self, data: bytes) -> None:31 events = self.conn.receive_data(data)32 self.buffer += self.conn.data_to_send()33 for event in events:34 if isinstance(event, h2.events.RequestReceived):35 self.request_received(event.headers, event.stream_id)36 elif isinstance(event, h2.events.DataReceived):37 self.receive_data(event.data, event.stream_id)38 elif isinstance(event, h2.events.StreamEnded):39 self.stream_complete(event.stream_id)4041 async def write(self, data: bytes, timeout) -> None:42 self.write_no_block(data)4344 async def close(self) -> None:45 pass4647 # Server implementation4849 def request_received(self, headers, stream_id):50 if stream_id not in self.requests:51 self.requests[stream_id] = []52 self.requests[stream_id].append({"headers": headers, "data": b""})5354 def receive_data(self, data, stream_id):55 self.requests[stream_id][-1]["data"] += data5657 def stream_complete(self, stream_id):58 request = self.requests[stream_id].pop(0)59 if not self.requests[stream_id]:60 del self.requests[stream_id]6162 request_headers = dict(request["headers"])63 request_data = request["data"]6465 response_body = json.dumps(66 {67 "method": request_headers[b":method"].decode(),68 "path": request_headers[b":path"].decode(),69 "body": request_data.decode(),70 }71 ).encode()7273 response_headers = (74 (b":status", b"200"),75 (b"content-length", str(len(response_body)).encode()),76 )77 self.conn.send_headers(stream_id, response_headers)78 self.conn.send_data(stream_id, response_body, end_stream=True)79 self.buffer += self.conn.data_to_send()808182@pytest.mark.asyncio83async def test_http2_get_request():84 server = MockServer()85 conn = HTTP2Connection(reader=server, writer=server)86 request = Request("GET", "http://example.org")87 request.prepare()8889 response = await conn.send(request)9025 assert response.status_code == 20026 assert json.loads(response.content) == {"method": "GET", "path": "/", "body": ""}272895@pytest.mark.asyncio96async def test_http2_post_request():97 server = MockServer()98 conn = HTTP2Connection(reader=server, writer=server)99 request = Request("POST", "http://example.org", data=b"<data>")100 request.prepare()29def test_http2_post_request():30 backend = MockHTTP2Backend(app=app)31102 response = await conn.send(request)32 with Client(backend=backend) as client:33 response = client.post("http://example.org", data=b"<data>")3435 assert response.status_code == 20036 assert json.loads(response.content) == {37 "method": "POST",
1 unmodified line
39 "body": "<data>",40 }4142112@pytest.mark.asyncio113async def test_http2_multiple_requests():114 server = MockServer()115 conn = HTTP2Connection(reader=server, writer=server)116 request_1 = Request("GET", "http://example.org/1")117 request_2 = Request("GET", "http://example.org/2")118 request_3 = Request("GET", "http://example.org/3")43def test_http2_multiple_requests():44 backend = MockHTTP2Backend(app=app)45120 request_1.prepare()121 request_2.prepare()122 request_3.prepare()46 with Client(backend=backend) as client:47 response_1 = client.get("http://example.org/1")48 response_2 = client.get("http://example.org/2")49 response_3 = client.get("http://example.org/3")50124 response_1 = await conn.send(request_1)125 response_2 = await conn.send(request_2)126 response_3 = await conn.send(request_3)12751 assert response_1.status_code == 20052 assert json.loads(response_1.content) == {"method": "GET", "path": "/1", "body": ""}5354 assert response_2.status_code == 20055 assert json.loads(response_2.content) == {"method": "GET", "path": "/2", "body": ""}5657 assert response_3.status_code == 20058 assert json.loads(response_3.content) == {"method": "GET", "path": "/3", "body": ""}136137 await conn.close()
added:tests/dispatch/utils.py+108 added
1import ssl2import typing34import h2.config5import h2.connection6import h2.events78from httpcore import AsyncioBackend, BaseReader, BaseWriter, Protocol, Request, TimeoutConfig91011class MockHTTP2Backend(AsyncioBackend):12 def __init__(self, app):13 self.app = app1415 async def connect(16 self,17 hostname: str,18 port: int,19 ssl_context: typing.Optional[ssl.SSLContext],20 timeout: TimeoutConfig,21 ) -> typing.Tuple[BaseReader, BaseWriter, Protocol]:22 server = MockHTTP2Server(self.app)23 return (server, server, Protocol.HTTP_2)242526class MockHTTP2Server(BaseReader, BaseWriter):27 """28 This class exposes Reader and Writer style interfaces.29 """3031 def __init__(self, app):32 config = h2.config.H2Configuration(client_side=False)33 self.conn = h2.connection.H2Connection(config=config)34 self.app = app35 self.buffer = b""36 self.requests = {}3738 # BaseReader interface3940 async def read(self, n, timeout) -> bytes:41 send, self.buffer = self.buffer[:n], self.buffer[n:]42 return send4344 # BaseWriter interface4546 def write_no_block(self, data: bytes) -> None:47 events = self.conn.receive_data(data)48 self.buffer += self.conn.data_to_send()49 for event in events:50 if isinstance(event, h2.events.RequestReceived):51 self.request_received(event.headers, event.stream_id)52 elif isinstance(event, h2.events.DataReceived):53 self.receive_data(event.data, event.stream_id)54 elif isinstance(event, h2.events.StreamEnded):55 self.stream_complete(event.stream_id)5657 async def write(self, data: bytes, timeout) -> None:58 self.write_no_block(data)5960 async def close(self) -> None:61 pass6263 # Server implementation6465 def request_received(self, headers, stream_id):66 """67 Handler for when the initial part of the HTTP request is received.68 """69 if stream_id not in self.requests:70 self.requests[stream_id] = []71 self.requests[stream_id].append({"headers": headers, "data": b""})7273 def receive_data(self, data, stream_id):74 """75 Handler for when a data part of the HTTP request is received.76 """77 self.requests[stream_id][-1]["data"] += data7879 def stream_complete(self, stream_id):80 """81 Handler for when the HTTP request is completed.82 """83 request = self.requests[stream_id].pop(0)84 if not self.requests[stream_id]:85 del self.requests[stream_id]8687 headers_dict = dict(request["headers"])8889 method = headers_dict[b":method"].decode("ascii")90 url = "%s://%s%s" % (91 headers_dict[b":scheme"].decode("ascii"),92 headers_dict[b":authority"].decode("ascii"),93 headers_dict[b":path"].decode("ascii"),94 )95 headers = [(k, v) for k, v in request["headers"] if not k.startswith(b":")]96 data = request["data"]9798 # Call out to the app.99 request = Request(method, url, headers=headers, data=data)100 response = self.app(request)101102 # Write the response to the buffer.103 status_code_bytes = str(int(response.status_code)).encode("ascii")104 response_headers = [(b":status", status_code_bytes)] + response.headers.raw105106 self.conn.send_headers(stream_id, response_headers)107 self.conn.send_data(stream_id, response.content, end_stream=True)108 self.buffer += self.conn.data_to_send()