| 1 |
import contextlib |
| 2 |
import ssl |
| 3 |
import threading |
| 4 |
import time |
| 5 |
import urllib.parse |
| 6 |
|
| 7 |
from websockets.sync.router import route, unix_route |
| 8 |
from websockets.sync.server import serve, unix_serve |
| 9 |
|
| 10 |
|
| 11 |
def get_host_port(server): |
| 12 |
return server.socket.getsockname() |
| 13 |
|
| 14 |
|
| 15 |
def get_uri(server, secure=None): |
| 16 |
if secure is None: |
| 17 |
secure = isinstance(server.socket, ssl.SSLSocket) # hack |
| 18 |
protocol = "wss" if secure else "ws" |
| 19 |
host, port = get_host_port(server) |
| 20 |
return f"{protocol}://{host}:{port}" |
| 21 |
|
| 22 |
|
| 23 |
def handler(ws): |
| 24 |
path = urllib.parse.urlparse(ws.request.path).path |
| 25 |
if path == "/": |
| 26 |
# The default path is an eval shell. |
| 27 |
for expr in ws: |
| 28 |
value = eval(expr) |
| 29 |
ws.send(str(value)) |
| 30 |
elif path == "/crash": |
| 31 |
raise RuntimeError |
| 32 |
elif path == "/no-op": |
| 33 |
pass |
| 34 |
elif path == "/delay": |
| 35 |
delay = float(ws.recv()) |
| 36 |
ws.close() |
| 37 |
time.sleep(delay) |
| 38 |
else: |
| 39 |
raise AssertionError(f"unexpected path: {path}") |
| 40 |
|
| 41 |
|
| 42 |
class EvalShellMixin: |
| 43 |
def assertEval(self, client, expr, value): |
| 44 |
client.send(expr) |
| 45 |
self.assertEqual(client.recv(), value) |
| 46 |
|
| 47 |
|
| 48 |
@contextlib.contextmanager |
| 49 |
def run_server_or_router( |
| 50 |
serve_or_route, |
| 51 |
handler_or_url_map, |
| 52 |
host="localhost", |
| 53 |
port=0, |
| 54 |
**kwargs, |
| 55 |
): |
| 56 |
with serve_or_route(handler_or_url_map, host, port, **kwargs) as server: |
| 57 |
thread = threading.Thread(target=server.serve_forever) |
| 58 |
thread.start() |
| 59 |
try: |
| 60 |
yield server |
| 61 |
finally: |
| 62 |
server.shutdown() |
| 63 |
thread.join() |
| 64 |
|
| 65 |
|
| 66 |
def run_server(handler=handler, **kwargs): |
| 67 |
return run_server_or_router(serve, handler, **kwargs) |
| 68 |
|
| 69 |
|
| 70 |
def run_router(url_map, **kwargs): |
| 71 |
return run_server_or_router(route, url_map, **kwargs) |
| 72 |
|
| 73 |
|
| 74 |
@contextlib.contextmanager |
| 75 |
def run_unix_server_or_router( |
| 76 |
unix_serve_or_route, |
| 77 |
handler_or_url_map, |
| 78 |
path, |
| 79 |
**kwargs, |
| 80 |
): |
| 81 |
with unix_serve_or_route(handler_or_url_map, path, **kwargs) as server: |
| 82 |
thread = threading.Thread(target=server.serve_forever) |
| 83 |
thread.start() |
| 84 |
try: |
| 85 |
yield server |
| 86 |
finally: |
| 87 |
server.shutdown() |
| 88 |
thread.join() |
| 89 |
|
| 90 |
|
| 91 |
def run_unix_server(path, handler=handler, **kwargs): |
| 92 |
return run_unix_server_or_router(unix_serve, handler, path, **kwargs) |
| 93 |
|
| 94 |
|
| 95 |
def run_unix_router(path, url_map, **kwargs): |
| 96 |
return run_unix_server_or_router(unix_route, url_map, path, **kwargs) |