Skip to content
Myr

utils.py

This file

Path

tests/dispatch/utils.py

209 lines · 7.1 KiB · Python

Last changed by

Rename `concurrency` directory to `backends` (#662)Andrés Álvarezbefore adoptione34df7a

History of this file

Take it

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

Merge pull request #314 from dobrovolsky/drop_npnTom Christiebefore adoptioncbe7616

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

Rename `concurrency` directory to `backends` (#662)Andrés Álvarezbefore adoptione34df7a

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

Merge pull request #314 from dobrovolsky/drop_npnTom Christiebefore adoptioncbe7616

lines 10–13why, one step back
10from tests.concurrency import sleep
111213class 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"):

Merge pull request #314 from dobrovolsky/drop_npnTom Christiebefore adoptioncbe7616

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)

Merge pull request #314 from dobrovolsky/drop_npnTom Christiebefore adoptioncbe7616

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(

Merge pull request #314 from dobrovolsky/drop_npnTom Christiebefore adoptioncbe7616

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:

Merge pull request #314 from dobrovolsky/drop_npnTom Christiebefore adoptioncbe7616

lines 26–33why, one step back
26 self.server = MockHTTP2Server(self.app, backend=self.backend)
27 return self.server2829 # Defer all other attributes and methods to the underlying backend.30 def __getattr__(self, name: str) -> typing.Any:31 return getattr(self.backend, name)3233

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

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

Merge pull request #314 from dobrovolsky/drop_npnTom Christiebefore adoptioncbe7616

lines 35–42why, one step back
35 def __init__(self, app, backend):
36 config = h2.config.H2Configuration(client_side=False)37 self.conn = h2.connection.H2Connection(config=config)38 self.app = app39 self.backend = backend40 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 = []

Merge pull request #314 from dobrovolsky/drop_npnTom Christiebefore adoptioncbe7616

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

Merge pull request #314 from dobrovolsky/drop_npnTom Christiebefore adoptioncbe7616

lines 47–55why, 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:52 await sleep(self.backend, 0)53 send, self.buffer = self.buffer[:n], self.buffer[n:]54 return send55

Added RequestContent (#636)Tom Christiebefore adoption8d4f182

lines 56–58why, one step back
56 async def write(self, data: bytes, timeout) -> None:
57 if not data:58 return

Merge pull request #314 from dobrovolsky/drop_npnTom Christiebefore adoptioncbe7616

lines 59–65why, one step back
59 events = self.conn.receive_data(data)
60 self.buffer += self.conn.data_to_send()61 for event in events:62 if isinstance(event, h2.events.RequestReceived):63 self.request_received(event.headers, event.stream_id)64 elif isinstance(event, h2.events.DataReceived):65 self.receive_data(event.data, event.stream_id)

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

lines 66–76why, one step back
66 # This should send an UPDATE_WINDOW for both the stream and the
67 # connection increasing it by the amount68 # consumed keeping the flow control window constant69 flow_control_consumed = event.flow_controlled_length70 if flow_control_consumed > 0:71 self.conn.increment_flow_control_window(flow_control_consumed)72 self.buffer += self.conn.data_to_send()73 self.conn.increment_flow_control_window(74 flow_control_consumed, event.stream_id75 )76 self.buffer += self.conn.data_to_send()

Merge pull request #314 from dobrovolsky/drop_npnTom Christiebefore adoptioncbe7616

line 77why, one step back
77 elif isinstance(event, h2.events.StreamEnded):

Added RequestContent (#636)Tom Christiebefore adoption8d4f182

line 78why, one step back
78 await self.stream_complete(event.stream_id)

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

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

Merge pull request #314 from dobrovolsky/drop_npnTom Christiebefore adoptioncbe7616

lines 81–103why, one step back
81
82 async def close(self) -> None:83 pass8485 def is_connection_dropped(self) -> bool:86 return self.close_connection8788 # Server implementation8990 def request_received(self, headers, stream_id):91 """92 Handler for when the initial part of the HTTP request is received.93 """94 if stream_id not in self.requests:95 self.requests[stream_id] = []96 self.requests[stream_id].append({"headers": headers, "data": b""})9798 def receive_data(self, data, stream_id):99 """100 Handler for when a data part of the HTTP request is received.101 """102 self.requests[stream_id][-1]["data"] += data103

Added RequestContent (#636)Tom Christiebefore adoption8d4f182

line 104why, one step back
104 async def stream_complete(self, stream_id):

Merge pull request #314 from dobrovolsky/drop_npnTom Christiebefore adoptioncbe7616

lines 105–124why, one step back
105 """
106 Handler for when the HTTP request is completed.107 """108 request = self.requests[stream_id].pop(0)109 if not self.requests[stream_id]:110 del self.requests[stream_id]111112 headers_dict = dict(request["headers"])113114 method = headers_dict[b":method"].decode("ascii")115 url = "%s://%s%s" % (116 headers_dict[b":scheme"].decode("ascii"),117 headers_dict[b":authority"].decode("ascii"),118 headers_dict[b":path"].decode("ascii"),119 )120 headers = [(k, v) for k, v in request["headers"] if not k.startswith(b":")]121 data = request["data"]122123 # Call out to the app.124 request = Request(method, url, headers=headers, data=data)

Added RequestContent (#636)Tom Christiebefore adoption8d4f182

line 125why, one step back
125 response = await self.app(request)

Merge pull request #314 from dobrovolsky/drop_npnTom Christiebefore adoptioncbe7616

lines 126–131why, one step back
126
127 # Write the response to the buffer.128 status_code_bytes = str(response.status_code).encode("ascii")129 response_headers = [(b":status", status_code_bytes)] + response.headers.raw130131 self.conn.send_headers(stream_id, response_headers)

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

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

Merge pull request #314 from dobrovolsky/drop_npnTom Christiebefore adoptioncbe7616

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

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

lines 155–157why, one step back
155
156157class MockRawSocketBackend:

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

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

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

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

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

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

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

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

TimeoutConfig -> Timeout (#591)Tom Christiebefore adoptionc033ed1

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

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

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

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

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

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

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

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

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

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

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

TimeoutConfig -> Timeout (#591)Tom Christiebefore adoptionc033ed1

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

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

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

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

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

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

lines 190–193why, one step back
190
191 def get_http_version(self) -> str:192 return "HTTP/1.1"193

Added RequestContent (#636)Tom Christiebefore adoption8d4f182

lines 194–196why, one step back
194 async def write(self, data: bytes, timeout) -> None:
195 if not data:196 return

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

lines 197–204why, one step back
197 self.backend.received_data.append(data)
198199 async def read(self, n, timeout, flag=None) -> bytes:200 await sleep(self.backend.backend, 0)201 if not self.backend.data_to_send:202 return b""203 return self.backend.data_to_send.pop(0)204

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

lines 205–207why, one step back
205 def is_connection_dropped(self) -> bool:
206 return False207

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

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