Skip to content
Myr

utils.py

This file

Path

tests/dispatch/utils.py

212 lines · 7.3 KiB · Python

Last changed by

Bump up flow control defaults (#629)Tom Christiebefore adoption52c2c97

History of this file

Take it

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

Add missing async test cases (#269)Florimond Mancabefore adoptiona4b93b9

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

Tighten up top-level API to only expose public API (#608)Tom Christiebefore adoptiond15dc0b

line 8why, one step back
8from httpx import Request, Timeout

Refactor tests in the light of backend auto-detection (#615)Florimond Mancabefore adoptionab41a5d

line 9why, one step back
9from httpx.concurrency.base import BaseSocketStream, lookup_backend

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

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

Add missing async test cases (#269)Florimond Mancabefore adoptiona4b93b9

lines 11–12why, one step back
11
12

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

line 13why, one step back
13class MockHTTP2Backend:

Refactor tests in the light of backend auto-detection (#615)Florimond Mancabefore adoptionab41a5d

line 14why, one step back
14 def __init__(self, app, backend="auto"):

Add missing async test cases (#269)Florimond Mancabefore adoptiona4b93b9

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

Refactor tests in the light of backend auto-detection (#615)Florimond Mancabefore adoptionab41a5d

line 16why, one step back
16 self.backend = lookup_backend(backend)

Add missing async test cases (#269)Florimond Mancabefore adoptiona4b93b9

lines 17–18why, one step back
17 self.server = None
18

Stream -> TCPStream (#339)Florimond Mancabefore adoption315a18b

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

Add missing async test cases (#269)Florimond Mancabefore adoptiona4b93b9

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

TimeoutConfig -> Timeout (#591)Tom Christiebefore adoptionc033ed1

line 24why, one step back
24 timeout: Timeout,

Rename BaseTCPStream/TCPStream to BaseSocketStream/SocketStream (#517)Jonas Lundbergbefore adoption1a32cf0

line 25why, one step back
25 ) -> BaseSocketStream:

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

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

Add missing async test cases (#269)Florimond Mancabefore adoptiona4b93b9

lines 27–28why, one step back
27 return self.server
28

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

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

Add missing async test cases (#269)Florimond Mancabefore adoptiona4b93b9

line 32why, one step back
32

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

line 33why, one step back
33

Rename BaseTCPStream/TCPStream to BaseSocketStream/SocketStream (#517)Jonas Lundbergbefore adoption1a32cf0

line 34why, one step back
34class MockHTTP2Server(BaseSocketStream):

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

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

Add missing async test cases (#269)Florimond Mancabefore adoptiona4b93b9

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

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

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

Add missing async test cases (#269)Florimond Mancabefore adoptiona4b93b9

lines 40–42why, one step back
40 self.buffer = b""
41 self.requests = {}42 self.close_connection = False

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

line 43why, one step back
43 self.return_data = {}

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

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

Add missing async test cases (#269)Florimond Mancabefore adoptiona4b93b9

line 45why, one step back
45

Rename BaseTCPStream/TCPStream to BaseSocketStream/SocketStream (#517)Jonas Lundbergbefore adoption1a32cf0

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

Add missing async test cases (#269)Florimond Mancabefore adoptiona4b93b9

lines 47–51why, one step back
47
48 def get_http_version(self) -> str:49 return "HTTP/2"5051 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)

Add missing async test cases (#269)Florimond Mancabefore adoptiona4b93b9

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

Add missing async test cases (#269)Florimond Mancabefore adoptiona4b93b9

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

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

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

Add missing async test cases (#269)Florimond Mancabefore adoptiona4b93b9

lines 79–132why, one step back
79
80 async def write(self, data: bytes, timeout) -> None:81 self.write_no_block(data)8283 async def close(self) -> None:84 pass8586 def is_connection_dropped(self) -> bool:87 return self.close_connection8889 # Server implementation9091 def request_received(self, headers, stream_id):92 """93 Handler for when the initial part of the HTTP request is received.94 """95 if stream_id not in self.requests:96 self.requests[stream_id] = []97 self.requests[stream_id].append({"headers": headers, "data": b""})9899 def receive_data(self, data, stream_id):100 """101 Handler for when a data part of the HTTP request is received.102 """103 self.requests[stream_id][-1]["data"] += data104105 def stream_complete(self, stream_id):106 """107 Handler for when the HTTP request is completed.108 """109 request = self.requests[stream_id].pop(0)110 if not self.requests[stream_id]:111 del self.requests[stream_id]112113 headers_dict = dict(request["headers"])114115 method = headers_dict[b":method"].decode("ascii")116 url = "%s://%s%s" % (117 headers_dict[b":scheme"].decode("ascii"),118 headers_dict[b":authority"].decode("ascii"),119 headers_dict[b":path"].decode("ascii"),120 )121 headers = [(k, v) for k, v in request["headers"] if not k.startswith(b":")]122 data = request["data"]123124 # Call out to the app.125 request = Request(method, url, headers=headers, data=data)126 response = self.app(request)127128 # Write the response to the buffer.129 status_code_bytes = str(response.status_code).encode("ascii")130 response_headers = [(b":status", status_code_bytes)] + response.headers.raw131132 self.conn.send_headers(stream_id, response_headers)

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

lines 133–154why, one step back
133 self.buffer += self.conn.data_to_send()
134 self.return_data[stream_id] = response.content135 self.send_return_data(stream_id)136137 def send_return_data(self, stream_id):138 while self.return_data[stream_id]:139 flow_control = self.conn.local_flow_control_window(stream_id)140 chunk_size = min(141 len(self.return_data[stream_id]),142 flow_control,143 self.conn.max_outbound_frame_size,144 )145 if chunk_size == 0:146 return147 else:148 chunk, self.return_data[stream_id] = (149 self.return_data[stream_id][:chunk_size],150 self.return_data[stream_id][chunk_size:],151 )152 self.conn.send_data(stream_id, chunk)153 self.buffer += self.conn.data_to_send()154 self.conn.end_stream(stream_id)

Add missing async test cases (#269)Florimond Mancabefore adoptiona4b93b9

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

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

lines 156–158why, one step back
156
157158class MockRawSocketBackend:

Refactor tests in the light of backend auto-detection (#615)Florimond Mancabefore adoptionab41a5d

lines 159–160why, one step back
159 def __init__(self, data_to_send=b"", backend="auto"):
160 self.backend = lookup_backend(backend)

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

lines 161–164why, one step back
161 self.data_to_send = data_to_send
162 self.received_data = []163 self.stream = MockRawSocketStream(self)164

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

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

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

lines 166–169why, one step back
166 self,
167 hostname: str,168 port: int,169 ssl_context: typing.Optional[ssl.SSLContext],

TimeoutConfig -> Timeout (#591)Tom Christiebefore adoptionc033ed1

line 170why, one step back
170 timeout: Timeout,

Rename BaseTCPStream/TCPStream to BaseSocketStream/SocketStream (#517)Jonas Lundbergbefore adoption1a32cf0

line 171why, one step back
171 ) -> BaseSocketStream:

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

lines 172–181why, one step back
172 self.received_data.append(
173 b"--- CONNECT(%s, %d) ---" % (hostname.encode(), port)174 )175 return self.stream176177 # Defer all other attributes and methods to the underlying backend.178 def __getattr__(self, name: str) -> typing.Any:179 return getattr(self.backend, name)180181

Rename BaseTCPStream/TCPStream to BaseSocketStream/SocketStream (#517)Jonas Lundbergbefore adoption1a32cf0

line 182why, one step back
182class MockRawSocketStream(BaseSocketStream):

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

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

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

lines 185–186why, one step back
185
186 async def start_tls(

TimeoutConfig -> Timeout (#591)Tom Christiebefore adoptionc033ed1

line 187why, one step back
187 self, hostname: str, ssl_context: ssl.SSLContext, timeout: Timeout

Rename BaseTCPStream/TCPStream to BaseSocketStream/SocketStream (#517)Jonas Lundbergbefore adoption1a32cf0

line 188why, one step back
188 ) -> BaseSocketStream:

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

lines 189–190why, one step back
189 self.backend.received_data.append(b"--- START_TLS(%s) ---" % hostname.encode())
190 return MockRawSocketStream(self.backend)

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

lines 191–197why, one step back
191
192 def get_http_version(self) -> str:193 return "HTTP/1.1"194195 def write_no_block(self, data: bytes) -> None:196 self.backend.received_data.append(data)197

TimeoutConfig -> Timeout (#591)Tom Christiebefore adoptionc033ed1

line 198why, one step back
198 async def write(self, data: bytes, timeout: Timeout = None) -> None:

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

lines 199–207why, one step back
199 if data:
200 self.write_no_block(data)201202 async def read(self, n, timeout, flag=None) -> bytes:203 await sleep(self.backend.backend, 0)204 if not self.backend.data_to_send:205 return b""206 return self.backend.data_to_send.pop(0)207

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

lines 208–210why, one step back
208 def is_connection_dropped(self) -> bool:
209 return False210

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

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