Skip to content
Myr

utils.py

This file

Path

tests/dispatch/utils.py

124 lines · 3.7 KiB · Python

Last changed by

Initial pass at configuring supported protocol versionsTom Christiebefore adoption0e49f23

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

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 9why, one step back
9from httpx import (

LintingTom Christiebefore adoption8f4abe0

lines 10–15why, one step back
10 AsyncioBackend,
11 BaseReader,12 BaseWriter,13 Protocol,14 Request,15 TimeoutConfig,

Initial pass at configuring supported protocol versionsTom Christiebefore adoption0e49f23

line 16why, one step back
16 ProtocolConfig

LintingTom Christiebefore adoption8f4abe0

line 17why, one step back
17)

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

lines 18–22why, one step back
18
1920class MockHTTP2Backend(AsyncioBackend):21 def __init__(self, app):22 self.app = app

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

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

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

lines 24–30why, one step back
24
25 async def connect(26 self,27 hostname: str,28 port: int,29 ssl_context: typing.Optional[ssl.SSLContext],30 timeout: TimeoutConfig,

Initial pass at configuring supported protocol versionsTom Christiebefore adoption0e49f23

line 31why, one step back
31 protocols: ProtocolConfig

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

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

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

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

Added base class HTTPError with request/response attribute (#162)halbowbefore adoption92fbe5f

line 34why, one step back
34 return self.server, self.server, Protocol.HTTP_2

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

lines 35–47why, one step back
35
3637class MockHTTP2Server(BaseReader, BaseWriter):38 """39 This class exposes Reader and Writer style interfaces.40 """4142 def __init__(self, app):43 config = h2.config.H2Configuration(client_side=False)44 self.conn = h2.connection.H2Connection(config=config)45 self.app = app46 self.buffer = b""47 self.requests = {}

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

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

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

lines 49–51why, one step back
49
50 # BaseReader interface51

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

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

Handle early connection closes (#103)Tom Christiebefore adoptionb9c8a15

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

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

lines 54–74why, one step back
54 send, self.buffer = self.buffer[:n], self.buffer[n:]
55 return send5657 # BaseWriter interface5859 def write_no_block(self, data: bytes) -> None:60 events = self.conn.receive_data(data)61 self.buffer += self.conn.data_to_send()62 for event in events:63 if isinstance(event, h2.events.RequestReceived):64 self.request_received(event.headers, event.stream_id)65 elif isinstance(event, h2.events.DataReceived):66 self.receive_data(event.data, event.stream_id)67 elif isinstance(event, h2.events.StreamEnded):68 self.stream_complete(event.stream_id)6970 async def write(self, data: bytes, timeout) -> None:71 self.write_no_block(data)7273 async def close(self) -> None:74 pass

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

lines 75–77why, one step back
75
76 def is_connection_dropped(self) -> bool:77 return self.close_connection

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

lines 78–118why, one step back
78
79 # Server implementation8081 def request_received(self, headers, stream_id):82 """83 Handler for when the initial part of the HTTP request is received.84 """85 if stream_id not in self.requests:86 self.requests[stream_id] = []87 self.requests[stream_id].append({"headers": headers, "data": b""})8889 def receive_data(self, data, stream_id):90 """91 Handler for when a data part of the HTTP request is received.92 """93 self.requests[stream_id][-1]["data"] += data9495 def stream_complete(self, stream_id):96 """97 Handler for when the HTTP request is completed.98 """99 request = self.requests[stream_id].pop(0)100 if not self.requests[stream_id]:101 del self.requests[stream_id]102103 headers_dict = dict(request["headers"])104105 method = headers_dict[b":method"].decode("ascii")106 url = "%s://%s%s" % (107 headers_dict[b":scheme"].decode("ascii"),108 headers_dict[b":authority"].decode("ascii"),109 headers_dict[b":path"].decode("ascii"),110 )111 headers = [(k, v) for k, v in request["headers"] if not k.startswith(b":")]112 data = request["data"]113114 # Call out to the app.115 request = Request(method, url, headers=headers, data=data)116 response = self.app(request)117118 # Write the response to the buffer.

Status code tweaks (#77)Tom Christiebefore adoptionc12c271

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

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

lines 120–124why, one step back
120 response_headers = [(b":status", status_code_bytes)] + response.headers.raw
121122 self.conn.send_headers(stream_id, response_headers)123 self.conn.send_data(stream_id, response.content, end_stream=True)124 self.buffer += self.conn.data_to_send()