utils.py
This file
Path
tests/dispatch/utils.py
109 lines · 3.5 KiB · Python
Last changed by
Unify BaseReader and BaseWriter as BaseStreamflorimondmancabefore adoption14eb81f
History of this fileTake it
1import asyncio2import ssl3import typing45import h2.config6import h2.connection7import h2.events89from httpx import AsyncioBackend, BaseStream, 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[BaseStream, str]:24 self.server = MockHTTP2Server(self.app)25 return self.server, "HTTP/2"262728class MockHTTP2Server(BaseStream):29 def __init__(self, app):30 config = h2.config.H2Configuration(client_side=False)31 self.conn = h2.connection.H2Connection(config=config)32 self.app = app33 self.buffer = b""34 self.requests = {}35 self.close_connection = False3637 # Stream interface3839 async def read(self, n, timeout, flag=None) -> bytes:40 await asyncio.sleep(0)41 send, self.buffer = self.buffer[:n], self.buffer[n:]42 return send4344 def write_no_block(self, data: bytes) -> None:45 events = self.conn.receive_data(data)46 self.buffer += self.conn.data_to_send()47 for event in events:48 if isinstance(event, h2.events.RequestReceived):49 self.request_received(event.headers, event.stream_id)50 elif isinstance(event, h2.events.DataReceived):51 self.receive_data(event.data, event.stream_id)52 elif isinstance(event, h2.events.StreamEnded):53 self.stream_complete(event.stream_id)5455 async def write(self, data: bytes, timeout) -> None:56 self.write_no_block(data)5758 async def close(self) -> None:59 pass6061 def is_connection_dropped(self) -> bool:62 return self.close_connection6364 # Server implementation6566 def request_received(self, headers, stream_id):67 """68 Handler for when the initial part of the HTTP request is received.69 """70 if stream_id not in self.requests:71 self.requests[stream_id] = []72 self.requests[stream_id].append({"headers": headers, "data": b""})7374 def receive_data(self, data, stream_id):75 """76 Handler for when a data part of the HTTP request is received.77 """78 self.requests[stream_id][-1]["data"] += data7980 def stream_complete(self, stream_id):81 """82 Handler for when the HTTP request is completed.83 """84 request = self.requests[stream_id].pop(0)85 if not self.requests[stream_id]:86 del self.requests[stream_id]8788 headers_dict = dict(request["headers"])8990 method = headers_dict[b":method"].decode("ascii")91 url = "%s://%s%s" % (92 headers_dict[b":scheme"].decode("ascii"),93 headers_dict[b":authority"].decode("ascii"),94 headers_dict[b":path"].decode("ascii"),95 )96 headers = [(k, v) for k, v in request["headers"] if not k.startswith(b":")]97 data = request["data"]9899 # Call out to the app.100 request = Request(method, url, headers=headers, data=data)101 response = self.app(request)102103 # Write the response to the buffer.104 status_code_bytes = str(response.status_code).encode("ascii")105 response_headers = [(b":status", status_code_bytes)] + response.headers.raw106107 self.conn.send_headers(stream_id, response_headers)108 self.conn.send_data(stream_id, response.content, end_stream=True)109 self.buffer += self.conn.data_to_send()