Skip to content
Myr

utils.py

This file

Path

tests/dispatch/utils.py

222 lines · 7.8 KiB · Python

Last changed by

Make start_tls a method on streams & return a new stream (#484)Jamie Hewlandbefore adoption644e8fc

History of this file

Take it

The walk stopped after 200 commits: lines older than 56a7943 point at it.

Int status codes (#92)Tom Christiebefore adoption56a7943

lines 1–7why, one step back
1import ssl
2import typing34import h2.config5import h2.connection6import h2.events7

Stream -> TCPStream (#339)Florimond Mancabefore adoption315a18b

line 8why, one step back
8from httpx import AsyncioBackend, BaseTCPStream, Request, TimeoutConfig

Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058

line 9why, one step back
9from tests.concurrency import sleep

Int status codes (#92)Tom Christiebefore adoption56a7943

lines 10–11why, one step back
10
11

Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058

lines 12–13why, one step back
12class MockHTTP2Backend:
13 def __init__(self, app, backend=None):

Int status codes (#92)Tom Christiebefore adoption56a7943

line 14why, one step back
14 self.app = app

Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058

line 15why, one step back
15 self.backend = AsyncioBackend() if backend is None else backend

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

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

Int status codes (#92)Tom Christiebefore adoption56a7943

line 17why, one step back
17

Stream -> TCPStream (#339)Florimond Mancabefore adoption315a18b

line 18why, one step back
18 async def open_tcp_stream(

Int status codes (#92)Tom Christiebefore adoption56a7943

lines 19–23why, one step back
19 self,
20 hostname: str,21 port: int,22 ssl_context: typing.Optional[ssl.SSLContext],23 timeout: TimeoutConfig,

Stream -> TCPStream (#339)Florimond Mancabefore adoption315a18b

line 24why, one step back
24 ) -> BaseTCPStream:

Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058

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

Merge pull request #255 from encode/refactor/stream-interfaceTom Christiebefore adoption3069227

line 26why, one step back
26 return self.server

Int status codes (#92)Tom Christiebefore adoption56a7943

line 27why, one step back
27

Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058

lines 28–30why, one step back
28 # Defer all other attributes and methods to the underlying backend.
29 def __getattr__(self, name: str) -> typing.Any:30 return getattr(self.backend, name)

Int status codes (#92)Tom Christiebefore adoption56a7943

line 31why, one step back
31

Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058

line 32why, one step back
32

Stream -> TCPStream (#339)Florimond Mancabefore adoption315a18b

line 33why, one step back
33class MockHTTP2Server(BaseTCPStream):

Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058

line 34why, one step back
34 def __init__(self, app, backend):

Int status codes (#92)Tom Christiebefore adoption56a7943

lines 35–37why, one step back
35 config = h2.config.H2Configuration(client_side=False)
36 self.conn = h2.connection.H2Connection(config=config)37 self.app = app

Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058

line 38why, one step back
38 self.backend = backend

Int status codes (#92)Tom Christiebefore adoption56a7943

lines 39–40why, one step back
39 self.buffer = b""
40 self.requests = {}

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

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

Fix bug in calculating maximum frame size (#153)IsaacBenghiatbefore adoptionab9cd0e

lines 42–43why, one step back
42 self.return_data = {}
43 self.returning = {}

Remove ENABLE_CONNECT_PROTOCOL from HTTP/2 Settings (#373)Seth Michael Larsonbefore adoptionb574230

line 44why, one step back
44 self.settings_changed = []

Int status codes (#92)Tom Christiebefore adoption56a7943

line 45why, one step back
45

Stream -> TCPStream (#339)Florimond Mancabefore adoption315a18b

line 46why, one step back
46 # TCP stream interface

Int status codes (#92)Tom Christiebefore adoption56a7943

line 47why, one step back
47

Merge pull request #255 from encode/refactor/stream-interfaceTom Christiebefore adoption3069227

lines 48–50why, one step back
48 def get_http_version(self) -> str:
49 return "HTTP/2"50

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

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

Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058

line 52why, one step back
52 await sleep(self.backend, 0)

Int status codes (#92)Tom Christiebefore adoption56a7943

lines 53–63why, one step back
53 send, self.buffer = self.buffer[:n], self.buffer[n:]
54 return send5556 def write_no_block(self, data: bytes) -> None:57 events = self.conn.receive_data(data)58 self.buffer += self.conn.data_to_send()59 for event in events:60 if isinstance(event, h2.events.RequestReceived):61 self.request_received(event.headers, event.stream_id)62 elif isinstance(event, h2.events.DataReceived):63 self.receive_data(event.data, event.stream_id)

Fix bug in calculating maximum frame size (#153)IsaacBenghiatbefore adoptionab9cd0e

lines 64–74why, one step back
64 # This should send an UPDATE_WINDOW for both the stream and the
65 # connection increasing it by the amount66 # consumed keeping the flow control window constant67 flow_control_consumed = event.flow_controlled_length68 if flow_control_consumed > 0:69 self.conn.increment_flow_control_window(flow_control_consumed)70 self.buffer += self.conn.data_to_send()71 self.conn.increment_flow_control_window(72 flow_control_consumed, event.stream_id73 )74 self.buffer += self.conn.data_to_send()

Int status codes (#92)Tom Christiebefore adoption56a7943

lines 75–76why, one step back
75 elif isinstance(event, h2.events.StreamEnded):
76 self.stream_complete(event.stream_id)

Fix bug in calculating maximum frame size (#153)IsaacBenghiatbefore adoptionab9cd0e

lines 77–84why, one step back
77 elif isinstance(event, h2.events.WindowUpdated):
78 if event.stream_id == 0:79 for key, value in self.returning.items():80 if value:81 self.send_return_data(key)82 # This will throw an error if the event is for a not-yet created stream83 elif self.returning[event.stream_id]:84 self.send_return_data(event.stream_id)

Remove ENABLE_CONNECT_PROTOCOL from HTTP/2 Settings (#373)Seth Michael Larsonbefore adoptionb574230

lines 85–86why, one step back
85 elif isinstance(event, h2.events.RemoteSettingsChanged):
86 self.settings_changed.append(event)

Int status codes (#92)Tom Christiebefore adoption56a7943

lines 87–92why, one step back
87
88 async def write(self, data: bytes, timeout) -> None:89 self.write_no_block(data)9091 async def close(self) -> None:92 pass

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

lines 93–95why, one step back
93
94 def is_connection_dropped(self) -> bool:95 return self.close_connection

Int status codes (#92)Tom Christiebefore adoption56a7943

lines 96–140why, one step back
96
97 # Server implementation9899 def request_received(self, headers, stream_id):100 """101 Handler for when the initial part of the HTTP request is received.102 """103 if stream_id not in self.requests:104 self.requests[stream_id] = []105 self.requests[stream_id].append({"headers": headers, "data": b""})106107 def receive_data(self, data, stream_id):108 """109 Handler for when a data part of the HTTP request is received.110 """111 self.requests[stream_id][-1]["data"] += data112113 def stream_complete(self, stream_id):114 """115 Handler for when the HTTP request is completed.116 """117 request = self.requests[stream_id].pop(0)118 if not self.requests[stream_id]:119 del self.requests[stream_id]120121 headers_dict = dict(request["headers"])122123 method = headers_dict[b":method"].decode("ascii")124 url = "%s://%s%s" % (125 headers_dict[b":scheme"].decode("ascii"),126 headers_dict[b":authority"].decode("ascii"),127 headers_dict[b":path"].decode("ascii"),128 )129 headers = [(k, v) for k, v in request["headers"] if not k.startswith(b":")]130 data = request["data"]131132 # Call out to the app.133 request = Request(method, url, headers=headers, data=data)134 response = self.app(request)135136 # Write the response to the buffer.137 status_code_bytes = str(response.status_code).encode("ascii")138 response_headers = [(b":status", status_code_bytes)] + response.headers.raw139140 self.conn.send_headers(stream_id, response_headers)

Fix bug in calculating maximum frame size (#153)IsaacBenghiatbefore adoptionab9cd0e

lines 141–164why, one step back
141 self.buffer += self.conn.data_to_send()
142 self.return_data[stream_id] = response.content143 self.returning[stream_id] = True144 self.send_return_data(stream_id)145146 def send_return_data(self, stream_id):147 while self.return_data[stream_id]:148 flow_control = self.conn.local_flow_control_window(stream_id)149 chunk_size = min(150 len(self.return_data[stream_id]),151 flow_control,152 self.conn.max_outbound_frame_size,153 )154 if chunk_size == 0:155 return156 else:157 chunk, self.return_data[stream_id] = (158 self.return_data[stream_id][:chunk_size],159 self.return_data[stream_id][chunk_size:],160 )161 self.conn.send_data(stream_id, chunk)162 self.buffer += self.conn.data_to_send()163 self.returning[stream_id] = False164 self.conn.end_stream(stream_id)

Int status codes (#92)Tom Christiebefore adoption56a7943

line 165why, one step back
165 self.buffer += self.conn.data_to_send()

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

lines 166–174why, one step back
166
167168class MockRawSocketBackend:169 def __init__(self, data_to_send=b"", backend=None):170 self.backend = AsyncioBackend() if backend is None else backend171 self.data_to_send = data_to_send172 self.received_data = []173 self.stream = MockRawSocketStream(self)174

Fix remaining references to BaseStream in tests (#347)Florimond Mancabefore adoption6c6148e

line 175why, one step back
175 async def open_tcp_stream(

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

lines 176–180why, one step back
176 self,
177 hostname: str,178 port: int,179 ssl_context: typing.Optional[ssl.SSLContext],180 timeout: TimeoutConfig,

Fix remaining references to BaseStream in tests (#347)Florimond Mancabefore adoption6c6148e

line 181why, one step back
181 ) -> BaseTCPStream:

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

lines 182–191why, one step back
182 self.received_data.append(
183 b"--- CONNECT(%s, %d) ---" % (hostname.encode(), port)184 )185 return self.stream186187 # Defer all other attributes and methods to the underlying backend.188 def __getattr__(self, name: str) -> typing.Any:189 return getattr(self.backend, name)190191

Fix remaining references to BaseStream in tests (#347)Florimond Mancabefore adoption6c6148e

line 192why, one step back
192class MockRawSocketStream(BaseTCPStream):

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

lines 193–194why, one step back
193 def __init__(self, backend: MockRawSocketBackend):
194 self.backend = backend

Make start_tls a method on streams & return a new stream (#484)Jamie Hewlandbefore adoption644e8fc

lines 195–200why, one step back
195
196 async def start_tls(197 self, hostname: str, ssl_context: ssl.SSLContext, timeout: TimeoutConfig198 ) -> BaseTCPStream:199 self.backend.received_data.append(b"--- START_TLS(%s) ---" % hostname.encode())200 return MockRawSocketStream(self.backend)

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

lines 201–217why, one step back
201
202 def get_http_version(self) -> str:203 return "HTTP/1.1"204205 def write_no_block(self, data: bytes) -> None:206 self.backend.received_data.append(data)207208 async def write(self, data: bytes, timeout: TimeoutConfig = None) -> None:209 if data:210 self.write_no_block(data)211212 async def read(self, n, timeout, flag=None) -> bytes:213 await sleep(self.backend.backend, 0)214 if not self.backend.data_to_send:215 return b""216 return self.backend.data_to_send.pop(0)217

Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085

lines 218–220why, one step back
218 def is_connection_dropped(self) -> bool:
219 return False220

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

lines 221–222why, one step back
221 async def close(self) -> None:
222 pass