Skip to content
Myr

utils.py

This file

Path

tests/dispatch/utils.py

115 lines · 3.5 KiB · Python

Last changed by

Status code tweaks (#77)Tom Christiebefore adoptionc12c271

History of this file

Take it

1import ssl2import typing34import h2.config5import h2.connection6import h2.events78from httpcore import (9    AsyncioBackend,10    BaseReader,11    BaseWriter,12    Protocol,13    Request,14    TimeoutConfig,15)161718class MockHTTP2Backend(AsyncioBackend):19    def __init__(self, app):20        self.app = app2122    async def connect(23        self,24        hostname: str,25        port: int,26        ssl_context: typing.Optional[ssl.SSLContext],27        timeout: TimeoutConfig,28    ) -> typing.Tuple[BaseReader, BaseWriter, Protocol]:29        server = MockHTTP2Server(self.app)30        return (server, server, Protocol.HTTP_2)313233class MockHTTP2Server(BaseReader, BaseWriter):34    """35    This class exposes Reader and Writer style interfaces.36    """3738    def __init__(self, app):39        config = h2.config.H2Configuration(client_side=False)40        self.conn = h2.connection.H2Connection(config=config)41        self.app = app42        self.buffer = b""43        self.requests = {}4445    # BaseReader interface4647    async def read(self, n, timeout) -> bytes:48        send, self.buffer = self.buffer[:n], self.buffer[n:]49        return send5051    # BaseWriter interface5253    def write_no_block(self, data: bytes) -> None:54        events = self.conn.receive_data(data)55        self.buffer += self.conn.data_to_send()56        for event in events:57            if isinstance(event, h2.events.RequestReceived):58                self.request_received(event.headers, event.stream_id)59            elif isinstance(event, h2.events.DataReceived):60                self.receive_data(event.data, event.stream_id)61            elif isinstance(event, h2.events.StreamEnded):62                self.stream_complete(event.stream_id)6364    async def write(self, data: bytes, timeout) -> None:65        self.write_no_block(data)6667    async def close(self) -> None:68        pass6970    # 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()