utils.py
This file
Path
tests/dispatch/utils.py
209 lines · 7.2 KiB · Python
Last changed by
Added RequestContent (#636)Tom Christiebefore adoption8d4f182
History of this fileTake it
The walk stopped after 200 commits: lines older than 9e420a5 point at it.
Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5
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_backendAutomatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5
lines 10–13why, one step back10from tests.concurrency import sleep111213class 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"):Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5
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)Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5
lines 17–18why, one step back17 self.server = None18Stream -> TCPStream (#339)Florimond Mancabefore adoption315a18b
line 19why, one step back19 async def open_tcp_stream(Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5
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:Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5
lines 26–33why, one step back26 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)3233Rename BaseTCPStream/TCPStream to BaseSocketStream/SocketStream (#517)Jonas Lundbergbefore adoption1a32cf0
line 34why, one step back34class MockHTTP2Server(BaseSocketStream):Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5
lines 35–42why, one step back35 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 = FalseFix bug in calculating maximum frame size (#153)IsaacBenghiatbefore adoptionab9cd0e
line 43why, one step back43 self.return_data = {}Remove ENABLE_CONNECT_PROTOCOL from HTTP/2 Settings (#373)Seth Michael Larsonbefore adoptionb574230
line 44why, one step back44 self.settings_changed = []Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5
line 45why, one step back45Rename BaseTCPStream/TCPStream to BaseSocketStream/SocketStream (#517)Jonas Lundbergbefore adoption1a32cf0
line 46why, one step back46 # Socket stream interfaceAutomatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5
lines 47–55why, one step back4748 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 send55Added RequestContent (#636)Tom Christiebefore adoption8d4f182
lines 56–58why, one step back56 async def write(self, data: bytes, timeout) -> None:57 if not data:58 returnAutomatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5
lines 59–65why, one step back59 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()Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5
line 77why, one step back77 elif isinstance(event, h2.events.StreamEnded):Added RequestContent (#636)Tom Christiebefore adoption8d4f182
line 78why, one step back78 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 back79 elif isinstance(event, h2.events.RemoteSettingsChanged):80 self.settings_changed.append(event)Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5
lines 81–103why, one step back8182 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"] += data103Added RequestContent (#636)Tom Christiebefore adoption8d4f182
line 104why, one step back104 async def stream_complete(self, stream_id):Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5
lines 105–124why, one step back105 """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 back125 response = await self.app(request)Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5
lines 126–131why, one step back126127 # 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 back132 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)Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5
line 154why, one step back154 self.buffer += self.conn.data_to_send()Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 155–157why, one step back155156157class MockRawSocketBackend:Refactor tests in the light of backend auto-detection (#615)Florimond Mancabefore adoptionab41a5d
lines 158–159why, one step back158 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 back160 self.data_to_send = data_to_send161 self.received_data = []162 self.stream = MockRawSocketStream(self)163Fix remaining references to BaseStream in tests (#347)Florimond Mancabefore adoption6c6148e
line 164why, one step back164 async def open_tcp_stream(Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 165–168why, one step back165 self,166 hostname: str,167 port: int,168 ssl_context: typing.Optional[ssl.SSLContext],TimeoutConfig -> Timeout (#591)Tom Christiebefore adoptionc033ed1
line 169why, one step back169 timeout: Timeout,Rename BaseTCPStream/TCPStream to BaseSocketStream/SocketStream (#517)Jonas Lundbergbefore adoption1a32cf0
line 170why, one step back170 ) -> BaseSocketStream:Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 171–180why, one step back171 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)179180Rename BaseTCPStream/TCPStream to BaseSocketStream/SocketStream (#517)Jonas Lundbergbefore adoption1a32cf0
line 181why, one step back181class MockRawSocketStream(BaseSocketStream):Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 182–183why, one step back182 def __init__(self, backend: MockRawSocketBackend):183 self.backend = backendMake start_tls a method on streams & return a new stream (#484)Jamie Hewlandbefore adoption644e8fc
lines 184–185why, one step back184185 async def start_tls(TimeoutConfig -> Timeout (#591)Tom Christiebefore adoptionc033ed1
line 186why, one step back186 self, hostname: str, ssl_context: ssl.SSLContext, timeout: TimeoutRename BaseTCPStream/TCPStream to BaseSocketStream/SocketStream (#517)Jonas Lundbergbefore adoption1a32cf0
line 187why, one step back187 ) -> BaseSocketStream:Make start_tls a method on streams & return a new stream (#484)Jamie Hewlandbefore adoption644e8fc
lines 188–189why, one step back188 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 back190191 def get_http_version(self) -> str:192 return "HTTP/1.1"193Added RequestContent (#636)Tom Christiebefore adoption8d4f182
lines 194–196why, one step back194 async def write(self, data: bytes, timeout) -> None:195 if not data:196 returnImplement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 197–204why, one step back197 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)204Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085
lines 205–207why, one step back205 def is_connection_dropped(self) -> bool:206 return False207Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 208–209why, one step back208 async def close(self) -> None:209 pass