Skip to content
Myr

utils.py

This file

Path

tests/dispatch/utils.py

117 lines · 3.5 KiB · Python

Last changed by

Handle early connection closes (#103)Tom Christiebefore adoptionb9c8a15

History of this file

Take it

1import asyncio2import ssl3import typing45import h2.config6import h2.connection7import h2.events89from http3 import (10    AsyncioBackend,11    BaseReader,12    BaseWriter,13    Protocol,14    Request,15    TimeoutConfig,16)171819class MockHTTP2Backend(AsyncioBackend):20    def __init__(self, app):21        self.app = app2223    async def connect(24        self,25        hostname: str,26        port: int,27        ssl_context: typing.Optional[ssl.SSLContext],28        timeout: TimeoutConfig,29    ) -> typing.Tuple[BaseReader, BaseWriter, Protocol]:30        server = MockHTTP2Server(self.app)31        return (server, server, Protocol.HTTP_2)323334class MockHTTP2Server(BaseReader, BaseWriter):35    """36    This class exposes Reader and Writer style interfaces.37    """3839    def __init__(self, app):40        config = h2.config.H2Configuration(client_side=False)41        self.conn = h2.connection.H2Connection(config=config)42        self.app = app43        self.buffer = b""44        self.requests = {}4546    # BaseReader interface4748    async def read(self, n, timeout) -> bytes:49        await asyncio.sleep(0)50        send, self.buffer = self.buffer[:n], self.buffer[n:]51        return send5253    # BaseWriter interface5455    def write_no_block(self, data: bytes) -> None:56        events = self.conn.receive_data(data)57        self.buffer += self.conn.data_to_send()58        for event in events:59            if isinstance(event, h2.events.RequestReceived):60                self.request_received(event.headers, event.stream_id)61            elif isinstance(event, h2.events.DataReceived):62                self.receive_data(event.data, event.stream_id)63            elif isinstance(event, h2.events.StreamEnded):64                self.stream_complete(event.stream_id)6566    async def write(self, data: bytes, timeout) -> None:67        self.write_no_block(data)6869    async def close(self) -> None:70        pass7172    # Server implementation7374    def request_received(self, headers, stream_id):75        """76        Handler for when the initial part of the HTTP request is received.77        """78        if stream_id not in self.requests:79            self.requests[stream_id] = []80        self.requests[stream_id].append({"headers": headers, "data": b""})8182    def receive_data(self, data, stream_id):83        """84        Handler for when a data part of the HTTP request is received.85        """86        self.requests[stream_id][-1]["data"] += data8788    def stream_complete(self, stream_id):89        """90        Handler for when the HTTP request is completed.91        """92        request = self.requests[stream_id].pop(0)93        if not self.requests[stream_id]:94            del self.requests[stream_id]9596        headers_dict = dict(request["headers"])9798        method = headers_dict[b":method"].decode("ascii")99        url = "%s://%s%s" % (100            headers_dict[b":scheme"].decode("ascii"),101            headers_dict[b":authority"].decode("ascii"),102            headers_dict[b":path"].decode("ascii"),103        )104        headers = [(k, v) for k, v in request["headers"] if not k.startswith(b":")]105        data = request["data"]106107        # Call out to the app.108        request = Request(method, url, headers=headers, data=data)109        response = self.app(request)110111        # Write the response to the buffer.112        status_code_bytes = str(response.status_code).encode("ascii")113        response_headers = [(b":status", status_code_bytes)] + response.headers.raw114115        self.conn.send_headers(stream_id, response_headers)116        self.conn.send_data(stream_id, response.content, end_stream=True)117        self.buffer += self.conn.data_to_send()