utils.py
This file
Path
tests/dispatch/utils.py
123 lines · 3.7 KiB · Python
Last changed by
'Protocols' -> 'HTTPVersions'Tom Christiebefore adoptionf72fa68
History of this fileTake it
Handle early connection closes (#103)Tom Christiebefore adoptionb9c8a15
line 1why, one step back1import asyncioMerge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
lines 2–8why, one step back2import ssl3import typing45import h2.config6import h2.connection7import h2.events8Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b
line 9why, one step back9from httpx import (LintingTom Christiebefore adoption8f4abe0
lines 10–15why, one step back10 AsyncioBackend,11 BaseReader,12 BaseWriter,13 Protocol,14 Request,15 TimeoutConfig,'Protocols' -> 'HTTPVersions'Tom Christiebefore adoptionf72fa68
line 16why, one step back16 HTTPVersionConfigLintingTom Christiebefore adoption8f4abe0
line 17why, one step back17)Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
lines 18–22why, one step back181920class MockHTTP2Backend(AsyncioBackend):21 def __init__(self, app):22 self.app = appCheck for connection aliveness on pool re-acquiry (#111)Tom Christiebefore adoption025240c
line 23why, one step back23 self.server = NoneMerge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
lines 24–29why, one step back2425 async def connect(26 self,27 hostname: str,28 port: int,29 ssl_context: typing.Optional[ssl.SSLContext],'Protocols' -> 'HTTPVersions'Tom Christiebefore adoptionf72fa68
line 30why, one step back30 timeout: TimeoutConfigMerge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
line 31why, one step back31 ) -> typing.Tuple[BaseReader, BaseWriter, Protocol]:Check for connection aliveness on pool re-acquiry (#111)Tom Christiebefore adoption025240c
line 32why, one step back32 self.server = MockHTTP2Server(self.app)Added base class HTTPError with request/response attribute (#162)halbowbefore adoption92fbe5f
line 33why, one step back33 return self.server, self.server, Protocol.HTTP_2Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
lines 34–46why, one step back343536class MockHTTP2Server(BaseReader, BaseWriter):37 """38 This class exposes Reader and Writer style interfaces.39 """4041 def __init__(self, app):42 config = h2.config.H2Configuration(client_side=False)43 self.conn = h2.connection.H2Connection(config=config)44 self.app = app45 self.buffer = b""46 self.requests = {}Check disconnections on connection reacquiry (#145)Tom Christiebefore adoptionec365c0
line 47why, one step back47 self.close_connection = FalseMerge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
lines 48–50why, one step back4849 # BaseReader interface50Read/Write timeout modes (#104)Tom Christiebefore adoptionf4f05e3
line 51why, one step back51 async def read(self, n, timeout, flag=None) -> bytes:Handle early connection closes (#103)Tom Christiebefore adoptionb9c8a15
line 52why, one step back52 await asyncio.sleep(0)Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
lines 53–73why, one step back53 send, self.buffer = self.buffer[:n], self.buffer[n:]54 return send5556 # BaseWriter interface5758 def write_no_block(self, data: bytes) -> None:59 events = self.conn.receive_data(data)60 self.buffer += self.conn.data_to_send()61 for event in events:62 if isinstance(event, h2.events.RequestReceived):63 self.request_received(event.headers, event.stream_id)64 elif isinstance(event, h2.events.DataReceived):65 self.receive_data(event.data, event.stream_id)66 elif isinstance(event, h2.events.StreamEnded):67 self.stream_complete(event.stream_id)6869 async def write(self, data: bytes, timeout) -> None:70 self.write_no_block(data)7172 async def close(self) -> None:73 passCheck disconnections on connection reacquiry (#145)Tom Christiebefore adoptionec365c0
lines 74–76why, one step back7475 def is_connection_dropped(self) -> bool:76 return self.close_connectionMerge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
lines 77–117why, one step back7778 # Server implementation7980 def request_received(self, headers, stream_id):81 """82 Handler for when the initial part of the HTTP request is received.83 """84 if stream_id not in self.requests:85 self.requests[stream_id] = []86 self.requests[stream_id].append({"headers": headers, "data": b""})8788 def receive_data(self, data, stream_id):89 """90 Handler for when a data part of the HTTP request is received.91 """92 self.requests[stream_id][-1]["data"] += data9394 def stream_complete(self, stream_id):95 """96 Handler for when the HTTP request is completed.97 """98 request = self.requests[stream_id].pop(0)99 if not self.requests[stream_id]:100 del self.requests[stream_id]101102 headers_dict = dict(request["headers"])103104 method = headers_dict[b":method"].decode("ascii")105 url = "%s://%s%s" % (106 headers_dict[b":scheme"].decode("ascii"),107 headers_dict[b":authority"].decode("ascii"),108 headers_dict[b":path"].decode("ascii"),109 )110 headers = [(k, v) for k, v in request["headers"] if not k.startswith(b":")]111 data = request["data"]112113 # Call out to the app.114 request = Request(method, url, headers=headers, data=data)115 response = self.app(request)116117 # Write the response to the buffer.Status code tweaks (#77)Tom Christiebefore adoptionc12c271
line 118why, one step back118 status_code_bytes = str(response.status_code).encode("ascii")Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
lines 119–123why, one step back119 response_headers = [(b":status", status_code_bytes)] + response.headers.raw120121 self.conn.send_headers(stream_id, response_headers)122 self.conn.send_data(stream_id, response.content, end_stream=True)123 self.buffer += self.conn.data_to_send()