utils.py
This file
Path
tests/dispatch/utils.py
224 lines · 7.9 KiB · Python
Last changed by
Tighten up top-level API to only expose public API (#608)Tom Christiebefore adoptiond15dc0b
History of this fileTake it
The walk stopped after 200 commits: lines older than 9c7d23c point at it.
Enforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
lines 1–7why, one step back1import ssl2import typing34import h2.config5import h2.connection6import h2.events7Tighten up top-level API to only expose public API (#608)Tom Christiebefore adoptiond15dc0b
lines 8–10why, one step back8from httpx import Request, Timeout9from httpx.concurrency.asyncio import AsyncioBackend10from httpx.concurrency.base import BaseSocketStreamParametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
line 11why, one step back11from tests.concurrency import sleepEnforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
lines 12–13why, one step back1213Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
lines 14–15why, one step back14class MockHTTP2Backend:15 def __init__(self, app, backend=None):Enforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
line 16why, one step back16 self.app = appParametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
line 17why, one step back17 self.backend = AsyncioBackend() if backend is None else backendEnforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
lines 18–19why, one step back18 self.server = None19Stream -> TCPStream (#339)Florimond Mancabefore adoption315a18b
line 20why, one step back20 async def open_tcp_stream(Enforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
lines 21–24why, one step back21 self,22 hostname: str,23 port: int,24 ssl_context: typing.Optional[ssl.SSLContext],TimeoutConfig -> Timeout (#591)Tom Christiebefore adoptionc033ed1
line 25why, one step back25 timeout: Timeout,Rename BaseTCPStream/TCPStream to BaseSocketStream/SocketStream (#517)Jonas Lundbergbefore adoption1a32cf0
line 26why, one step back26 ) -> BaseSocketStream:Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
line 27why, one step back27 self.server = MockHTTP2Server(self.app, backend=self.backend)Merge pull request #255 from encode/refactor/stream-interfaceTom Christiebefore adoption3069227
line 28why, one step back28 return self.serverEnforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
line 29why, one step back29Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
lines 30–32why, one step back30 # Defer all other attributes and methods to the underlying backend.31 def __getattr__(self, name: str) -> typing.Any:32 return getattr(self.backend, name)Enforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
line 33why, one step back33Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
line 34why, one step back34Rename BaseTCPStream/TCPStream to BaseSocketStream/SocketStream (#517)Jonas Lundbergbefore adoption1a32cf0
line 35why, one step back35class MockHTTP2Server(BaseSocketStream):Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
line 36why, one step back36 def __init__(self, app, backend):Enforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
lines 37–39why, one step back37 config = h2.config.H2Configuration(client_side=False)38 self.conn = h2.connection.H2Connection(config=config)39 self.app = appParametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
line 40why, one step back40 self.backend = backendEnforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
lines 41–43why, one step back41 self.buffer = b""42 self.requests = {}43 self.close_connection = FalseFix bug in calculating maximum frame size (#153)IsaacBenghiatbefore adoptionab9cd0e
lines 44–45why, one step back44 self.return_data = {}45 self.returning = {}Remove ENABLE_CONNECT_PROTOCOL from HTTP/2 Settings (#373)Seth Michael Larsonbefore adoptionb574230
line 46why, one step back46 self.settings_changed = []Enforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
line 47why, one step back47Rename BaseTCPStream/TCPStream to BaseSocketStream/SocketStream (#517)Jonas Lundbergbefore adoption1a32cf0
line 48why, one step back48 # Socket stream interfaceEnforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
line 49why, one step back49Merge pull request #255 from encode/refactor/stream-interfaceTom Christiebefore adoption3069227
lines 50–52why, one step back50 def get_http_version(self) -> str:51 return "HTTP/2"52Enforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
line 53why, one step back53 async def read(self, n, timeout, flag=None) -> bytes:Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
line 54why, one step back54 await sleep(self.backend, 0)Enforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
lines 55–65why, one step back55 send, self.buffer = self.buffer[:n], self.buffer[n:]56 return send5758 def write_no_block(self, data: bytes) -> None: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 back66 # This should send an UPDATE_WINDOW for both the stream and the67 # 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()Enforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
lines 77–78why, one step back77 elif isinstance(event, h2.events.StreamEnded):78 self.stream_complete(event.stream_id)Fix bug in calculating maximum frame size (#153)IsaacBenghiatbefore adoptionab9cd0e
lines 79–86why, one step back79 elif isinstance(event, h2.events.WindowUpdated):80 if event.stream_id == 0:81 for key, value in self.returning.items():82 if value:83 self.send_return_data(key)84 # This will throw an error if the event is for a not-yet created stream85 elif self.returning[event.stream_id]:86 self.send_return_data(event.stream_id)Remove ENABLE_CONNECT_PROTOCOL from HTTP/2 Settings (#373)Seth Michael Larsonbefore adoptionb574230
lines 87–88why, one step back87 elif isinstance(event, h2.events.RemoteSettingsChanged):88 self.settings_changed.append(event)Enforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
lines 89–142why, one step back8990 async def write(self, data: bytes, timeout) -> None:91 self.write_no_block(data)9293 async def close(self) -> None:94 pass9596 def is_connection_dropped(self) -> bool:97 return self.close_connection9899 # Server implementation100101 def request_received(self, headers, stream_id):102 """103 Handler for when the initial part of the HTTP request is received.104 """105 if stream_id not in self.requests:106 self.requests[stream_id] = []107 self.requests[stream_id].append({"headers": headers, "data": b""})108109 def receive_data(self, data, stream_id):110 """111 Handler for when a data part of the HTTP request is received.112 """113 self.requests[stream_id][-1]["data"] += data114115 def stream_complete(self, stream_id):116 """117 Handler for when the HTTP request is completed.118 """119 request = self.requests[stream_id].pop(0)120 if not self.requests[stream_id]:121 del self.requests[stream_id]122123 headers_dict = dict(request["headers"])124125 method = headers_dict[b":method"].decode("ascii")126 url = "%s://%s%s" % (127 headers_dict[b":scheme"].decode("ascii"),128 headers_dict[b":authority"].decode("ascii"),129 headers_dict[b":path"].decode("ascii"),130 )131 headers = [(k, v) for k, v in request["headers"] if not k.startswith(b":")]132 data = request["data"]133134 # Call out to the app.135 request = Request(method, url, headers=headers, data=data)136 response = self.app(request)137138 # Write the response to the buffer.139 status_code_bytes = str(response.status_code).encode("ascii")140 response_headers = [(b":status", status_code_bytes)] + response.headers.raw141142 self.conn.send_headers(stream_id, response_headers)Fix bug in calculating maximum frame size (#153)IsaacBenghiatbefore adoptionab9cd0e
lines 143–166why, one step back143 self.buffer += self.conn.data_to_send()144 self.return_data[stream_id] = response.content145 self.returning[stream_id] = True146 self.send_return_data(stream_id)147148 def send_return_data(self, stream_id):149 while self.return_data[stream_id]:150 flow_control = self.conn.local_flow_control_window(stream_id)151 chunk_size = min(152 len(self.return_data[stream_id]),153 flow_control,154 self.conn.max_outbound_frame_size,155 )156 if chunk_size == 0:157 return158 else:159 chunk, self.return_data[stream_id] = (160 self.return_data[stream_id][:chunk_size],161 self.return_data[stream_id][chunk_size:],162 )163 self.conn.send_data(stream_id, chunk)164 self.buffer += self.conn.data_to_send()165 self.returning[stream_id] = False166 self.conn.end_stream(stream_id)Enforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
line 167why, one step back167 self.buffer += self.conn.data_to_send()Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 168–176why, one step back168169170class MockRawSocketBackend:171 def __init__(self, data_to_send=b"", backend=None):172 self.backend = AsyncioBackend() if backend is None else backend173 self.data_to_send = data_to_send174 self.received_data = []175 self.stream = MockRawSocketStream(self)176Fix remaining references to BaseStream in tests (#347)Florimond Mancabefore adoption6c6148e
line 177why, one step back177 async def open_tcp_stream(Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 178–181why, one step back178 self,179 hostname: str,180 port: int,181 ssl_context: typing.Optional[ssl.SSLContext],TimeoutConfig -> Timeout (#591)Tom Christiebefore adoptionc033ed1
line 182why, one step back182 timeout: Timeout,Rename BaseTCPStream/TCPStream to BaseSocketStream/SocketStream (#517)Jonas Lundbergbefore adoption1a32cf0
line 183why, one step back183 ) -> BaseSocketStream:Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 184–193why, one step back184 self.received_data.append(185 b"--- CONNECT(%s, %d) ---" % (hostname.encode(), port)186 )187 return self.stream188189 # Defer all other attributes and methods to the underlying backend.190 def __getattr__(self, name: str) -> typing.Any:191 return getattr(self.backend, name)192193Rename BaseTCPStream/TCPStream to BaseSocketStream/SocketStream (#517)Jonas Lundbergbefore adoption1a32cf0
line 194why, one step back194class MockRawSocketStream(BaseSocketStream):Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 195–196why, one step back195 def __init__(self, backend: MockRawSocketBackend):196 self.backend = backendMake start_tls a method on streams & return a new stream (#484)Jamie Hewlandbefore adoption644e8fc
lines 197–198why, one step back197198 async def start_tls(TimeoutConfig -> Timeout (#591)Tom Christiebefore adoptionc033ed1
line 199why, one step back199 self, hostname: str, ssl_context: ssl.SSLContext, timeout: TimeoutRename BaseTCPStream/TCPStream to BaseSocketStream/SocketStream (#517)Jonas Lundbergbefore adoption1a32cf0
line 200why, one step back200 ) -> BaseSocketStream:Make start_tls a method on streams & return a new stream (#484)Jamie Hewlandbefore adoption644e8fc
lines 201–202why, one step back201 self.backend.received_data.append(b"--- START_TLS(%s) ---" % hostname.encode())202 return MockRawSocketStream(self.backend)Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 203–209why, one step back203204 def get_http_version(self) -> str:205 return "HTTP/1.1"206207 def write_no_block(self, data: bytes) -> None:208 self.backend.received_data.append(data)209TimeoutConfig -> Timeout (#591)Tom Christiebefore adoptionc033ed1
line 210why, one step back210 async def write(self, data: bytes, timeout: Timeout = None) -> None:Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 211–219why, one step back211 if data:212 self.write_no_block(data)213214 async def read(self, n, timeout, flag=None) -> bytes:215 await sleep(self.backend.backend, 0)216 if not self.backend.data_to_send:217 return b""218 return self.backend.data_to_send.pop(0)219Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085
lines 220–222why, one step back220 def is_connection_dropped(self) -> bool:221 return False222Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 223–224why, one step back223 async def close(self) -> None:224 pass