| 1 |
import http |
| 2 |
import socket |
| 3 |
import sys |
| 4 |
import unittest |
| 5 |
from unittest.mock import patch |
| 6 |
|
| 7 |
from websockets.asyncio.client import connect, unix_connect |
| 8 |
from websockets.asyncio.router import * |
| 9 |
from websockets.exceptions import InvalidStatus |
| 10 |
|
| 11 |
from ..utils import CLIENT_CONTEXT, SERVER_CONTEXT, alist, temp_unix_socket_path |
| 12 |
from .server import EvalShellMixin, get_uri, handler |
| 13 |
|
| 14 |
|
| 15 |
try: |
| 16 |
from werkzeug.routing import Map, Rule |
| 17 |
except ImportError: |
| 18 |
pass |
| 19 |
else: |
| 20 |
url_map = Map( |
| 21 |
[ |
| 22 |
Rule("/", endpoint=handler), |
| 23 |
Rule("/r", redirect_to="/"), |
| 24 |
] |
| 25 |
) |
| 26 |
|
| 27 |
|
| 28 |
async def echo(websocket, count): |
| 29 |
message = await websocket.recv() |
| 30 |
for _ in range(count): |
| 31 |
await websocket.send(message) |
| 32 |
|
| 33 |
|
| 34 |
@unittest.skipUnless("werkzeug" in sys.modules, "werkzeug not installed") |
| 35 |
class RouterTests(EvalShellMixin, unittest.IsolatedAsyncioTestCase): |
| 36 |
# This is a small realistic example of werkzeug's basic URL routing |
| 37 |
# features: path matching, parameter extraction, and default values. |
| 38 |
|
| 39 |
async def test_router_matches_paths_and_extracts_parameters(self): |
| 40 |
"""Router matches paths and extracts parameters.""" |
| 41 |
url_map = Map( |
| 42 |
[ |
| 43 |
Rule("/echo", defaults={"count": 1}, endpoint=echo), |
| 44 |
Rule("/echo/<int:count>", endpoint=echo), |
| 45 |
] |
| 46 |
) |
| 47 |
async with route(url_map, "localhost", 0) as server: |
| 48 |
async with connect(get_uri(server) + "/echo") as client: |
| 49 |
await client.send("hello") |
| 50 |
messages = await alist(client) |
| 51 |
self.assertEqual(messages, ["hello"]) |
| 52 |
|
| 53 |
async with connect(get_uri(server) + "/echo/3") as client: |
| 54 |
await client.send("hello") |
| 55 |
messages = await alist(client) |
| 56 |
self.assertEqual(messages, ["hello", "hello", "hello"]) |
| 57 |
|
| 58 |
async def test_route_with_query_string(self): |
| 59 |
"""Router ignores query strings when matching paths.""" |
| 60 |
async with route(url_map, "localhost", 0) as server: |
| 61 |
async with connect(get_uri(server) + "/?a=b") as client: |
| 62 |
await self.assertEval(client, "ws.request.path", "/?a=b") |
| 63 |
|
| 64 |
async def test_redirect(self): |
| 65 |
"""Router redirects connections according to redirect_to.""" |
| 66 |
async with route(url_map, "localhost", 0) as server: |
| 67 |
async with connect(get_uri(server) + "/r") as client: |
| 68 |
await self.assertEval(client, "ws.request.path", "/") |
| 69 |
|
| 70 |
async def test_secure_redirect(self): |
| 71 |
"""Router redirects connections according to redirect_to when TLS is enabled.""" |
| 72 |
async with route(url_map, "localhost", 0, ssl=SERVER_CONTEXT) as server: |
| 73 |
async with connect(get_uri(server) + "/r", ssl=CLIENT_CONTEXT) as client: |
| 74 |
await self.assertEval(client, "ws.request.path", "/") |
| 75 |
|
| 76 |
@patch("websockets.asyncio.client.connect.process_redirect", lambda _, exc: exc) |
| 77 |
async def test_force_secure_redirect(self): |
| 78 |
"""Router redirects ws:// connections to a wss:// URI when ssl=True.""" |
| 79 |
async with route(url_map, "localhost", 0, ssl=True) as server: |
| 80 |
redirect_uri = get_uri(server, secure=True) |
| 81 |
with self.assertRaises(InvalidStatus) as raised: |
| 82 |
async with connect(get_uri(server) + "/r"): |
| 83 |
self.fail("did not raise") |
| 84 |
self.assertEqual( |
| 85 |
raised.exception.response.headers["Location"], |
| 86 |
redirect_uri + "/", |
| 87 |
) |
| 88 |
|
| 89 |
@patch("websockets.asyncio.client.connect.process_redirect", lambda _, exc: exc) |
| 90 |
async def test_force_redirect_server_name(self): |
| 91 |
"""Router redirects connections to the host declared in server_name.""" |
| 92 |
async with route(url_map, "localhost", 0, server_name="other") as server: |
| 93 |
with self.assertRaises(InvalidStatus) as raised: |
| 94 |
async with connect(get_uri(server) + "/r"): |
| 95 |
self.fail("did not raise") |
| 96 |
self.assertEqual( |
| 97 |
raised.exception.response.headers["Location"], |
| 98 |
"ws://other/", |
| 99 |
) |
| 100 |
|
| 101 |
async def test_not_found(self): |
| 102 |
"""Router rejects requests to unknown paths with an HTTP 404 error.""" |
| 103 |
async with route(url_map, "localhost", 0) as server: |
| 104 |
with self.assertRaises(InvalidStatus) as raised: |
| 105 |
async with connect(get_uri(server) + "/n"): |
| 106 |
self.fail("did not raise") |
| 107 |
self.assertEqual( |
| 108 |
str(raised.exception), |
| 109 |
"server rejected WebSocket connection: HTTP 404", |
| 110 |
) |
| 111 |
|
| 112 |
async def test_process_request_function_returning_none(self): |
| 113 |
"""Router supports a process_request function returning None.""" |
| 114 |
|
| 115 |
def process_request(ws, request): |
| 116 |
ws.process_request_ran = True |
| 117 |
|
| 118 |
async with route( |
| 119 |
url_map, "localhost", 0, process_request=process_request |
| 120 |
) as server: |
| 121 |
async with connect(get_uri(server) + "/") as client: |
| 122 |
await self.assertEval(client, "ws.process_request_ran", "True") |
| 123 |
|
| 124 |
async def test_process_request_coroutine_returning_none(self): |
| 125 |
"""Router supports a process_request coroutine returning None.""" |
| 126 |
|
| 127 |
async def process_request(ws, request): |
| 128 |
ws.process_request_ran = True |
| 129 |
|
| 130 |
async with route( |
| 131 |
url_map, "localhost", 0, process_request=process_request |
| 132 |
) as server: |
| 133 |
async with connect(get_uri(server) + "/") as client: |
| 134 |
await self.assertEval(client, "ws.process_request_ran", "True") |
| 135 |
|
| 136 |
async def test_process_request_function_returning_response(self): |
| 137 |
"""Router supports a process_request function returning a response.""" |
| 138 |
|
| 139 |
def process_request(ws, request): |
| 140 |
return ws.respond(http.HTTPStatus.FORBIDDEN, "Forbidden") |
| 141 |
|
| 142 |
async with route( |
| 143 |
url_map, "localhost", 0, process_request=process_request |
| 144 |
) as server: |
| 145 |
with self.assertRaises(InvalidStatus) as raised: |
| 146 |
async with connect(get_uri(server) + "/"): |
| 147 |
self.fail("did not raise") |
| 148 |
self.assertEqual( |
| 149 |
str(raised.exception), |
| 150 |
"server rejected WebSocket connection: HTTP 403", |
| 151 |
) |
| 152 |
|
| 153 |
async def test_process_request_coroutine_returning_response(self): |
| 154 |
"""Router supports a process_request coroutine returning a response.""" |
| 155 |
|
| 156 |
async def process_request(ws, request): |
| 157 |
return ws.respond(http.HTTPStatus.FORBIDDEN, "Forbidden") |
| 158 |
|
| 159 |
async with route( |
| 160 |
url_map, "localhost", 0, process_request=process_request |
| 161 |
) as server: |
| 162 |
with self.assertRaises(InvalidStatus) as raised: |
| 163 |
async with connect(get_uri(server) + "/"): |
| 164 |
self.fail("did not raise") |
| 165 |
self.assertEqual( |
| 166 |
str(raised.exception), |
| 167 |
"server rejected WebSocket connection: HTTP 403", |
| 168 |
) |
| 169 |
|
| 170 |
async def test_custom_router_factory(self): |
| 171 |
"""Router supports a custom router factory.""" |
| 172 |
|
| 173 |
class MyRouter(Router): |
| 174 |
async def handler(self, connection): |
| 175 |
connection.my_router_ran = True |
| 176 |
return await super().handler(connection) |
| 177 |
|
| 178 |
async with route(url_map, "localhost", 0, create_router=MyRouter) as server: |
| 179 |
async with connect(get_uri(server)) as client: |
| 180 |
await self.assertEval(client, "ws.my_router_ran", "True") |
| 181 |
|
| 182 |
|
| 183 |
@unittest.skipUnless(hasattr(socket, "AF_UNIX"), "this test requires Unix sockets") |
| 184 |
@unittest.skipUnless("werkzeug" in sys.modules, "werkzeug not installed") |
| 185 |
class UnixRouterTests(EvalShellMixin, unittest.IsolatedAsyncioTestCase): |
| 186 |
async def test_router_supports_unix_sockets(self): |
| 187 |
"""Router supports Unix sockets.""" |
| 188 |
url_map = Map([Rule("/echo/<int:count>", endpoint=echo)]) |
| 189 |
with temp_unix_socket_path() as path: |
| 190 |
async with unix_route(url_map, path): |
| 191 |
async with unix_connect(path, "ws://localhost/echo/3") as client: |
| 192 |
await client.send("hello") |
| 193 |
messages = await alist(client) |
| 194 |
self.assertEqual(messages, ["hello", "hello", "hello"]) |