Debian Codegraph @

tests/sync/test_router.py

raw
1 import http
2 import socket
3 import sys
4 import unittest
5 from unittest.mock import patch
6
7 from websockets.exceptions import InvalidStatus
8 from websockets.sync.client import connect, unix_connect
9 from websockets.sync.router import *
10
11 from ..utils import CLIENT_CONTEXT, SERVER_CONTEXT, temp_unix_socket_path
12 from .server import EvalShellMixin, get_uri, handler, run_router, run_unix_router
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 def echo(websocket, count):
29 message = websocket.recv()
30 for _ in range(count):
31 websocket.send(message)
32
33
34 @unittest.skipUnless("werkzeug" in sys.modules, "werkzeug not installed")
35 class RouterTests(EvalShellMixin, unittest.TestCase):
36 # This is a small realistic example of werkzeug's basic URL routing
37 # features: path matching, parameter extraction, and default values.
38
39 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 with run_router(url_map) as server:
48 with connect(get_uri(server) + "/echo") as client:
49 client.send("hello")
50 messages = list(client)
51 self.assertEqual(messages, ["hello"])
52
53 with connect(get_uri(server) + "/echo/3") as client:
54 client.send("hello")
55 messages = list(client)
56 self.assertEqual(messages, ["hello", "hello", "hello"])
57
58 def test_route_with_query_string(self):
59 """Router ignores query strings when matching paths."""
60 with run_router(url_map) as server:
61 with connect(get_uri(server) + "/?a=b") as client:
62 self.assertEval(client, "ws.request.path", "/?a=b")
63
64 def test_redirect(self):
65 """Router redirects connections according to redirect_to."""
66 with run_router(url_map) as server:
67 with connect(get_uri(server) + "/r") as client:
68 self.assertEval(client, "ws.request.path", "/")
69
70 def test_secure_redirect(self):
71 """Router redirects connections according to redirect_to when TLS is enabled."""
72 with run_router(url_map, ssl=SERVER_CONTEXT) as server:
73 with connect(get_uri(server) + "/r", ssl=CLIENT_CONTEXT) as client:
74 self.assertEval(client, "ws.request.path", "/")
75
76 @patch("websockets.sync.client.reconnect.process_redirect", lambda _, exc: exc)
77 def test_force_secure_redirect(self):
78 """Router redirects ws:// connections to a wss:// URI when ssl=True."""
79 with run_router(url_map, ssl=True) as server:
80 redirect_uri = get_uri(server, secure=True)
81 with self.assertRaises(InvalidStatus) as raised:
82 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.sync.client.reconnect.process_redirect", lambda _, exc: exc)
90 def test_force_redirect_server_name(self):
91 """Router redirects connections to the host declared in server_name."""
92 with run_router(url_map, server_name="other") as server:
93 with self.assertRaises(InvalidStatus) as raised:
94 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 def test_not_found(self):
102 """Router rejects requests to unknown paths with an HTTP 404 error."""
103 with run_router(url_map) as server:
104 with self.assertRaises(InvalidStatus) as raised:
105 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 def test_process_request_returning_none(self):
113 """Router supports a process_request returning None."""
114
115 def process_request(ws, request):
116 ws.process_request_ran = True
117
118 with run_router(url_map, process_request=process_request) as server:
119 with connect(get_uri(server) + "/") as client:
120 self.assertEval(client, "ws.process_request_ran", "True")
121
122 def test_process_request_returning_response(self):
123 """Router supports a process_request returning a response."""
124
125 def process_request(ws, request):
126 return ws.respond(http.HTTPStatus.FORBIDDEN, "Forbidden")
127
128 with run_router(url_map, process_request=process_request) as server:
129 with self.assertRaises(InvalidStatus) as raised:
130 with connect(get_uri(server) + "/"):
131 self.fail("did not raise")
132 self.assertEqual(
133 str(raised.exception),
134 "server rejected WebSocket connection: HTTP 403",
135 )
136
137 def test_custom_router_factory(self):
138 """Router supports a custom router factory."""
139
140 class MyRouter(Router):
141 def handler(self, connection):
142 connection.my_router_ran = True
143 return super().handler(connection)
144
145 with run_router(url_map, create_router=MyRouter) as server:
146 with connect(get_uri(server)) as client:
147 self.assertEval(client, "ws.my_router_ran", "True")
148
149
150 @unittest.skipUnless(hasattr(socket, "AF_UNIX"), "this test requires Unix sockets")
151 @unittest.skipUnless("werkzeug" in sys.modules, "werkzeug not installed")
152 class UnixRouterTests(EvalShellMixin, unittest.IsolatedAsyncioTestCase):
153 def test_router_supports_unix_sockets(self):
154 """Router supports Unix sockets."""
155 url_map = Map([Rule("/echo/<int:count>", endpoint=echo)])
156 with temp_unix_socket_path() as path:
157 with run_unix_router(path, url_map):
158 with unix_connect(path, "ws://localhost/echo/3") as client:
159 client.send("hello")
160 messages = list(client)
161 self.assertEqual(messages, ["hello", "hello", "hello"])