utils.py
This file
Path
tests/dispatch/utils.py
220 lines · 7.6 KiB · Python
Last changed by
Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
History of this fileTake it
Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
lines 1–7why, one step back1import ssl2import typing34import h2.config5import h2.connection6import h2.events7Merge pull request #255 from encode/refactor/stream-interfaceTom Christiebefore adoption3069227
line 8why, one step back8from httpx import AsyncioBackend, BaseStream, Request, TimeoutConfigParametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
line 9why, one step back9from tests.concurrency import sleepMerge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
lines 10–11why, one step back1011Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
lines 12–13why, one step back12class MockHTTP2Backend:13 def __init__(self, app, backend=None):Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
line 14why, one step back14 self.app = appParametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
line 15why, one step back15 self.backend = AsyncioBackend() if backend is None else backendCheck for connection aliveness on pool re-acquiry (#111)Tom Christiebefore adoption025240c
line 16why, one step back16 self.server = NoneMerge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
lines 17–23why, one step back1718 async def connect(19 self,20 hostname: str,21 port: int,22 ssl_context: typing.Optional[ssl.SSLContext],23 timeout: TimeoutConfig,Merge pull request #255 from encode/refactor/stream-interfaceTom Christiebefore adoption3069227
line 24why, one step back24 ) -> BaseStream:Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
line 25why, one step back25 self.server = MockHTTP2Server(self.app, backend=self.backend)Merge pull request #255 from encode/refactor/stream-interfaceTom Christiebefore adoption3069227
line 26why, one step back26 return self.serverMerge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
line 27why, one step back27Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
lines 28–30why, one step back28 # Defer all other attributes and methods to the underlying backend.29 def __getattr__(self, name: str) -> typing.Any:30 return getattr(self.backend, name)Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
line 31why, one step back31Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
line 32why, one step back32Merge pull request #255 from encode/refactor/stream-interfaceTom Christiebefore adoption3069227
line 33why, one step back33class MockHTTP2Server(BaseStream):Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
line 34why, one step back34 def __init__(self, app, backend):Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
lines 35–37why, one step back35 config = h2.config.H2Configuration(client_side=False)36 self.conn = h2.connection.H2Connection(config=config)37 self.app = appParametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
line 38why, one step back38 self.backend = backendMerge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
lines 39–40why, one step back39 self.buffer = b""40 self.requests = {}Check disconnections on connection reacquiry (#145)Tom Christiebefore adoptionec365c0
line 41why, one step back41 self.close_connection = FalseFix bug in calculating maximum frame size (#153)IsaacBenghiatbefore adoptionab9cd0e
lines 42–43why, one step back42 self.return_data = {}43 self.returning = {}Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
line 44why, one step back44Merge pull request #255 from encode/refactor/stream-interfaceTom Christiebefore adoption3069227
line 45why, one step back45 # Stream interfaceMerge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
line 46why, one step back46Merge pull request #255 from encode/refactor/stream-interfaceTom Christiebefore adoption3069227
lines 47–49why, one step back47 def get_http_version(self) -> str:48 return "HTTP/2"49Read/Write timeout modes (#104)Tom Christiebefore adoptionf4f05e3
line 50why, one step back50 async def read(self, n, timeout, flag=None) -> bytes:Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
line 51why, one step back51 await sleep(self.backend, 0)Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
lines 52–62why, one step back52 send, self.buffer = self.buffer[:n], self.buffer[n:]53 return send5455 def write_no_block(self, data: bytes) -> None:56 events = self.conn.receive_data(data)57 self.buffer += self.conn.data_to_send()58 for event in events:59 if isinstance(event, h2.events.RequestReceived):60 self.request_received(event.headers, event.stream_id)61 elif isinstance(event, h2.events.DataReceived):62 self.receive_data(event.data, event.stream_id)Fix bug in calculating maximum frame size (#153)IsaacBenghiatbefore adoptionab9cd0e
lines 63–73why, one step back63 # This should send an UPDATE_WINDOW for both the stream and the64 # connection increasing it by the amount65 # consumed keeping the flow control window constant66 flow_control_consumed = event.flow_controlled_length67 if flow_control_consumed > 0:68 self.conn.increment_flow_control_window(flow_control_consumed)69 self.buffer += self.conn.data_to_send()70 self.conn.increment_flow_control_window(71 flow_control_consumed, event.stream_id72 )73 self.buffer += self.conn.data_to_send()Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
lines 74–75why, one step back74 elif isinstance(event, h2.events.StreamEnded):75 self.stream_complete(event.stream_id)Fix bug in calculating maximum frame size (#153)IsaacBenghiatbefore adoptionab9cd0e
lines 76–83why, one step back76 elif isinstance(event, h2.events.WindowUpdated):77 if event.stream_id == 0:78 for key, value in self.returning.items():79 if value:80 self.send_return_data(key)81 # This will throw an error if the event is for a not-yet created stream82 elif self.returning[event.stream_id]:83 self.send_return_data(event.stream_id)Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
lines 84–89why, one step back8485 async def write(self, data: bytes, timeout) -> None:86 self.write_no_block(data)8788 async def close(self) -> None:89 passCheck disconnections on connection reacquiry (#145)Tom Christiebefore adoptionec365c0
lines 90–92why, one step back9091 def is_connection_dropped(self) -> bool:92 return self.close_connectionMerge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
lines 93–133why, one step back9394 # Server implementation9596 def request_received(self, headers, stream_id):97 """98 Handler for when the initial part of the HTTP request is received.99 """100 if stream_id not in self.requests:101 self.requests[stream_id] = []102 self.requests[stream_id].append({"headers": headers, "data": b""})103104 def receive_data(self, data, stream_id):105 """106 Handler for when a data part of the HTTP request is received.107 """108 self.requests[stream_id][-1]["data"] += data109110 def stream_complete(self, stream_id):111 """112 Handler for when the HTTP request is completed.113 """114 request = self.requests[stream_id].pop(0)115 if not self.requests[stream_id]:116 del self.requests[stream_id]117118 headers_dict = dict(request["headers"])119120 method = headers_dict[b":method"].decode("ascii")121 url = "%s://%s%s" % (122 headers_dict[b":scheme"].decode("ascii"),123 headers_dict[b":authority"].decode("ascii"),124 headers_dict[b":path"].decode("ascii"),125 )126 headers = [(k, v) for k, v in request["headers"] if not k.startswith(b":")]127 data = request["data"]128129 # Call out to the app.130 request = Request(method, url, headers=headers, data=data)131 response = self.app(request)132133 # Write the response to the buffer.Status code tweaks (#77)Tom Christiebefore adoptionc12c271
line 134why, one step back134 status_code_bytes = str(response.status_code).encode("ascii")Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
lines 135–137why, one step back135 response_headers = [(b":status", status_code_bytes)] + response.headers.raw136137 self.conn.send_headers(stream_id, response_headers)Fix bug in calculating maximum frame size (#153)IsaacBenghiatbefore adoptionab9cd0e
lines 138–161why, one step back138 self.buffer += self.conn.data_to_send()139 self.return_data[stream_id] = response.content140 self.returning[stream_id] = True141 self.send_return_data(stream_id)142143 def send_return_data(self, stream_id):144 while self.return_data[stream_id]:145 flow_control = self.conn.local_flow_control_window(stream_id)146 chunk_size = min(147 len(self.return_data[stream_id]),148 flow_control,149 self.conn.max_outbound_frame_size,150 )151 if chunk_size == 0:152 return153 else:154 chunk, self.return_data[stream_id] = (155 self.return_data[stream_id][:chunk_size],156 self.return_data[stream_id][chunk_size:],157 )158 self.conn.send_data(stream_id, chunk)159 self.buffer += self.conn.data_to_send()160 self.returning[stream_id] = False161 self.conn.end_stream(stream_id)Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af
line 162why, one step back162 self.buffer += self.conn.data_to_send()Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 163–220why, one step back163164165class MockRawSocketBackend:166 def __init__(self, data_to_send=b"", backend=None):167 self.backend = AsyncioBackend() if backend is None else backend168 self.data_to_send = data_to_send169 self.received_data = []170 self.stream = MockRawSocketStream(self)171172 async def connect(173 self,174 hostname: str,175 port: int,176 ssl_context: typing.Optional[ssl.SSLContext],177 timeout: TimeoutConfig,178 ) -> BaseStream:179 self.received_data.append(180 b"--- CONNECT(%s, %d) ---" % (hostname.encode(), port)181 )182 return self.stream183184 async def start_tls(185 self,186 stream: BaseStream,187 hostname: str,188 ssl_context: ssl.SSLContext,189 timeout: TimeoutConfig,190 ) -> BaseStream:191 self.received_data.append(b"--- START_TLS(%s) ---" % hostname.encode())192 return self.stream193194 # Defer all other attributes and methods to the underlying backend.195 def __getattr__(self, name: str) -> typing.Any:196 return getattr(self.backend, name)197198199class MockRawSocketStream(BaseStream):200 def __init__(self, backend: MockRawSocketBackend):201 self.backend = backend202203 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)208209 async def write(self, data: bytes, timeout: TimeoutConfig = None) -> None:210 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)218219 async def close(self) -> None:220 pass