Skip to content
Myr

utils.py

This file

Path

tests/dispatch/utils.py

122 lines · 3.7 KiB · Python

Last changed by

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

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–16why, one step back
10 AsyncioBackend,
11 BaseReader,12 BaseWriter,13 Protocol,14 Request,15 TimeoutConfig,16)

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

lines 17–21why, one step back
17
1819class MockHTTP2Backend(AsyncioBackend):20 def __init__(self, app):21 self.app = app

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

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

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

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

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

lines 31–32why, one step back
31 self.server = MockHTTP2Server(self.app)
32 return (self.server, self.server, Protocol.HTTP_2)

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

lines 33–45why, one step back
33
3435class MockHTTP2Server(BaseReader, BaseWriter):36 """37 This class exposes Reader and Writer style interfaces.38 """3940 def __init__(self, app):41 config = h2.config.H2Configuration(client_side=False)42 self.conn = h2.connection.H2Connection(config=config)43 self.app = app44 self.buffer = b""45 self.requests = {}

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

line 46why, one step back
46 self.raise_disconnect = False

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

lines 47–49why, one step back
47
48 # BaseReader interface49

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

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

Handle early connection closes (#103)Tom Christiebefore adoptionb9c8a15

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

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

lines 52–57why, one step back
52 send, self.buffer = self.buffer[:n], self.buffer[n:]
53 return send5455 # BaseWriter interface5657 def write_no_block(self, data: bytes) -> None:

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

lines 58–60why, one step back
58 if self.raise_disconnect:
59 self.raise_disconnect = False60 raise ConnectionResetError()

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

lines 61–116why, one step back
61 events = self.conn.receive_data(data)
62 self.buffer += self.conn.data_to_send()63 for event in events:64 if isinstance(event, h2.events.RequestReceived):65 self.request_received(event.headers, event.stream_id)66 elif isinstance(event, h2.events.DataReceived):67 self.receive_data(event.data, event.stream_id)68 elif isinstance(event, h2.events.StreamEnded):69 self.stream_complete(event.stream_id)7071 async def write(self, data: bytes, timeout) -> None:72 self.write_no_block(data)7374 async def close(self) -> None:75 pass7677 # Server implementation7879 def request_received(self, headers, stream_id):80 """81 Handler for when the initial part of the HTTP request is received.82 """83 if stream_id not in self.requests:84 self.requests[stream_id] = []85 self.requests[stream_id].append({"headers": headers, "data": b""})8687 def receive_data(self, data, stream_id):88 """89 Handler for when a data part of the HTTP request is received.90 """91 self.requests[stream_id][-1]["data"] += data9293 def stream_complete(self, stream_id):94 """95 Handler for when the HTTP request is completed.96 """97 request = self.requests[stream_id].pop(0)98 if not self.requests[stream_id]:99 del self.requests[stream_id]100101 headers_dict = dict(request["headers"])102103 method = headers_dict[b":method"].decode("ascii")104 url = "%s://%s%s" % (105 headers_dict[b":scheme"].decode("ascii"),106 headers_dict[b":authority"].decode("ascii"),107 headers_dict[b":path"].decode("ascii"),108 )109 headers = [(k, v) for k, v in request["headers"] if not k.startswith(b":")]110 data = request["data"]111112 # Call out to the app.113 request = Request(method, url, headers=headers, data=data)114 response = self.app(request)115116 # Write the response to the buffer.

Status code tweaks (#77)Tom Christiebefore adoptionc12c271

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

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

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