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

Handle early connection closes (#103)Tom Christiebefore adoptionb9c8a15

line 1why, one step back
1import asyncio

Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af

lines 2–8why, one step back
2import ssl
3import typing45import h2.config6import h2.connection7import h2.events8

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

line 9why, one step back
9from httpx import AsyncioBackend, BaseReader, BaseWriter, Request, TimeoutConfig

Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af

lines 10–14why, one step back
10
1112class MockHTTP2Backend(AsyncioBackend):13 def __init__(self, app):14 self.app = app

Check for connection aliveness on pool re-acquiry (#111)Tom Christiebefore adoption025240c

line 15why, one step back
15 self.server = None

Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af

lines 16–22why, one step back
16
17 async def connect(18 self,19 hostname: str,20 port: int,21 ssl_context: typing.Optional[ssl.SSLContext],22 timeout: TimeoutConfig,

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

line 23why, one step back
23 ) -> typing.Tuple[BaseReader, BaseWriter, str]:

Check for connection aliveness on pool re-acquiry (#111)Tom Christiebefore adoption025240c

line 24why, one step back
24 self.server = MockHTTP2Server(self.app)

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

line 25why, one step back
25 return self.server, self.server, "HTTP/2"

Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af

lines 26–38why, one step back
26
2728class 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 = {}

Check disconnections on connection reacquiry (#145)Tom Christiebefore adoptionec365c0

line 39why, one step back
39 self.close_connection = False

Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af

lines 40–42why, one step back
40
41 # BaseReader interface42

Read/Write timeout modes (#104)Tom Christiebefore adoptionf4f05e3

line 43why, one step back
43 async def read(self, n, timeout, flag=None) -> bytes:

Handle early connection closes (#103)Tom Christiebefore adoptionb9c8a15

line 44why, one step back
44 await asyncio.sleep(0)

Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af

lines 45–65why, one step back
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 pass

Check disconnections on connection reacquiry (#145)Tom Christiebefore adoptionec365c0

lines 66–68why, one step back
66
67 def is_connection_dropped(self) -> bool:68 return self.close_connection

Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af

lines 69–109why, one step back
69
70 # 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.

Status code tweaks (#77)Tom Christiebefore adoptionc12c271

line 110why, one step back
110 status_code_bytes = str(response.status_code).encode("ascii")

Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af

lines 111–115why, one step back
111 response_headers = [(b":status", status_code_bytes)] + response.headers.raw
112113 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()