utils.py
This file
Path
tests/dispatch/utils.py
212 lines · 7.3 KiB · Python
Last changed by
Bump up flow control defaults (#629)Tom Christiebefore adoption52c2c97
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
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 = []Enforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
line 45why, one step back45Rename BaseTCPStream/TCPStream to BaseSocketStream/SocketStream (#517)Jonas Lundbergbefore adoption1a32cf0
line 46why, one step back46 # Socket stream interfaceEnforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
line 47why, one step back47Merge pull request #255 from encode/refactor/stream-interfaceTom Christiebefore adoption3069227
lines 48–50why, one step back48 def get_http_version(self) -> str:49 return "HTTP/2"50Enforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
line 51why, one step back51 async def read(self, n, timeout, flag=None) -> bytes:Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
line 52why, one step back52 await sleep(self.backend, 0)Enforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
lines 53–63why, one step back53 send, self.buffer = self.buffer[:n], self.buffer[n:]54 return send5556 def write_no_block(self, data: bytes) -> None:57 events = self.conn.receive_data(data)58 self.buffer += self.conn.data_to_send()59 for event in events:60 if isinstance(event, h2.events.RequestReceived):61 self.request_received(event.headers, event.stream_id)62 elif isinstance(event, h2.events.DataReceived):63 self.receive_data(event.data, event.stream_id)Fix bug in calculating maximum frame size (#153)IsaacBenghiatbefore adoptionab9cd0e
lines 64–74why, one step back64 # This should send an UPDATE_WINDOW for both the stream and the65 # connection increasing it by the amount66 # consumed keeping the flow control window constant67 flow_control_consumed = event.flow_controlled_length68 if flow_control_consumed > 0:69 self.conn.increment_flow_control_window(flow_control_consumed)70 self.buffer += self.conn.data_to_send()71 self.conn.increment_flow_control_window(72 flow_control_consumed, event.stream_id73 )74 self.buffer += self.conn.data_to_send()Enforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
lines 75–76why, one step back75 elif isinstance(event, h2.events.StreamEnded):76 self.stream_complete(event.stream_id)Remove ENABLE_CONNECT_PROTOCOL from HTTP/2 Settings (#373)Seth Michael Larsonbefore adoptionb574230
lines 77–78why, one step back77 elif isinstance(event, h2.events.RemoteSettingsChanged):78 self.settings_changed.append(event)Enforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
lines 79–132why, one step back7980 async def write(self, data: bytes, timeout) -> None:81 self.write_no_block(data)8283 async def close(self) -> None:84 pass8586 def is_connection_dropped(self) -> bool:87 return self.close_connection8889 # Server implementation9091 def request_received(self, headers, stream_id):92 """93 Handler for when the initial part of the HTTP request is received.94 """95 if stream_id not in self.requests:96 self.requests[stream_id] = []97 self.requests[stream_id].append({"headers": headers, "data": b""})9899 def receive_data(self, data, stream_id):100 """101 Handler for when a data part of the HTTP request is received.102 """103 self.requests[stream_id][-1]["data"] += data104105 def stream_complete(self, stream_id):106 """107 Handler for when the HTTP request is completed.108 """109 request = self.requests[stream_id].pop(0)110 if not self.requests[stream_id]:111 del self.requests[stream_id]112113 headers_dict = dict(request["headers"])114115 method = headers_dict[b":method"].decode("ascii")116 url = "%s://%s%s" % (117 headers_dict[b":scheme"].decode("ascii"),118 headers_dict[b":authority"].decode("ascii"),119 headers_dict[b":path"].decode("ascii"),120 )121 headers = [(k, v) for k, v in request["headers"] if not k.startswith(b":")]122 data = request["data"]123124 # Call out to the app.125 request = Request(method, url, headers=headers, data=data)126 response = self.app(request)127128 # Write the response to the buffer.129 status_code_bytes = str(response.status_code).encode("ascii")130 response_headers = [(b":status", status_code_bytes)] + response.headers.raw131132 self.conn.send_headers(stream_id, response_headers)Fix bug in calculating maximum frame size (#153)IsaacBenghiatbefore adoptionab9cd0e
lines 133–154why, one step back133 self.buffer += self.conn.data_to_send()134 self.return_data[stream_id] = response.content135 self.send_return_data(stream_id)136137 def send_return_data(self, stream_id):138 while self.return_data[stream_id]:139 flow_control = self.conn.local_flow_control_window(stream_id)140 chunk_size = min(141 len(self.return_data[stream_id]),142 flow_control,143 self.conn.max_outbound_frame_size,144 )145 if chunk_size == 0:146 return147 else:148 chunk, self.return_data[stream_id] = (149 self.return_data[stream_id][:chunk_size],150 self.return_data[stream_id][chunk_size:],151 )152 self.conn.send_data(stream_id, chunk)153 self.buffer += self.conn.data_to_send()154 self.conn.end_stream(stream_id)Enforce that sync client uses asyncio-based backend (#232)Florimond Mancabefore adoption9c7d23c
line 155why, one step back155 self.buffer += self.conn.data_to_send()Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 156–158why, one step back156157158class MockRawSocketBackend:Refactor tests in the light of backend auto-detection (#615)Florimond Mancabefore adoptionab41a5d
lines 159–160why, one step back159 def __init__(self, data_to_send=b"", backend="auto"):160 self.backend = lookup_backend(backend)Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 161–164why, one step back161 self.data_to_send = data_to_send162 self.received_data = []163 self.stream = MockRawSocketStream(self)164Fix remaining references to BaseStream in tests (#347)Florimond Mancabefore adoption6c6148e
line 165why, one step back165 async def open_tcp_stream(Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 166–169why, one step back166 self,167 hostname: str,168 port: int,169 ssl_context: typing.Optional[ssl.SSLContext],TimeoutConfig -> Timeout (#591)Tom Christiebefore adoptionc033ed1
line 170why, one step back170 timeout: Timeout,Rename BaseTCPStream/TCPStream to BaseSocketStream/SocketStream (#517)Jonas Lundbergbefore adoption1a32cf0
line 171why, one step back171 ) -> BaseSocketStream:Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 172–181why, one step back172 self.received_data.append(173 b"--- CONNECT(%s, %d) ---" % (hostname.encode(), port)174 )175 return self.stream176177 # Defer all other attributes and methods to the underlying backend.178 def __getattr__(self, name: str) -> typing.Any:179 return getattr(self.backend, name)180181Rename BaseTCPStream/TCPStream to BaseSocketStream/SocketStream (#517)Jonas Lundbergbefore adoption1a32cf0
line 182why, one step back182class MockRawSocketStream(BaseSocketStream):Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 183–184why, one step back183 def __init__(self, backend: MockRawSocketBackend):184 self.backend = backendMake start_tls a method on streams & return a new stream (#484)Jamie Hewlandbefore adoption644e8fc
lines 185–186why, one step back185186 async def start_tls(TimeoutConfig -> Timeout (#591)Tom Christiebefore adoptionc033ed1
line 187why, one step back187 self, hostname: str, ssl_context: ssl.SSLContext, timeout: TimeoutRename BaseTCPStream/TCPStream to BaseSocketStream/SocketStream (#517)Jonas Lundbergbefore adoption1a32cf0
line 188why, one step back188 ) -> BaseSocketStream:Make start_tls a method on streams & return a new stream (#484)Jamie Hewlandbefore adoption644e8fc
lines 189–190why, one step back189 self.backend.received_data.append(b"--- START_TLS(%s) ---" % hostname.encode())190 return MockRawSocketStream(self.backend)Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 191–197why, one step back191192 def get_http_version(self) -> str:193 return "HTTP/1.1"194195 def write_no_block(self, data: bytes) -> None:196 self.backend.received_data.append(data)197TimeoutConfig -> Timeout (#591)Tom Christiebefore adoptionc033ed1
line 198why, one step back198 async def write(self, data: bytes, timeout: Timeout = None) -> None:Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 199–207why, one step back199 if data:200 self.write_no_block(data)201202 async def read(self, n, timeout, flag=None) -> bytes:203 await sleep(self.backend.backend, 0)204 if not self.backend.data_to_send:205 return b""206 return self.backend.data_to_send.pop(0)207Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085
lines 208–210why, one step back208 def is_connection_dropped(self) -> bool:209 return False210Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 211–212why, one step back211 async def close(self) -> None:212 pass