Skip to content
Myr

utils.py

This file

Path

tests/dispatch/utils.py

115 lines · 3.6 KiB · Python

Last changed by

Drop Protocol str enum class in favor of plain old strings (#251)Tom Christiebefore adoptione69ee77

History of this file

Take it

1import asyncio2import ssl3import typing45import h2.config6import h2.connection7import h2.events89from httpx import AsyncioBackend, BaseReader, BaseWriter, Request, TimeoutConfig101112class MockHTTP2Backend(AsyncioBackend):13    def __init__(self, app):14        self.app = app15        self.server = None1617    async def connect(18        self,19        hostname: str,20        port: int,21        ssl_context: typing.Optional[ssl.SSLContext],22        timeout: TimeoutConfig,23    ) -> typing.Tuple[BaseReader, BaseWriter, str]:24        self.server = MockHTTP2Server(self.app)25        return self.server, self.server, "HTTP/2"262728class MockHTTP2Server(BaseReader, BaseWriter):29    """30    This class exposes Reader and Writer style interfaces.31    """3233    def __init__(self, app):34        config = h2.config.H2Configuration(client_side=False)35        self.conn = h2.connection.H2Connection(config=config)36        self.app = app37        self.buffer = b""38        self.requests = {}39        self.close_connection = False4041    # BaseReader interface4243    async def read(self, n, timeout, flag=None) -> bytes:44        await asyncio.sleep(0)45        send, self.buffer = self.buffer[:n], self.buffer[n:]46        return send4748    # BaseWriter interface4950    def write_no_block(self, data: bytes) -> None:51        events = self.conn.receive_data(data)52        self.buffer += self.conn.data_to_send()53        for event in events:54            if isinstance(event, h2.events.RequestReceived):55                self.request_received(event.headers, event.stream_id)56            elif isinstance(event, h2.events.DataReceived):57                self.receive_data(event.data, event.stream_id)58            elif isinstance(event, h2.events.StreamEnded):59                self.stream_complete(event.stream_id)6061    async def write(self, data: bytes, timeout) -> None:62        self.write_no_block(data)6364    async def close(self) -> None:65        pass6667    def is_connection_dropped(self) -> bool:68        return self.close_connection6970    # Server implementation7172    def request_received(self, headers, stream_id):73        """74        Handler for when the initial part of the HTTP request is received.75        """76        if stream_id not in self.requests:77            self.requests[stream_id] = []78        self.requests[stream_id].append({"headers": headers, "data": b""})7980    def receive_data(self, data, stream_id):81        """82        Handler for when a data part of the HTTP request is received.83        """84        self.requests[stream_id][-1]["data"] += data8586    def stream_complete(self, stream_id):87        """88        Handler for when the HTTP request is completed.89        """90        request = self.requests[stream_id].pop(0)91        if not self.requests[stream_id]:92            del self.requests[stream_id]9394        headers_dict = dict(request["headers"])9596        method = headers_dict[b":method"].decode("ascii")97        url = "%s://%s%s" % (98            headers_dict[b":scheme"].decode("ascii"),99            headers_dict[b":authority"].decode("ascii"),100            headers_dict[b":path"].decode("ascii"),101        )102        headers = [(k, v) for k, v in request["headers"] if not k.startswith(b":")]103        data = request["data"]104105        # Call out to the app.106        request = Request(method, url, headers=headers, data=data)107        response = self.app(request)108109        # Write the response to the buffer.110        status_code_bytes = str(response.status_code).encode("ascii")111        response_headers = [(b":status", status_code_bytes)] + response.headers.raw112113        self.conn.send_headers(stream_id, response_headers)114        self.conn.send_data(stream_id, response.content, end_stream=True)115        self.buffer += self.conn.data_to_send()