Debian Codegraph @

tests/sync/test_server.py

raw
1 import dataclasses
2 import hmac
3 import http
4 import logging
5 import pathlib
6 import socket
7 import threading
8 import time
9 import unittest
10 from unittest.mock import patch
11
12 from websockets.exceptions import (
13 ConnectionClosedError,
14 ConnectionClosedOK,
15 InvalidHandshake,
16 InvalidStatus,
17 NegotiationError,
18 )
19 from websockets.http11 import Request, Response
20 from websockets.sync.client import connect, unix_connect
21 from websockets.sync.server import *
22
23 from ..utils import (
24 CLIENT_CONTEXT,
25 MS,
26 SERVER_CONTEXT,
27 DeprecationTestCase,
28 LoggingTestCase,
29 temp_unix_socket_path,
30 )
31 from .server import (
32 EvalShellMixin,
33 get_host_port,
34 get_uri,
35 handler,
36 run_server,
37 run_unix_server,
38 )
39
40
41 class ServerTests(EvalShellMixin, LoggingTestCase, unittest.TestCase):
42 def test_connection(self):
43 """Server receives connection from client and the handshake succeeds."""
44 with run_server() as server:
45 with connect(get_uri(server)) as client:
46 self.assertEval(client, "ws.protocol.state.name", "OPEN")
47
48 def test_connection_handler_returns(self):
49 """Connection handler returns."""
50 with run_server() as server:
51 with connect(get_uri(server) + "/no-op") as client:
52 with self.assertRaises(ConnectionClosedOK) as raised:
53 client.recv()
54 self.assertEqual(
55 str(raised.exception),
56 "received 1000 (OK); then sent 1000 (OK)",
57 )
58
59 def test_connection_handler_raises_exception(self):
60 """Connection handler raises an exception."""
61 with run_server() as server:
62 with connect(get_uri(server) + "/crash") as client:
63 with self.assertRaises(ConnectionClosedError) as raised:
64 client.recv()
65 self.assertEqual(
66 str(raised.exception),
67 "received 1011 (internal error); then sent 1011 (internal error)",
68 )
69
70 def test_existing_socket(self):
71 """Server receives connection using a pre-existing socket."""
72 with socket.create_server(("localhost", 0)) as sock:
73 host, port = sock.getsockname()
74 # Unset the default values of host and port set by run_server.
75 with run_server(host=None, port=None, sock=sock):
76 with connect(f"ws://{host}:{port}/") as client:
77 self.assertEval(client, "ws.protocol.state.name", "OPEN")
78
79 def test_select_subprotocol(self):
80 """Server selects a subprotocol with the select_subprotocol callable."""
81
82 def select_subprotocol(ws, subprotocols):
83 ws.select_subprotocol_ran = True
84 assert "chat" in subprotocols
85 return "chat"
86
87 with run_server(
88 subprotocols=["chat"],
89 select_subprotocol=select_subprotocol,
90 ) as server:
91 with connect(get_uri(server), subprotocols=["chat"]) as client:
92 self.assertEval(client, "ws.select_subprotocol_ran", "True")
93 self.assertEval(client, "ws.subprotocol", "chat")
94
95 def test_select_subprotocol_rejects_handshake(self):
96 """Server rejects handshake if select_subprotocol raises NegotiationError."""
97
98 def select_subprotocol(ws, subprotocols):
99 raise NegotiationError
100
101 with run_server(select_subprotocol=select_subprotocol) as server:
102 with self.assertRaises(InvalidStatus) as raised:
103 with connect(get_uri(server)):
104 self.fail("did not raise")
105 self.assertEqual(
106 str(raised.exception),
107 "server rejected WebSocket connection: HTTP 400",
108 )
109
110 def test_select_subprotocol_raises_exception(self):
111 """Server returns an error if select_subprotocol raises an exception."""
112
113 def select_subprotocol(ws, subprotocols):
114 raise RuntimeError
115
116 with run_server(select_subprotocol=select_subprotocol) as server:
117 with self.assertRaises(InvalidStatus) as raised:
118 with connect(get_uri(server)):
119 self.fail("did not raise")
120 self.assertEqual(
121 str(raised.exception),
122 "server rejected WebSocket connection: HTTP 500",
123 )
124
125 def test_compression_is_enabled(self):
126 """Server enables compression by default."""
127 with run_server() as server:
128 with connect(get_uri(server)) as client:
129 self.assertEval(
130 client,
131 "[type(ext).__name__ for ext in ws.protocol.extensions]",
132 "['PerMessageDeflate']",
133 )
134
135 def test_disable_compression(self):
136 """Server disables compression."""
137 with run_server(compression=None) as server:
138 with connect(get_uri(server)) as client:
139 self.assertEval(client, "ws.protocol.extensions", "[]")
140
141 def test_process_request_returns_none(self):
142 """Server runs process_request and continues the handshake."""
143
144 def process_request(ws, request):
145 self.assertIsInstance(request, Request)
146 ws.process_request_ran = True
147
148 with run_server(process_request=process_request) as server:
149 with connect(get_uri(server)) as client:
150 self.assertEval(client, "ws.process_request_ran", "True")
151
152 def test_process_request_returns_response(self):
153 """Server aborts handshake if process_request returns a response."""
154
155 def process_request(ws, request):
156 return ws.respond(http.HTTPStatus.FORBIDDEN, "Forbidden")
157
158 def handler(ws):
159 self.fail("handler must not run")
160
161 with self.assertNoLogs("websockets", logging.ERROR):
162 with run_server(handler, process_request=process_request) as server:
163 with self.assertRaises(InvalidStatus) as raised:
164 with connect(get_uri(server)):
165 self.fail("did not raise")
166 self.assertEqual(
167 str(raised.exception),
168 "server rejected WebSocket connection: HTTP 403",
169 )
170
171 def test_process_request_raises_exception(self):
172 """Server returns an error if process_request raises an exception."""
173
174 def process_request(ws, request):
175 raise RuntimeError("BOOM")
176
177 with self.assertLogs("websockets", logging.ERROR) as logs:
178 with run_server(process_request=process_request) as server:
179 with self.assertRaises(InvalidStatus) as raised:
180 with connect(get_uri(server)):
181 self.fail("did not raise")
182 self.assertEqual(
183 str(raised.exception),
184 "server rejected WebSocket connection: HTTP 500",
185 )
186 self.assertExceptionLogged(logs, "process_request failed", "BOOM")
187
188 def test_process_response_returns_none(self):
189 """Server runs process_response but keeps the handshake response."""
190
191 def process_response(ws, request, response):
192 self.assertIsInstance(request, Request)
193 self.assertIsInstance(response, Response)
194 ws.process_response_ran = True
195
196 with run_server(process_response=process_response) as server:
197 with connect(get_uri(server)) as client:
198 self.assertEval(client, "ws.process_response_ran", "True")
199
200 def test_process_response_modifies_response(self):
201 """Server runs process_response and modifies the handshake response."""
202
203 def process_response(ws, request, response):
204 response.headers["X-ProcessResponse"] = "OK"
205
206 with run_server(process_response=process_response) as server:
207 with connect(get_uri(server)) as client:
208 self.assertEqual(client.response.headers["X-ProcessResponse"], "OK")
209
210 def test_process_response_replaces_response(self):
211 """Server runs process_response and replaces the handshake response."""
212
213 def process_response(ws, request, response):
214 headers = response.headers.copy()
215 headers["X-ProcessResponse"] = "OK"
216 return dataclasses.replace(response, headers=headers)
217
218 with run_server(process_response=process_response) as server:
219 with connect(get_uri(server)) as client:
220 self.assertEqual(client.response.headers["X-ProcessResponse"], "OK")
221
222 def test_process_response_raises_exception(self):
223 """Server returns an error if process_response raises an exception."""
224
225 def process_response(ws, request, response):
226 raise RuntimeError("BOOM")
227
228 with self.assertLogs("websockets", logging.ERROR) as logs:
229 with run_server(process_response=process_response) as server:
230 with self.assertRaises(InvalidStatus) as raised:
231 with connect(get_uri(server)):
232 self.fail("did not raise")
233 self.assertEqual(
234 str(raised.exception),
235 "server rejected WebSocket connection: HTTP 500",
236 )
237 self.assertExceptionLogged(logs, "process_response failed", "BOOM")
238
239 def test_override_server_header(self):
240 """Server can override Server header with server_header."""
241 with run_server(server_header="Neo") as server:
242 with connect(get_uri(server)) as client:
243 self.assertEval(client, "ws.response.headers['Server']", "Neo")
244
245 def test_remove_server_header(self):
246 """Server can remove Server header with server_header."""
247 with run_server(server_header=None) as server:
248 with connect(get_uri(server)) as client:
249 self.assertEval(client, "'Server' in ws.response.headers", "False")
250
251 def test_keepalive_is_enabled(self):
252 """Server enables keepalive and measures latency."""
253 with run_server(ping_interval=MS) as server:
254 with connect(get_uri(server)) as client:
255 client.send("ws.latency")
256 latency = eval(client.recv())
257 self.assertEqual(latency, 0)
258 time.sleep(2 * MS)
259 client.send("ws.latency")
260 latency = eval(client.recv())
261 self.assertGreater(latency, 0)
262
263 def test_disable_keepalive(self):
264 """Server disables keepalive."""
265 with run_server(ping_interval=None) as server:
266 with connect(get_uri(server)) as client:
267 time.sleep(2 * MS)
268 client.send("ws.latency")
269 latency = eval(client.recv())
270 self.assertEqual(latency, 0)
271
272 def test_logger(self):
273 """Server accepts a logger argument."""
274 logger = logging.getLogger("test")
275 with run_server(logger=logger) as server:
276 self.assertEqual(server.logger.name, logger.name)
277
278 def test_custom_connection_factory(self):
279 """Server runs ServerConnection factory provided in create_connection."""
280
281 def create_connection(*args, **kwargs):
282 server = ServerConnection(*args, **kwargs)
283 server.create_connection_ran = True
284 return server
285
286 with run_server(create_connection=create_connection) as server:
287 with connect(get_uri(server)) as client:
288 self.assertEval(client, "ws.create_connection_ran", "True")
289
290 def test_connections(self):
291 """Server provides a connections property."""
292 with run_server() as server:
293 self.assertEqual(server.connections, set())
294 with (
295 connect(get_uri(server)) as client1,
296 connect(get_uri(server)) as client2,
297 ):
298 client1.send("ws.id")
299 client2.send("ws.id")
300 self.assertEqual(
301 {str(connection.id) for connection in server.connections},
302 {client1.recv(), client2.recv()},
303 )
304 self.assertEqual(server.connections, set())
305
306 def test_handshake_fails(self):
307 """Server receives connection from client but the handshake fails."""
308
309 def remove_key_header(self, request):
310 del request.headers["Sec-WebSocket-Key"]
311
312 with run_server(process_request=remove_key_header) as server:
313 with self.assertRaises(InvalidStatus) as raised:
314 with connect(get_uri(server)):
315 self.fail("did not raise")
316 self.assertEqual(
317 str(raised.exception),
318 "server rejected WebSocket connection: HTTP 400",
319 )
320
321 def test_timeout_before_handshake_request(self):
322 """Server times out before receiving handshake request from client."""
323 with self.assertLogs("websockets", logging.DEBUG) as logs:
324 with run_server(open_timeout=MS) as server:
325 with socket.create_connection(get_host_port(server)) as sock:
326 # Wait for the server to close the connection.
327 self.assertEqual(sock.recv(4096), b"")
328
329 self.assertExceptionLogged(
330 logs,
331 "! no valid HTTP request",
332 "connection closed while reading HTTP request line",
333 )
334
335 def test_connection_closed_before_handshake_request(self):
336 """Server reads EOF before receiving handshake request from client."""
337 with self.assertLogs("websockets", logging.DEBUG) as logs:
338 with run_server() as server:
339 with socket.create_connection(get_host_port(server)):
340 # Wait for the server to receive the connection, then close it.
341 time.sleep(MS)
342
343 self.assertExceptionLogged(
344 logs,
345 "! no valid HTTP request",
346 "connection closed while reading HTTP request line",
347 )
348
349 def test_connection_closed_before_handshake_response_sync(self):
350 """Server reads EOF before sending handshake response to client."""
351
352 def process_request(ws, _request):
353 ws.close_socket()
354
355 with self.assertNoLogs("websockets", logging.ERROR):
356 with run_server(process_request=process_request) as server:
357 with self.assertRaises(InvalidHandshake):
358 with connect(get_uri(server)):
359 self.fail("did not raise")
360
361 def test_junk_handshake_request(self):
362 """Server closes the connection when receiving non-HTTP request from client."""
363 with self.assertLogs("websockets.server", logging.DEBUG) as logs:
364 with run_server() as server:
365 with socket.create_connection(get_host_port(server)) as sock:
366 sock.send(b"HELO relay.invalid\r\n")
367 # Wait for the server to close the connection.
368 self.assertEqual(sock.recv(4096), b"")
369
370 self.assertExceptionLogged(
371 logs,
372 "! no valid HTTP request",
373 "invalid HTTP request line: HELO relay.invalid",
374 )
375
376 def test_shutdown_stops_accepting_connections(self):
377 """Server stops accepting connections."""
378 with run_server() as server:
379 # Connect a client and disable close_connections to delay closing.
380 uri = get_uri(server)
381 with connect(uri):
382 shutdown_thread = threading.Thread(
383 target=server.shutdown,
384 kwargs={"close_connections": False},
385 )
386 shutdown_thread.start()
387 time.sleep(MS)
388
389 # Server cannot receive new connections.
390 with self.assertRaises(OSError):
391 with connect(uri):
392 self.fail("did not raise")
393
394 shutdown_thread.join()
395
396 def test_shutdown_rejects_connecting_connections(self):
397 """Server rejects connecting connections with HTTP 503."""
398
399 def process_request(ws, _request):
400 ws.server.socket_closed.wait()
401
402 def shutdown_server(server):
403 time.sleep(2 * MS)
404 server.shutdown()
405
406 with run_server(process_request=process_request) as server:
407 shutdown_thread = threading.Thread(target=shutdown_server, args=(server,))
408 shutdown_thread.start()
409 with self.assertRaises(InvalidStatus) as raised:
410 with connect(get_uri(server)):
411 self.fail("did not raise")
412 self.assertEqual(
413 str(raised.exception),
414 "server rejected WebSocket connection: HTTP 503",
415 )
416 shutdown_thread.join(MS)
417
418 def test_shutdown_closes_open_connections(self):
419 """Server closes open connections with code 1001."""
420 with run_server() as server:
421 with connect(get_uri(server)) as client:
422 server.shutdown()
423 with self.assertRaises(ConnectionClosedOK) as raised:
424 client.recv()
425 self.assertEqual(
426 str(raised.exception),
427 "received 1001 (going away); then sent 1001 (going away)",
428 )
429
430 def test_shutdown_closes_open_connections_with_code_and_reason(self):
431 """Server closes open connections with a custom code and reason."""
432 with run_server() as server:
433 with connect(get_uri(server)) as client:
434 server.shutdown(code=1012, reason="restarting")
435 with self.assertRaises(ConnectionClosedError) as raised:
436 client.recv()
437 self.assertEqual(
438 str(raised.exception),
439 "received 1012 (service restart) restarting; "
440 "then sent 1012 (service restart) restarting",
441 )
442
443 def test_shutdown_keeps_connections_open(self):
444 """Server waits for the client to close open connections."""
445 with run_server() as server:
446 with connect(get_uri(server)):
447 shutdown_thread = threading.Thread(
448 target=server.shutdown,
449 kwargs={"close_connections": False},
450 )
451 shutdown_thread.start()
452
453 # The server waits for the client to close the connection.
454 shutdown_thread.join(MS)
455 self.assertTrue(shutdown_thread.is_alive())
456
457 # Once the client closes the connection, the server terminates.
458 shutdown_thread.join(MS)
459 self.assertFalse(shutdown_thread.is_alive())
460
461 @patch("websockets.sync.server.Server.SHUTDOWN_POLLING_INTERVAL", MS)
462 def test_shutdown_keeps_handlers_running(self):
463 """Server waits for connection handlers to terminate."""
464 with run_server() as server:
465 with connect(get_uri(server) + "/delay") as client:
466 # Delay termination of the connection handler.
467 client.send(str(3 * MS))
468
469 shutdown_thread = threading.Thread(target=server.shutdown)
470 shutdown_thread.start()
471
472 # The server waits for the connection handler to terminate.
473 shutdown_thread.join(2 * MS)
474 self.assertTrue(shutdown_thread.is_alive())
475
476 # Set a longer timeout here, else the test becomes flaky.
477 shutdown_thread.join(5 * MS)
478 self.assertFalse(shutdown_thread.is_alive())
479
480 def test_fileno(self):
481 """Server provides a fileno method."""
482 with run_server() as server:
483 self.assertIsInstance(server.fileno(), int)
484
485 def test_context_manager_closes_server(self):
486 """Server closes when exiting context manager."""
487 with serve(handler, "localhost", 0) as server:
488 thread = threading.Thread(target=server.serve_forever)
489 thread.start()
490 self.addCleanup(thread.join)
491 self.assertFalse(server.socket_closed.is_set())
492
493 self.assertTrue(server.socket_closed.is_set())
494
495
496 class SecureServerTests(EvalShellMixin, unittest.TestCase):
497 def test_connection(self):
498 """Server receives secure connection from client."""
499 with run_server(ssl=SERVER_CONTEXT) as server:
500 with connect(get_uri(server), ssl=CLIENT_CONTEXT) as client:
501 self.assertEval(client, "ws.protocol.state.name", "OPEN")
502 self.assertEval(client, "ws.socket.version()[:3]", "TLS")
503
504 def test_timeout_during_tls_handshake(self):
505 """Server times out before receiving TLS handshake request from client."""
506 with run_server(ssl=SERVER_CONTEXT, open_timeout=MS) as server:
507 with socket.create_connection(get_host_port(server)) as sock:
508 # Wait for the server to close the connection.
509 self.assertEqual(sock.recv(4096), b"")
510
511 def test_connection_closed_during_tls_handshake(self):
512 """Server reads EOF before receiving TLS handshake request from client."""
513 with run_server(ssl=SERVER_CONTEXT) as server:
514 with socket.create_connection(get_host_port(server)):
515 # Wait for the server to receive the connection, then close it.
516 time.sleep(MS)
517
518
519 @unittest.skipUnless(hasattr(socket, "AF_UNIX"), "this test requires Unix sockets")
520 class UnixServerTests(EvalShellMixin, unittest.TestCase):
521 def test_connection(self):
522 """Server receives connection from client over a Unix socket."""
523 with temp_unix_socket_path() as path:
524 with run_unix_server(path):
525 with unix_connect(path) as client:
526 self.assertEval(client, "ws.protocol.state.name", "OPEN")
527
528 def test_pathlib_path(self):
529 """Server accepts a pathlib.Path object as the path argument."""
530 with temp_unix_socket_path() as path:
531 with run_unix_server(pathlib.Path(path)):
532 with unix_connect(path) as client:
533 self.assertEval(client, "ws.protocol.state.name", "OPEN")
534
535
536 @unittest.skipUnless(hasattr(socket, "AF_UNIX"), "this test requires Unix sockets")
537 class SecureUnixServerTests(EvalShellMixin, unittest.TestCase):
538 def test_connection(self):
539 """Server receives secure connection from client over a Unix socket."""
540 with temp_unix_socket_path() as path:
541 with run_unix_server(path, ssl=SERVER_CONTEXT):
542 with unix_connect(path, ssl=CLIENT_CONTEXT) as client:
543 self.assertEval(client, "ws.protocol.state.name", "OPEN")
544 self.assertEval(client, "ws.socket.version()[:3]", "TLS")
545
546
547 class ServerUsageErrorsTests(unittest.TestCase):
548 def test_host_and_sock(self):
549 """Server rejects host when sock is provided."""
550 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
551 self.addCleanup(sock.close)
552 with self.assertRaises(ValueError) as raised:
553 serve(handler, host="localhost", sock=sock)
554 self.assertEqual(
555 str(raised.exception),
556 "host is incompatible with sock",
557 )
558
559 def test_port_and_sock(self):
560 """Server rejects port when sock is provided."""
561 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
562 self.addCleanup(sock.close)
563 with self.assertRaises(ValueError) as raised:
564 serve(handler, port=0, sock=sock)
565 self.assertEqual(
566 str(raised.exception),
567 "port is incompatible with sock",
568 )
569
570 def test_unix_without_path_or_sock(self):
571 """Unix server requires path when sock isn't provided."""
572 with self.assertRaises(ValueError) as raised:
573 unix_serve(handler)
574 self.assertEqual(
575 str(raised.exception),
576 "missing path argument",
577 )
578
579 def test_unix_with_path_and_sock(self):
580 """Unix server rejects path when sock is provided."""
581 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
582 self.addCleanup(sock.close)
583 with self.assertRaises(ValueError) as raised:
584 unix_serve(handler, path="/", sock=sock)
585 self.assertEqual(
586 str(raised.exception),
587 "path is incompatible with sock",
588 )
589
590 def test_invalid_subprotocol(self):
591 """Server rejects single value of subprotocols."""
592 with self.assertRaises(TypeError) as raised:
593 serve(handler, subprotocols="chat")
594 self.assertEqual(
595 str(raised.exception),
596 "subprotocols must be a list, not a str",
597 )
598
599 def test_unsupported_compression(self):
600 """Server rejects incorrect value of compression."""
601 with self.assertRaises(ValueError) as raised:
602 serve(handler, compression=False)
603 self.assertEqual(
604 str(raised.exception),
605 "unsupported compression: False",
606 )
607
608
609 class BasicAuthTests(EvalShellMixin, unittest.IsolatedAsyncioTestCase):
610 def test_valid_authorization(self):
611 """basic_auth authenticates client with HTTP Basic Authentication."""
612 with run_server(
613 process_request=basic_auth(credentials=("hello", "iloveyou")),
614 ) as server:
615 with connect(
616 get_uri(server),
617 additional_headers={"Authorization": "Basic aGVsbG86aWxvdmV5b3U="},
618 ) as client:
619 self.assertEval(client, "ws.username", "hello")
620
621 def test_missing_authorization(self):
622 """basic_auth rejects client without credentials."""
623 with run_server(
624 process_request=basic_auth(credentials=("hello", "iloveyou")),
625 ) as server:
626 with self.assertRaises(InvalidStatus) as raised:
627 with connect(get_uri(server)):
628 self.fail("did not raise")
629 self.assertEqual(
630 str(raised.exception),
631 "server rejected WebSocket connection: HTTP 401",
632 )
633
634 def test_unsupported_authorization(self):
635 """basic_auth rejects client with unsupported credentials."""
636 with run_server(
637 process_request=basic_auth(credentials=("hello", "iloveyou")),
638 ) as server:
639 with self.assertRaises(InvalidStatus) as raised:
640 with connect(
641 get_uri(server),
642 additional_headers={"Authorization": "Negotiate ..."},
643 ):
644 self.fail("did not raise")
645 self.assertEqual(
646 str(raised.exception),
647 "server rejected WebSocket connection: HTTP 401",
648 )
649
650 def test_authorization_with_unknown_username(self):
651 """basic_auth rejects client with unknown username."""
652 with run_server(
653 process_request=basic_auth(credentials=("hello", "iloveyou")),
654 ) as server:
655 with self.assertRaises(InvalidStatus) as raised:
656 with connect(
657 get_uri(server),
658 additional_headers={"Authorization": "Basic YnllOnlvdWxvdmVtZQ=="},
659 ):
660 self.fail("did not raise")
661 self.assertEqual(
662 str(raised.exception),
663 "server rejected WebSocket connection: HTTP 401",
664 )
665
666 def test_authorization_with_incorrect_password(self):
667 """basic_auth rejects client with incorrect password."""
668 with run_server(
669 process_request=basic_auth(credentials=("hello", "changeme")),
670 ) as server:
671 with self.assertRaises(InvalidStatus) as raised:
672 with connect(
673 get_uri(server),
674 additional_headers={"Authorization": "Basic aGVsbG86aWxvdmV5b3U="},
675 ):
676 self.fail("did not raise")
677 self.assertEqual(
678 str(raised.exception),
679 "server rejected WebSocket connection: HTTP 401",
680 )
681
682 def test_list_of_credentials(self):
683 """basic_auth accepts a list of hard coded credentials."""
684 with run_server(
685 process_request=basic_auth(
686 credentials=[
687 ("hello", "iloveyou"),
688 ("bye", "youloveme"),
689 ]
690 ),
691 ) as server:
692 with connect(
693 get_uri(server),
694 additional_headers={"Authorization": "Basic YnllOnlvdWxvdmVtZQ=="},
695 ) as client:
696 self.assertEval(client, "ws.username", "bye")
697
698 def test_check_credentials_function(self):
699 """basic_auth accepts a check_credentials function."""
700
701 def check_credentials(username, password):
702 self.assertEqual(username, "hello")
703 return hmac.compare_digest(password, "iloveyou")
704
705 with run_server(
706 process_request=basic_auth(check_credentials=check_credentials),
707 ) as server:
708 with connect(
709 get_uri(server),
710 additional_headers={"Authorization": "Basic aGVsbG86aWxvdmV5b3U="},
711 ) as client:
712 self.assertEval(client, "ws.username", "hello")
713
714 def test_without_credentials_or_check_credentials(self):
715 """basic_auth requires either credentials or check_credentials."""
716 with self.assertRaises(ValueError) as raised:
717 basic_auth()
718 self.assertEqual(
719 str(raised.exception),
720 "provide either credentials or check_credentials",
721 )
722
723 def test_with_credentials_and_check_credentials(self):
724 """basic_auth requires only one of credentials and check_credentials."""
725 with self.assertRaises(ValueError) as raised:
726 basic_auth(
727 credentials=("hello", "iloveyou"),
728 check_credentials=lambda: False, # pragma: no cover
729 )
730 self.assertEqual(
731 str(raised.exception),
732 "provide either credentials or check_credentials",
733 )
734
735 def test_bad_credentials(self):
736 """basic_auth receives an unsupported credentials argument."""
737 with self.assertRaises(TypeError) as raised:
738 basic_auth(credentials=42)
739 self.assertEqual(
740 str(raised.exception),
741 "invalid credentials argument: 42",
742 )
743
744 def test_bad_list_of_credentials(self):
745 """basic_auth receives an unsupported credentials argument."""
746 with self.assertRaises(TypeError) as raised:
747 basic_auth(credentials=[42])
748 self.assertEqual(
749 str(raised.exception),
750 "invalid credentials argument: [42]",
751 )
752
753
754 class BackwardsCompatibilityTests(DeprecationTestCase):
755 def test_ssl_context_argument(self):
756 """Server supports the deprecated ssl_context argument."""
757 with self.assertDeprecationWarning("ssl_context was renamed to ssl"):
758 with run_server(ssl_context=SERVER_CONTEXT) as server:
759 with connect(get_uri(server), ssl=CLIENT_CONTEXT):
760 pass
761
762 def test_web_socket_server_class(self):
763 with self.assertDeprecationWarning("WebSocketServer was renamed to Server"):
764 from websockets.sync.server import WebSocketServer
765 self.assertIs(WebSocketServer, Server)