| 1 |
import contextlib |
| 2 |
import functools |
| 3 |
import socket |
| 4 |
import ssl |
| 5 |
import urllib.parse |
| 6 |
|
| 7 |
import trio |
| 8 |
|
| 9 |
from websockets.trio.router import route |
| 10 |
from websockets.trio.server import serve |
| 11 |
|
| 12 |
|
| 13 |
def get_host_port(server): |
| 14 |
for listener in server.listeners: |
| 15 |
if listener.socket.family == socket.AF_INET: # pragma: no branch |
| 16 |
return listener.socket.getsockname() |
| 17 |
raise AssertionError("expected at least one IPv4 socket") |
| 18 |
|
| 19 |
|
| 20 |
def get_uri(server, secure=None): |
| 21 |
if secure is None: |
| 22 |
secure = any( |
| 23 |
isinstance(cell.cell_contents, ssl.SSLContext) |
| 24 |
for cell in server.handler.__closure__ |
| 25 |
) # l33t hack |
| 26 |
protocol = "wss" if secure else "ws" |
| 27 |
host, port = get_host_port(server) |
| 28 |
return f"{protocol}://{host}:{port}" |
| 29 |
|
| 30 |
|
| 31 |
async def handler(ws): |
| 32 |
path = urllib.parse.urlparse(ws.request.path).path |
| 33 |
if path == "/": |
| 34 |
# The default path is an eval shell. |
| 35 |
async for expr in ws: |
| 36 |
value = eval(expr) |
| 37 |
await ws.send(str(value)) |
| 38 |
elif path == "/crash": |
| 39 |
raise RuntimeError |
| 40 |
elif path == "/no-op": |
| 41 |
pass |
| 42 |
elif path == "/delay": |
| 43 |
delay = float(await ws.recv()) |
| 44 |
await ws.aclose() |
| 45 |
await trio.sleep(delay) |
| 46 |
else: |
| 47 |
raise AssertionError(f"unexpected path: {path}") |
| 48 |
|
| 49 |
|
| 50 |
class EvalShellMixin: |
| 51 |
async def assertEval(self, client, expr, value): |
| 52 |
await client.send(expr) |
| 53 |
self.assertEqual(await client.recv(), value) |
| 54 |
|
| 55 |
|
| 56 |
@contextlib.asynccontextmanager |
| 57 |
async def run_server_or_route( |
| 58 |
serve_or_route, |
| 59 |
handler_or_url_map, |
| 60 |
port=0, |
| 61 |
host="localhost", |
| 62 |
**kwargs, |
| 63 |
): |
| 64 |
async with trio.open_nursery() as nursery: |
| 65 |
server = await nursery.start( |
| 66 |
functools.partial( |
| 67 |
serve_or_route, |
| 68 |
handler_or_url_map, |
| 69 |
port, |
| 70 |
host=host, |
| 71 |
**kwargs, |
| 72 |
) |
| 73 |
) |
| 74 |
try: |
| 75 |
yield server |
| 76 |
finally: |
| 77 |
# Run all tasks to guarantee that any exceptions are raised. |
| 78 |
# Otherwise, canceling the nursery could hide errors. |
| 79 |
await trio.testing.wait_all_tasks_blocked() |
| 80 |
nursery.cancel_scope.cancel() |
| 81 |
|
| 82 |
|
| 83 |
def run_server(handler=handler, **kwargs): |
| 84 |
return run_server_or_route(serve, handler, **kwargs) |
| 85 |
|
| 86 |
|
| 87 |
def run_router(url_map, **kwargs): |
| 88 |
return run_server_or_route(route, url_map, **kwargs) |