utils.py
This file
Path
tests/dispatch/utils.py
223 lines · 7.8 KiB · Python
Last changed by
Refactor tests in the light of backend auto-detection (#615)Florimond Mancabefore adoptionab41a5d
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
line 8why, one step back8from httpx import Request, TimeoutRefactor tests in the light of backend auto-detection (#615)Florimond Mancabefore adoptionab41a5d
line 9why, one step back9from httpx.concurrency.base import BaseSocketStream, lookup_backendParametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
line 10why, one step back10from tests.concurrency import sleepEnforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
lines 11–12why, one step back1112Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
line 13why, one step back13class MockHTTP2Backend:Refactor tests in the light of backend auto-detection (#615)Florimond Mancabefore adoptionab41a5d
line 14why, one step back14 def __init__(self, app, backend="auto"):Enforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
line 15why, one step back15 self.app = appRefactor tests in the light of backend auto-detection (#615)Florimond Mancabefore adoptionab41a5d
line 16why, one step back16 self.backend = lookup_backend(backend)Enforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
lines 17–18why, one step back17 self.server = None18Stream -> TCPStream (#339)Florimond Mancabefore adoption315a18b
line 19why, one step back19 async def open_tcp_stream(Enforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
lines 20–23why, one step back20 self,21 hostname: str,22 port: int,23 ssl_context: typing.Optional[ssl.SSLContext],TimeoutConfig -> Timeout (#591)Tom Christiebefore adoptionc033ed1
line 24why, one step back24 timeout: Timeout,Rename BaseTCPStream/TCPStream to BaseSocketStream/SocketStream (#517)Jonas Lundbergbefore adoption1a32cf0
line 25why, one step back25 ) -> BaseSocketStream:Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
line 26why, one step back26 self.server = MockHTTP2Server(self.app, backend=self.backend)Merge pull request #255 from encode/refactor/stream-interfaceTom Christiebefore adoption3069227
line 27why, one step back27 return self.serverEnforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
line 28why, one step back28Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
lines 29–31why, one step back29 # Defer all other attributes and methods to the underlying backend.30 def __getattr__(self, name: str) -> typing.Any:31 return getattr(self.backend, name)Enforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
line 32why, one step back32Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
line 33why, one step back33Rename BaseTCPStream/TCPStream to BaseSocketStream/SocketStream (#517)Jonas Lundbergbefore adoption1a32cf0
line 34why, one step back34class MockHTTP2Server(BaseSocketStream):Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
line 35why, one step back35 def __init__(self, app, backend):Enforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
lines 36–38why, one step back36 config = h2.config.H2Configuration(client_side=False)37 self.conn = h2.connection.H2Connection(config=config)38 self.app = appParametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
line 39why, one step back39 self.backend = backendEnforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
lines 40–42why, one step back40 self.buffer = b""41 self.requests = {}42 self.close_connection = FalseFix bug in calculating maximum frame size (#153)IsaacBenghiatbefore adoptionab9cd0e
lines 43–44why, one step back43 self.return_data = {}44 self.returning = {}Remove ENABLE_CONNECT_PROTOCOL from HTTP/2 Settings (#373)Seth Michael Larsonbefore adoptionb574230
line 45why, one step back45 self.settings_changed = []Enforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
line 46why, one step back46Rename BaseTCPStream/TCPStream to BaseSocketStream/SocketStream (#517)Jonas Lundbergbefore adoption1a32cf0
line 47why, one step back47 # Socket stream interfaceEnforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
line 48why, one step back48Merge pull request #255 from encode/refactor/stream-interfaceTom Christiebefore adoption3069227
lines 49–51why, one step back49 def get_http_version(self) -> str:50 return "HTTP/2"51Enforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
line 52why, one step back52 async def read(self, n, timeout, flag=None) -> bytes:Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
line 53why, one step back53 await sleep(self.backend, 0)Enforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
lines 54–64why, one step back54 send, self.buffer = self.buffer[:n], self.buffer[n:]55 return send5657 def write_no_block(self, data: bytes) -> None:58 events = self.conn.receive_data(data)59 self.buffer += self.conn.data_to_send()60 for event in events:61 if isinstance(event, h2.events.RequestReceived):62 self.request_received(event.headers, event.stream_id)63 elif isinstance(event, h2.events.DataReceived):64 self.receive_data(event.data, event.stream_id)Fix bug in calculating maximum frame size (#153)IsaacBenghiatbefore adoptionab9cd0e
lines 65–75why, one step back65 # This should send an UPDATE_WINDOW for both the stream and the66 # connection increasing it by the amount67 # consumed keeping the flow control window constant68 flow_control_consumed = event.flow_controlled_length69 if flow_control_consumed > 0:70 self.conn.increment_flow_control_window(flow_control_consumed)71 self.buffer += self.conn.data_to_send()72 self.conn.increment_flow_control_window(73 flow_control_consumed, event.stream_id74 )75 self.buffer += self.conn.data_to_send()Enforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
lines 76–77why, one step back76 elif isinstance(event, h2.events.StreamEnded):77 self.stream_complete(event.stream_id)Fix bug in calculating maximum frame size (#153)IsaacBenghiatbefore adoptionab9cd0e
lines 78–85why, one step back78 elif isinstance(event, h2.events.WindowUpdated):79 if event.stream_id == 0:80 for key, value in self.returning.items():81 if value:82 self.send_return_data(key)83 # This will throw an error if the event is for a not-yet created stream84 elif self.returning[event.stream_id]:85 self.send_return_data(event.stream_id)Remove ENABLE_CONNECT_PROTOCOL from HTTP/2 Settings (#373)Seth Michael Larsonbefore adoptionb574230
lines 86–87why, one step back86 elif isinstance(event, h2.events.RemoteSettingsChanged):87 self.settings_changed.append(event)Enforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
lines 88–141why, one step back8889 async def write(self, data: bytes, timeout) -> None:90 self.write_no_block(data)9192 async def close(self) -> None:93 pass9495 def is_connection_dropped(self) -> bool:96 return self.close_connection9798 # Server implementation99100 def request_received(self, headers, stream_id):101 """102 Handler for when the initial part of the HTTP request is received.103 """104 if stream_id not in self.requests:105 self.requests[stream_id] = []106 self.requests[stream_id].append({"headers": headers, "data": b""})107108 def receive_data(self, data, stream_id):109 """110 Handler for when a data part of the HTTP request is received.111 """112 self.requests[stream_id][-1]["data"] += data113114 def stream_complete(self, stream_id):115 """116 Handler for when the HTTP request is completed.117 """118 request = self.requests[stream_id].pop(0)119 if not self.requests[stream_id]:120 del self.requests[stream_id]121122 headers_dict = dict(request["headers"])123124 method = headers_dict[b":method"].decode("ascii")125 url = "%s://%s%s" % (126 headers_dict[b":scheme"].decode("ascii"),127 headers_dict[b":authority"].decode("ascii"),128 headers_dict[b":path"].decode("ascii"),129 )130 headers = [(k, v) for k, v in request["headers"] if not k.startswith(b":")]131 data = request["data"]132133 # Call out to the app.134 request = Request(method, url, headers=headers, data=data)135 response = self.app(request)136137 # Write the response to the buffer.138 status_code_bytes = str(response.status_code).encode("ascii")139 response_headers = [(b":status", status_code_bytes)] + response.headers.raw140141 self.conn.send_headers(stream_id, response_headers)Fix bug in calculating maximum frame size (#153)IsaacBenghiatbefore adoptionab9cd0e
lines 142–165why, one step back142 self.buffer += self.conn.data_to_send()143 self.return_data[stream_id] = response.content144 self.returning[stream_id] = True145 self.send_return_data(stream_id)146147 def send_return_data(self, stream_id):148 while self.return_data[stream_id]:149 flow_control = self.conn.local_flow_control_window(stream_id)150 chunk_size = min(151 len(self.return_data[stream_id]),152 flow_control,153 self.conn.max_outbound_frame_size,154 )155 if chunk_size == 0:156 return157 else:158 chunk, self.return_data[stream_id] = (159 self.return_data[stream_id][:chunk_size],160 self.return_data[stream_id][chunk_size:],161 )162 self.conn.send_data(stream_id, chunk)163 self.buffer += self.conn.data_to_send()164 self.returning[stream_id] = False165 self.conn.end_stream(stream_id)Enforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
line 166why, one step back166 self.buffer += self.conn.data_to_send()Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 167–169why, one step back167168169class MockRawSocketBackend:Refactor tests in the light of backend auto-detection (#615)Florimond Mancabefore adoptionab41a5d
lines 170–171why, one step back170 def __init__(self, data_to_send=b"", backend="auto"):171 self.backend = lookup_backend(backend)Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 172–175why, one step back172 self.data_to_send = data_to_send173 self.received_data = []174 self.stream = MockRawSocketStream(self)175Fix remaining references to BaseStream in tests (#347)Florimond Mancabefore adoption6c6148e
line 176why, one step back176 async def open_tcp_stream(Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 177–180why, one step back177 self,178 hostname: str,179 port: int,180 ssl_context: typing.Optional[ssl.SSLContext],TimeoutConfig -> Timeout (#591)Tom Christiebefore adoptionc033ed1
line 181why, one step back181 timeout: Timeout,Rename BaseTCPStream/TCPStream to BaseSocketStream/SocketStream (#517)Jonas Lundbergbefore adoption1a32cf0
line 182why, one step back182 ) -> BaseSocketStream:Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 183–192why, one step back183 self.received_data.append(184 b"--- CONNECT(%s, %d) ---" % (hostname.encode(), port)185 )186 return self.stream187188 # Defer all other attributes and methods to the underlying backend.189 def __getattr__(self, name: str) -> typing.Any:190 return getattr(self.backend, name)191192Rename BaseTCPStream/TCPStream to BaseSocketStream/SocketStream (#517)Jonas Lundbergbefore adoption1a32cf0
line 193why, one step back193class MockRawSocketStream(BaseSocketStream):Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 194–195why, one step back194 def __init__(self, backend: MockRawSocketBackend):195 self.backend = backendMake start_tls a method on streams & return a new stream (#484)Jamie Hewlandbefore adoption644e8fc
lines 196–197why, one step back196197 async def start_tls(TimeoutConfig -> Timeout (#591)Tom Christiebefore adoptionc033ed1
line 198why, one step back198 self, hostname: str, ssl_context: ssl.SSLContext, timeout: TimeoutRename BaseTCPStream/TCPStream to BaseSocketStream/SocketStream (#517)Jonas Lundbergbefore adoption1a32cf0
line 199why, one step back199 ) -> BaseSocketStream:Make start_tls a method on streams & return a new stream (#484)Jamie Hewlandbefore adoption644e8fc
lines 200–201why, one step back200 self.backend.received_data.append(b"--- START_TLS(%s) ---" % hostname.encode())201 return MockRawSocketStream(self.backend)Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 202–208why, one step back202203 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)208TimeoutConfig -> Timeout (#591)Tom Christiebefore adoptionc033ed1
line 209why, one step back209 async def write(self, data: bytes, timeout: Timeout = None) -> None:Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 210–218why, one step back210 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)218Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085
lines 219–221why, one step back219 def is_connection_dropped(self) -> bool:220 return False221Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 222–223why, one step back222 async def close(self) -> None:223 pass