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
Provenance
- Commit
3acc316- Tree
68ac724- Author
Tom Christie <tom@tomchristie.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
2694c48
5 files changed+141 added−106 removed
modified:httpcore/__init__.py+2 added-1 removed
1 from .client import AsyncClient, Client2+from .concurrency import AsyncioBackend3 from .config import PoolLimits, SSLConfig, TimeoutConfig4 from .dispatch.connection import HTTPConnection5 from .dispatch.connection_pool import ConnectionPool6 from .dispatch.http2 import HTTP2Connection12 unmodified lines19 StreamConsumed,20 Timeout,21 TooManyRedirects,22 )22-from .interfaces import BaseReader, BaseWriter, Dispatcher, Protocol23+from .interfaces import BaseReader, BaseWriter, ConcurrencyBackend, Dispatcher, Protocol24 from .models import URL, Headers, Origin, QueryParams, Request, Response25 from .status_codes import codes26 27 __version__ = "0.2.1"modified:httpcore/client.py+7 added-2 removed
11 unmodified lines12 TimeoutConfig,13 )14 from .dispatch.connection_pool import ConnectionPool15 from .exceptions import RedirectBodyUnavailable, RedirectLoop, TooManyRedirects16-from .interfaces import Dispatcher16+from .interfaces import ConcurrencyBackend, Dispatcher17 from .models import (18 URL,19 Headers,20 HeaderTypes,14 unmodified lines35 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+ )45 46 self.max_redirects = max_redirects47 self.dispatch = dispatch48 330 unmodified lines379 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()394 395 def request(216 unmodified linesadded:tests/dispatch/__init__.py
modified:tests/dispatch/test_http2.py+24 added-103 removed
1 import json2 3-import h2.config4-import h2.connection5-import h2.events3 import pytest4 8-from httpcore import BaseReader, BaseWriter, HTTP2Connection, Request5+from httpcore import Client, Response6+from .utils import MockHTTP2Backend7 8 11-class MockServer(BaseReader, BaseWriter):12- """13- This class exposes Reader and Writer style interfaces14- """9+def 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)17 16- 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 = {}18 22- # BaseReader interface19+def test_http2_get_request():20+ backend = MockHTTP2Backend(app=app)21 24- 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")24 28- # BaseWriter interface29-30- 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)40-41- async def write(self, data: bytes, timeout) -> None:42- self.write_no_block(data)43-44- async def close(self) -> None:45- pass46-47- # Server implementation48-49- 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""})53-54- def receive_data(self, data, stream_id):55- self.requests[stream_id][-1]["data"] += data56-57- 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]61-62- request_headers = dict(request["headers"])63- request_data = request["data"]64-65- 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()72-73- 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()80-81-82-@pytest.mark.asyncio83-async 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()88-89- response = await conn.send(request)90-25 assert response.status_code == 20026 assert json.loads(response.content) == {"method": "GET", "path": "/", "body": ""}27 28 95-@pytest.mark.asyncio96-async 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()29+def test_http2_post_request():30+ backend = MockHTTP2Backend(app=app)31 102- response = await conn.send(request)32+ with Client(backend=backend) as client:33+ response = client.post("http://example.org", data=b"<data>")34 35 assert response.status_code == 20036 assert json.loads(response.content) == {37 "method": "POST",1 unmodified line39 "body": "<data>",40 }41 42 112-@pytest.mark.asyncio113-async 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")43+def test_http2_multiple_requests():44+ backend = MockHTTP2Backend(app=app)45 120- 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")50 124- response_1 = await conn.send(request_1)125- response_2 = await conn.send(request_2)126- response_3 = await conn.send(request_3)127-51 assert response_1.status_code == 20052 assert json.loads(response_1.content) == {"method": "GET", "path": "/1", "body": ""}53 54 assert response_2.status_code == 20055 assert json.loads(response_2.content) == {"method": "GET", "path": "/2", "body": ""}56 57 assert response_3.status_code == 20058 assert json.loads(response_3.content) == {"method": "GET", "path": "/3", "body": ""}136-137- await conn.close()added:tests/dispatch/utils.py+108 added
1+import ssl2+import typing3+4+import h2.config5+import h2.connection6+import h2.events7+8+from httpcore import AsyncioBackend, BaseReader, BaseWriter, Protocol, Request, TimeoutConfig9+10+11+class MockHTTP2Backend(AsyncioBackend):12+ def __init__(self, app):13+ self.app = app14+15+ 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)24+25+26+class MockHTTP2Server(BaseReader, BaseWriter):27+ """28+ This class exposes Reader and Writer style interfaces.29+ """30+31+ 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 = {}37+38+ # BaseReader interface39+40+ async def read(self, n, timeout) -> bytes:41+ send, self.buffer = self.buffer[:n], self.buffer[n:]42+ return send43+44+ # BaseWriter interface45+46+ 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)56+57+ async def write(self, data: bytes, timeout) -> None:58+ self.write_no_block(data)59+60+ async def close(self) -> None:61+ pass62+63+ # Server implementation64+65+ 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""})72+73+ 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"] += data78+79+ 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]86+87+ headers_dict = dict(request["headers"])88+89+ 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"]97+98+ # Call out to the app.99+ request = Request(method, url, headers=headers, data=data)100+ response = self.app(request)101+102+ # 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.raw105+106+ 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()