Debian Codegraph @

tests/asyncio/server.py

raw
1 import asyncio
2 import socket
3 import urllib.parse
4
5
6 def get_host_port(server):
7 for sock in server.sockets:
8 if sock.family == socket.AF_INET: # pragma: no branch
9 return sock.getsockname()
10 raise AssertionError("expected at least one IPv4 socket")
11
12
13 def get_uri(server, secure=None):
14 if secure is None:
15 secure = server.server._ssl_context is not None # hack
16 protocol = "wss" if secure else "ws"
17 host, port = get_host_port(server)
18 return f"{protocol}://{host}:{port}"
19
20
21 async def handler(ws):
22 path = urllib.parse.urlparse(ws.request.path).path
23 if path == "/":
24 # The default path is an eval shell.
25 async for expr in ws:
26 value = eval(expr)
27 await ws.send(str(value))
28 elif path == "/crash":
29 raise RuntimeError
30 elif path == "/no-op":
31 pass
32 elif path == "/delay":
33 delay = float(await ws.recv())
34 await ws.close()
35 await asyncio.sleep(delay)
36 else:
37 raise AssertionError(f"unexpected path: {path}")
38
39
40 class EvalShellMixin:
41 async def assertEval(self, client, expr, value):
42 await client.send(expr)
43 self.assertEqual(await client.recv(), value)
44
45
46 # This shortcut avoids repeating serve(handler, "localhost", 0) for every test.
47 args = handler, "localhost", 0