Skip to content
Myr

utils.py

This file

Path

tests/dispatch/utils.py

223 lines · 7.7 KiB · Python

Last changed by

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

History of this file

Take it

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

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

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

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):

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

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

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

line 17why, one step back
17

Stream -> TCPStream (#339)Florimond Mancabefore adoption315a18b

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

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

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

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

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)

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

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):

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

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

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

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 = {}

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

line 44why, one step back
44

Stream -> TCPStream (#339)Florimond Mancabefore adoption315a18b

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

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

line 46why, one step back
46

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

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

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

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

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

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

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

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

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

lines 63–73why, one step back
63 # This should send an UPDATE_WINDOW for both the stream and the
64 # connection increasing it by the amount65 # consumed keeping the flow control window constant66 flow_control_consumed = event.flow_controlled_length67 if flow_control_consumed > 0:68 self.conn.increment_flow_control_window(flow_control_consumed)69 self.buffer += self.conn.data_to_send()70 self.conn.increment_flow_control_window(71 flow_control_consumed, event.stream_id72 )73 self.buffer += self.conn.data_to_send()

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

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

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

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

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

lines 84–89why, one step back
84
85 async def write(self, data: bytes, timeout) -> None:86 self.write_no_block(data)8788 async def close(self) -> None:89 pass

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

lines 90–92why, one step back
90
91 def is_connection_dropped(self) -> bool:92 return self.close_connection

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

lines 93–133why, one step back
93
94 # Server implementation9596 def request_received(self, headers, stream_id):97 """98 Handler for when the initial part of the HTTP request is received.99 """100 if stream_id not in self.requests:101 self.requests[stream_id] = []102 self.requests[stream_id].append({"headers": headers, "data": b""})103104 def receive_data(self, data, stream_id):105 """106 Handler for when a data part of the HTTP request is received.107 """108 self.requests[stream_id][-1]["data"] += data109110 def stream_complete(self, stream_id):111 """112 Handler for when the HTTP request is completed.113 """114 request = self.requests[stream_id].pop(0)115 if not self.requests[stream_id]:116 del self.requests[stream_id]117118 headers_dict = dict(request["headers"])119120 method = headers_dict[b":method"].decode("ascii")121 url = "%s://%s%s" % (122 headers_dict[b":scheme"].decode("ascii"),123 headers_dict[b":authority"].decode("ascii"),124 headers_dict[b":path"].decode("ascii"),125 )126 headers = [(k, v) for k, v in request["headers"] if not k.startswith(b":")]127 data = request["data"]128129 # Call out to the app.130 request = Request(method, url, headers=headers, data=data)131 response = self.app(request)132133 # Write the response to the buffer.

Status code tweaks (#77)Tom Christiebefore adoptionc12c271

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

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

lines 135–137why, one step back
135 response_headers = [(b":status", status_code_bytes)] + response.headers.raw
136137 self.conn.send_headers(stream_id, response_headers)

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

lines 138–161why, one step back
138 self.buffer += self.conn.data_to_send()
139 self.return_data[stream_id] = response.content140 self.returning[stream_id] = True141 self.send_return_data(stream_id)142143 def send_return_data(self, stream_id):144 while self.return_data[stream_id]:145 flow_control = self.conn.local_flow_control_window(stream_id)146 chunk_size = min(147 len(self.return_data[stream_id]),148 flow_control,149 self.conn.max_outbound_frame_size,150 )151 if chunk_size == 0:152 return153 else:154 chunk, self.return_data[stream_id] = (155 self.return_data[stream_id][:chunk_size],156 self.return_data[stream_id][chunk_size:],157 )158 self.conn.send_data(stream_id, chunk)159 self.buffer += self.conn.data_to_send()160 self.returning[stream_id] = False161 self.conn.end_stream(stream_id)

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

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

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

lines 163–171why, one step back
163
164165class MockRawSocketBackend:166 def __init__(self, data_to_send=b"", backend=None):167 self.backend = AsyncioBackend() if backend is None else backend168 self.data_to_send = data_to_send169 self.received_data = []170 self.stream = MockRawSocketStream(self)171

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

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

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

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

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

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

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

lines 179–185why, one step back
179 self.received_data.append(
180 b"--- CONNECT(%s, %d) ---" % (hostname.encode(), port)181 )182 return self.stream183184 async def start_tls(185 self,

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

line 186why, one step back
186 stream: BaseTCPStream,

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

lines 187–189why, one step back
187 hostname: str,
188 ssl_context: ssl.SSLContext,189 timeout: TimeoutConfig,

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

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

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

lines 191–198why, one step back
191 self.received_data.append(b"--- START_TLS(%s) ---" % hostname.encode())
192 return self.stream193194 # Defer all other attributes and methods to the underlying backend.195 def __getattr__(self, name: str) -> typing.Any:196 return getattr(self.backend, name)197198

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

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

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

lines 200–218why, one step back
200 def __init__(self, backend: MockRawSocketBackend):
201 self.backend = backend202203 def get_http_version(self) -> str:204 return "HTTP/1.1"205206 def write_no_block(self, data: bytes) -> None:207 self.backend.received_data.append(data)208209 async def write(self, data: bytes, timeout: TimeoutConfig = None) -> None:210 if data:211 self.write_no_block(data)212213 async def read(self, n, timeout, flag=None) -> bytes:214 await sleep(self.backend.backend, 0)215 if not self.backend.data_to_send:216 return b""217 return self.backend.data_to_send.pop(0)218

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

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

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

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