Skip to content
Myr

utils.py

This file

Path

tests/dispatch/utils.py

118 lines · 3.8 KiB · Python

Last changed by

Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058

History of this file

Take it

1import ssl2import typing34import h2.config5import h2.connection6import h2.events78from httpx import AsyncioBackend, BaseStream, Request, TimeoutConfig9from tests.concurrency import sleep101112class MockHTTP2Backend:13    def __init__(self, app, backend=None):14        self.app = app15        self.backend = AsyncioBackend() if backend is None else backend16        self.server = None1718    async def connect(19        self,20        hostname: str,21        port: int,22        ssl_context: typing.Optional[ssl.SSLContext],23        timeout: TimeoutConfig,24    ) -> BaseStream:25        self.server = MockHTTP2Server(self.app, backend=self.backend)26        return self.server2728    # Defer all other attributes and methods to the underlying backend.29    def __getattr__(self, name: str) -> typing.Any:30        return getattr(self.backend, name)313233class MockHTTP2Server(BaseStream):34    def __init__(self, app, backend):35        config = h2.config.H2Configuration(client_side=False)36        self.conn = h2.connection.H2Connection(config=config)37        self.app = app38        self.backend = backend39        self.buffer = b""40        self.requests = {}41        self.close_connection = False4243    # Stream interface4445    def get_http_version(self) -> str:46        return "HTTP/2"4748    async def read(self, n, timeout, flag=None) -> bytes:49        await sleep(self.backend, 0)50        send, self.buffer = self.buffer[:n], self.buffer[n:]51        return send5253    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    def is_connection_dropped(self) -> bool:71        return self.close_connection7273    # Server implementation7475    def request_received(self, headers, stream_id):76        """77        Handler for when the initial part of the HTTP request is received.78        """79        if stream_id not in self.requests:80            self.requests[stream_id] = []81        self.requests[stream_id].append({"headers": headers, "data": b""})8283    def receive_data(self, data, stream_id):84        """85        Handler for when a data part of the HTTP request is received.86        """87        self.requests[stream_id][-1]["data"] += data8889    def stream_complete(self, stream_id):90        """91        Handler for when the HTTP request is completed.92        """93        request = self.requests[stream_id].pop(0)94        if not self.requests[stream_id]:95            del self.requests[stream_id]9697        headers_dict = dict(request["headers"])9899        method = headers_dict[b":method"].decode("ascii")100        url = "%s://%s%s" % (101            headers_dict[b":scheme"].decode("ascii"),102            headers_dict[b":authority"].decode("ascii"),103            headers_dict[b":path"].decode("ascii"),104        )105        headers = [(k, v) for k, v in request["headers"] if not k.startswith(b":")]106        data = request["data"]107108        # Call out to the app.109        request = Request(method, url, headers=headers, data=data)110        response = self.app(request)111112        # Write the response to the buffer.113        status_code_bytes = str(response.status_code).encode("ascii")114        response_headers = [(b":status", status_code_bytes)] + response.headers.raw115116        self.conn.send_headers(stream_id, response_headers)117        self.conn.send_data(stream_id, response.content, end_stream=True)118        self.buffer += self.conn.data_to_send()