| 1 |
import asyncio |
| 2 |
import contextlib |
| 3 |
import functools |
| 4 |
import http |
| 5 |
import logging |
| 6 |
import platform |
| 7 |
import random |
| 8 |
import re |
| 9 |
import socket |
| 10 |
import ssl |
| 11 |
import unittest |
| 12 |
import urllib.error |
| 13 |
import urllib.request |
| 14 |
import warnings |
| 15 |
from unittest.mock import patch |
| 16 |
|
| 17 |
from websockets.datastructures import Headers |
| 18 |
from websockets.exceptions import ( |
| 19 |
ConnectionClosed, |
| 20 |
InvalidHandshake, |
| 21 |
InvalidHeader, |
| 22 |
NegotiationError, |
| 23 |
) |
| 24 |
from websockets.extensions.permessage_deflate import ( |
| 25 |
ClientPerMessageDeflateFactory, |
| 26 |
PerMessageDeflate, |
| 27 |
ServerPerMessageDeflateFactory, |
| 28 |
) |
| 29 |
from websockets.frames import CloseCode |
| 30 |
from websockets.http11 import USER_AGENT |
| 31 |
from websockets.legacy.client import * |
| 32 |
from websockets.legacy.exceptions import InvalidStatusCode |
| 33 |
from websockets.legacy.handshake import build_response |
| 34 |
from websockets.legacy.http import read_response |
| 35 |
from websockets.legacy.server import * |
| 36 |
from websockets.protocol import State |
| 37 |
from websockets.uri import parse_uri |
| 38 |
|
| 39 |
from ..extensions.utils import ( |
| 40 |
ClientNoOpExtensionFactory, |
| 41 |
NoOpExtension, |
| 42 |
ServerNoOpExtensionFactory, |
| 43 |
) |
| 44 |
from ..utils import CERTIFICATE, MS, temp_unix_socket_path |
| 45 |
from .utils import AsyncioTestCase |
| 46 |
|
| 47 |
|
| 48 |
async def default_handler(ws): |
| 49 |
if ws.path == "/deprecated_attributes": |
| 50 |
await ws.recv() # delay that allows catching warnings |
| 51 |
await ws.send(repr((ws.host, ws.port, ws.secure))) |
| 52 |
elif ws.path == "/close_timeout": |
| 53 |
await ws.send(repr(ws.close_timeout)) |
| 54 |
elif ws.path == "/path": |
| 55 |
await ws.send(str(ws.path)) |
| 56 |
elif ws.path == "/headers": |
| 57 |
await ws.send(repr(ws.request_headers)) |
| 58 |
await ws.send(repr(ws.response_headers)) |
| 59 |
elif ws.path == "/extensions": |
| 60 |
await ws.send(repr(ws.extensions)) |
| 61 |
elif ws.path == "/subprotocol": |
| 62 |
await ws.send(repr(ws.subprotocol)) |
| 63 |
elif ws.path == "/slow_stop": |
| 64 |
await ws.wait_closed() |
| 65 |
await asyncio.sleep(2 * MS) |
| 66 |
else: |
| 67 |
await ws.send(await ws.recv()) |
| 68 |
|
| 69 |
|
| 70 |
async def redirect_request(path, headers, test, status): |
| 71 |
if path == "/absolute_redirect": |
| 72 |
location = get_server_uri(test.server, test.secure, "/") |
| 73 |
elif path == "/relative_redirect": |
| 74 |
location = "/" |
| 75 |
elif path == "/infinite": |
| 76 |
location = get_server_uri(test.server, test.secure, "/infinite") |
| 77 |
elif path == "/force_secure": |
| 78 |
location = get_server_uri(test.server, True, "/") |
| 79 |
elif path == "/force_insecure": |
| 80 |
location = get_server_uri(test.server, False, "/") |
| 81 |
elif path == "/missing_location": |
| 82 |
return status, {}, b"" |
| 83 |
else: |
| 84 |
return None |
| 85 |
return status, {"Location": location}, b"" |
| 86 |
|
| 87 |
|
| 88 |
@contextlib.contextmanager |
| 89 |
def temp_test_server(test, **kwargs): |
| 90 |
test.start_server(**kwargs) |
| 91 |
try: |
| 92 |
yield |
| 93 |
finally: |
| 94 |
test.stop_server() |
| 95 |
|
| 96 |
|
| 97 |
def temp_test_redirecting_server(test, status=http.HTTPStatus.FOUND, **kwargs): |
| 98 |
process_request = functools.partial(redirect_request, test=test, status=status) |
| 99 |
return temp_test_server(test, process_request=process_request, **kwargs) |
| 100 |
|
| 101 |
|
| 102 |
@contextlib.contextmanager |
| 103 |
def temp_test_client(test, *args, **kwargs): |
| 104 |
test.start_client(*args, **kwargs) |
| 105 |
try: |
| 106 |
yield |
| 107 |
finally: |
| 108 |
test.stop_client() |
| 109 |
|
| 110 |
|
| 111 |
def with_manager(manager, *args, **kwargs): |
| 112 |
""" |
| 113 |
Return a decorator that wraps a function with a context manager. |
| 114 |
|
| 115 |
""" |
| 116 |
|
| 117 |
def decorate(func): |
| 118 |
@functools.wraps(func) |
| 119 |
def _decorate(self, *_args, **_kwargs): |
| 120 |
with manager(self, *args, **kwargs): |
| 121 |
return func(self, *_args, **_kwargs) |
| 122 |
|
| 123 |
return _decorate |
| 124 |
|
| 125 |
return decorate |
| 126 |
|
| 127 |
|
| 128 |
def with_server(**kwargs): |
| 129 |
""" |
| 130 |
Return a decorator for TestCase methods that starts and stops a server. |
| 131 |
|
| 132 |
""" |
| 133 |
return with_manager(temp_test_server, **kwargs) |
| 134 |
|
| 135 |
|
| 136 |
def with_client(*args, **kwargs): |
| 137 |
""" |
| 138 |
Return a decorator for TestCase methods that starts and stops a client. |
| 139 |
|
| 140 |
""" |
| 141 |
return with_manager(temp_test_client, *args, **kwargs) |
| 142 |
|
| 143 |
|
| 144 |
def get_server_address(server): |
| 145 |
""" |
| 146 |
Return an address on which the given server listens. |
| 147 |
|
| 148 |
""" |
| 149 |
# Pick a random socket in order to test both IPv4 and IPv6 on systems |
| 150 |
# where both are available. Randomizing tests is usually a bad idea. If |
| 151 |
# needed, either use the first socket, or test separately IPv4 and IPv6. |
| 152 |
server_socket = random.choice(server.sockets) |
| 153 |
|
| 154 |
if server_socket.family == socket.AF_INET6: # pragma: no cover |
| 155 |
return server_socket.getsockname()[:2] # (no IPv6 on CI) |
| 156 |
elif server_socket.family == socket.AF_INET: |
| 157 |
return server_socket.getsockname() |
| 158 |
else: # pragma: no cover |
| 159 |
raise ValueError("expected an IPv6, IPv4, or Unix socket") |
| 160 |
|
| 161 |
|
| 162 |
def get_server_uri(server, secure=False, resource_name="/", user_info=None): |
| 163 |
""" |
| 164 |
Return a WebSocket URI for connecting to the given server. |
| 165 |
|
| 166 |
""" |
| 167 |
proto = "wss" if secure else "ws" |
| 168 |
user_info = ":".join(user_info) + "@" if user_info else "" |
| 169 |
host, port = get_server_address(server) |
| 170 |
if ":" in host: # IPv6 address |
| 171 |
host = f"[{host}]" |
| 172 |
return f"{proto}://{user_info}{host}:{port}{resource_name}" |
| 173 |
|
| 174 |
|
| 175 |
class UnauthorizedServerProtocol(WebSocketServerProtocol): |
| 176 |
async def process_request(self, path, request_headers): |
| 177 |
# Test returning headers as a Headers instance (1/3) |
| 178 |
return http.HTTPStatus.UNAUTHORIZED, Headers([("X-Access", "denied")]), b"" |
| 179 |
|
| 180 |
|
| 181 |
class ForbiddenServerProtocol(WebSocketServerProtocol): |
| 182 |
async def process_request(self, path, request_headers): |
| 183 |
# Test returning headers as a dict (2/3) |
| 184 |
return http.HTTPStatus.FORBIDDEN, {"X-Access": "denied"}, b"" |
| 185 |
|
| 186 |
|
| 187 |
class HealthCheckServerProtocol(WebSocketServerProtocol): |
| 188 |
async def process_request(self, path, request_headers): |
| 189 |
# Test returning headers as a list of pairs (3/3) |
| 190 |
if path == "/__health__/": |
| 191 |
return http.HTTPStatus.OK, [("X-Access", "OK")], b"status = green\n" |
| 192 |
|
| 193 |
|
| 194 |
class ProcessRequestReturningIntProtocol(WebSocketServerProtocol): |
| 195 |
async def process_request(self, path, request_headers): |
| 196 |
assert path == "/__health__/" |
| 197 |
return 200, [], b"OK\n" |
| 198 |
|
| 199 |
|
| 200 |
class SlowOpeningHandshakeProtocol(WebSocketServerProtocol): |
| 201 |
async def process_request(self, path, request_headers): |
| 202 |
await asyncio.sleep(10 * MS) |
| 203 |
|
| 204 |
|
| 205 |
class FooClientProtocol(WebSocketClientProtocol): |
| 206 |
pass |
| 207 |
|
| 208 |
|
| 209 |
class BarClientProtocol(WebSocketClientProtocol): |
| 210 |
pass |
| 211 |
|
| 212 |
|
| 213 |
class ClientServerTestsMixin: |
| 214 |
secure = False |
| 215 |
|
| 216 |
def setUp(self): |
| 217 |
super().setUp() |
| 218 |
self.server = None |
| 219 |
|
| 220 |
def start_server(self, deprecation_warnings=None, **kwargs): |
| 221 |
handler = kwargs.pop("handler", default_handler) |
| 222 |
# Disable compression by default in tests. |
| 223 |
kwargs.setdefault("compression", None) |
| 224 |
# Disable pings by default in tests. |
| 225 |
kwargs.setdefault("ping_interval", None) |
| 226 |
|
| 227 |
# This logic is encapsulated in a coroutine to prevent it from executing |
| 228 |
# before the event loop is running which causes asyncio.get_event_loop() |
| 229 |
# to raise a DeprecationWarning on Python ≥ 3.10. |
| 230 |
async def start_server(): |
| 231 |
return await serve(handler, "localhost", 0, **kwargs) |
| 232 |
|
| 233 |
with warnings.catch_warnings(record=True) as recorded_warnings: |
| 234 |
warnings.simplefilter("always") |
| 235 |
self.server = self.loop.run_until_complete(start_server()) |
| 236 |
|
| 237 |
expected_warnings = [] if deprecation_warnings is None else deprecation_warnings |
| 238 |
self.assertDeprecationWarnings(recorded_warnings, expected_warnings) |
| 239 |
|
| 240 |
def start_client( |
| 241 |
self, resource_name="/", user_info=None, deprecation_warnings=None, **kwargs |
| 242 |
): |
| 243 |
# Disable compression by default in tests. |
| 244 |
kwargs.setdefault("compression", None) |
| 245 |
# Disable pings by default in tests. |
| 246 |
kwargs.setdefault("ping_interval", None) |
| 247 |
|
| 248 |
secure = kwargs.get("ssl") is not None |
| 249 |
try: |
| 250 |
server_uri = kwargs.pop("uri") |
| 251 |
except KeyError: |
| 252 |
server_uri = get_server_uri(self.server, secure, resource_name, user_info) |
| 253 |
|
| 254 |
# This logic is encapsulated in a coroutine to prevent it from executing |
| 255 |
# before the event loop is running which causes asyncio.get_event_loop() |
| 256 |
# to raise a DeprecationWarning on Python ≥ 3.10. |
| 257 |
async def start_client(): |
| 258 |
return await connect(server_uri, **kwargs) |
| 259 |
|
| 260 |
with warnings.catch_warnings(record=True) as recorded_warnings: |
| 261 |
warnings.simplefilter("always") |
| 262 |
self.client = self.loop.run_until_complete(start_client()) |
| 263 |
|
| 264 |
expected_warnings = [] if deprecation_warnings is None else deprecation_warnings |
| 265 |
self.assertDeprecationWarnings(recorded_warnings, expected_warnings) |
| 266 |
|
| 267 |
def stop_client(self): |
| 268 |
self.loop.run_until_complete( |
| 269 |
asyncio.wait_for(self.client.close_connection_task, timeout=1) |
| 270 |
) |
| 271 |
|
| 272 |
def stop_server(self): |
| 273 |
self.server.close() |
| 274 |
self.loop.run_until_complete( |
| 275 |
asyncio.wait_for(self.server.wait_closed(), timeout=1) |
| 276 |
) |
| 277 |
|
| 278 |
@contextlib.contextmanager |
| 279 |
def temp_server(self, **kwargs): |
| 280 |
with temp_test_server(self, **kwargs): |
| 281 |
yield |
| 282 |
|
| 283 |
@contextlib.contextmanager |
| 284 |
def temp_client(self, *args, **kwargs): |
| 285 |
with temp_test_client(self, *args, **kwargs): |
| 286 |
yield |
| 287 |
|
| 288 |
def make_http_request(self, path="/", headers=None): |
| 289 |
if headers is None: |
| 290 |
headers = {} |
| 291 |
|
| 292 |
# Set url to 'https?://<host>:<port><path>'. |
| 293 |
url = get_server_uri( |
| 294 |
self.server, resource_name=path, secure=self.secure |
| 295 |
).replace("ws", "http") |
| 296 |
|
| 297 |
request = urllib.request.Request(url=url, headers=headers) |
| 298 |
|
| 299 |
if self.secure: |
| 300 |
open_health_check = functools.partial( |
| 301 |
urllib.request.urlopen, request, context=self.client_context |
| 302 |
) |
| 303 |
else: |
| 304 |
open_health_check = functools.partial(urllib.request.urlopen, request) |
| 305 |
|
| 306 |
return self.loop.run_in_executor(None, open_health_check) |
| 307 |
|
| 308 |
|
| 309 |
class SecureClientServerTestsMixin(ClientServerTestsMixin): |
| 310 |
secure = True |
| 311 |
|
| 312 |
@property |
| 313 |
def server_context(self): |
| 314 |
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) |
| 315 |
ssl_context.load_cert_chain(CERTIFICATE) |
| 316 |
return ssl_context |
| 317 |
|
| 318 |
@property |
| 319 |
def client_context(self): |
| 320 |
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) |
| 321 |
ssl_context.load_verify_locations(CERTIFICATE) |
| 322 |
return ssl_context |
| 323 |
|
| 324 |
def start_server(self, **kwargs): |
| 325 |
kwargs.setdefault("ssl", self.server_context) |
| 326 |
super().start_server(**kwargs) |
| 327 |
|
| 328 |
def start_client(self, path="/", **kwargs): |
| 329 |
kwargs.setdefault("ssl", self.client_context) |
| 330 |
super().start_client(path, **kwargs) |
| 331 |
|
| 332 |
|
| 333 |
class CommonClientServerTests: |
| 334 |
""" |
| 335 |
Mixin that defines most tests but doesn't inherit unittest.TestCase. |
| 336 |
|
| 337 |
Tests are run by the ClientServerTests and SecureClientServerTests subclasses. |
| 338 |
|
| 339 |
""" |
| 340 |
|
| 341 |
@with_server() |
| 342 |
@with_client() |
| 343 |
def test_basic(self): |
| 344 |
self.loop.run_until_complete(self.client.send("Hello!")) |
| 345 |
reply = self.loop.run_until_complete(self.client.recv()) |
| 346 |
self.assertEqual(reply, "Hello!") |
| 347 |
|
| 348 |
def test_redirect(self): |
| 349 |
redirect_statuses = [ |
| 350 |
http.HTTPStatus.MOVED_PERMANENTLY, |
| 351 |
http.HTTPStatus.FOUND, |
| 352 |
http.HTTPStatus.SEE_OTHER, |
| 353 |
http.HTTPStatus.TEMPORARY_REDIRECT, |
| 354 |
http.HTTPStatus.PERMANENT_REDIRECT, |
| 355 |
] |
| 356 |
for status in redirect_statuses: |
| 357 |
with temp_test_redirecting_server(self, status): |
| 358 |
with self.temp_client("/absolute_redirect"): |
| 359 |
self.loop.run_until_complete(self.client.send("Hello!")) |
| 360 |
reply = self.loop.run_until_complete(self.client.recv()) |
| 361 |
self.assertEqual(reply, "Hello!") |
| 362 |
|
| 363 |
def test_redirect_relative_location(self): |
| 364 |
with temp_test_redirecting_server(self): |
| 365 |
with self.temp_client("/relative_redirect"): |
| 366 |
self.loop.run_until_complete(self.client.send("Hello!")) |
| 367 |
reply = self.loop.run_until_complete(self.client.recv()) |
| 368 |
self.assertEqual(reply, "Hello!") |
| 369 |
|
| 370 |
def test_infinite_redirect(self): |
| 371 |
with temp_test_redirecting_server(self): |
| 372 |
with self.assertRaises(InvalidHandshake): |
| 373 |
with self.temp_client("/infinite"): |
| 374 |
self.fail("did not raise") |
| 375 |
|
| 376 |
def test_redirect_missing_location(self): |
| 377 |
with temp_test_redirecting_server(self): |
| 378 |
with self.assertRaises(InvalidHeader): |
| 379 |
with self.temp_client("/missing_location"): |
| 380 |
self.fail("did not raise") |
| 381 |
|
| 382 |
def test_loop_backwards_compatibility(self): |
| 383 |
with self.temp_server( |
| 384 |
loop=self.loop, |
| 385 |
deprecation_warnings=["remove loop argument"], |
| 386 |
): |
| 387 |
with self.temp_client( |
| 388 |
loop=self.loop, |
| 389 |
deprecation_warnings=["remove loop argument"], |
| 390 |
): |
| 391 |
self.loop.run_until_complete(self.client.send("Hello!")) |
| 392 |
reply = self.loop.run_until_complete(self.client.recv()) |
| 393 |
self.assertEqual(reply, "Hello!") |
| 394 |
|
| 395 |
@with_server() |
| 396 |
def test_explicit_host_port(self): |
| 397 |
uri = get_server_uri(self.server, self.secure) |
| 398 |
wsuri = parse_uri(uri) |
| 399 |
|
| 400 |
# Change host and port to invalid values. |
| 401 |
scheme = "wss" if wsuri.secure else "ws" |
| 402 |
port = 65535 - wsuri.port |
| 403 |
changed_uri = f"{scheme}://example.com:{port}/" |
| 404 |
|
| 405 |
with self.temp_client(uri=changed_uri, host=wsuri.host, port=wsuri.port): |
| 406 |
self.loop.run_until_complete(self.client.send("Hello!")) |
| 407 |
reply = self.loop.run_until_complete(self.client.recv()) |
| 408 |
self.assertEqual(reply, "Hello!") |
| 409 |
|
| 410 |
@with_server() |
| 411 |
def test_explicit_socket(self): |
| 412 |
class TrackedSocket(socket.socket): |
| 413 |
def __init__(self, *args, **kwargs): |
| 414 |
self.used_for_read = False |
| 415 |
self.used_for_write = False |
| 416 |
super().__init__(*args, **kwargs) |
| 417 |
|
| 418 |
def recv(self, *args, **kwargs): |
| 419 |
self.used_for_read = True |
| 420 |
return super().recv(*args, **kwargs) |
| 421 |
|
| 422 |
def recv_into(self, *args, **kwargs): |
| 423 |
self.used_for_read = True |
| 424 |
return super().recv_into(*args, **kwargs) |
| 425 |
|
| 426 |
def send(self, *args, **kwargs): |
| 427 |
self.used_for_write = True |
| 428 |
return super().send(*args, **kwargs) |
| 429 |
|
| 430 |
server_socket = [ |
| 431 |
sock for sock in self.server.sockets if sock.family == socket.AF_INET |
| 432 |
][0] |
| 433 |
client_socket = TrackedSocket(socket.AF_INET, socket.SOCK_STREAM) |
| 434 |
client_socket.connect(server_socket.getsockname()) |
| 435 |
|
| 436 |
try: |
| 437 |
self.assertFalse(client_socket.used_for_read) |
| 438 |
self.assertFalse(client_socket.used_for_write) |
| 439 |
|
| 440 |
with self.temp_client(sock=client_socket): |
| 441 |
self.loop.run_until_complete(self.client.send("Hello!")) |
| 442 |
reply = self.loop.run_until_complete(self.client.recv()) |
| 443 |
self.assertEqual(reply, "Hello!") |
| 444 |
|
| 445 |
self.assertTrue(client_socket.used_for_read) |
| 446 |
self.assertTrue(client_socket.used_for_write) |
| 447 |
|
| 448 |
finally: |
| 449 |
client_socket.close() |
| 450 |
|
| 451 |
@unittest.skipUnless(hasattr(socket, "AF_UNIX"), "this test requires Unix sockets") |
| 452 |
def test_unix_socket(self): |
| 453 |
with temp_unix_socket_path() as path: |
| 454 |
# Like self.start_server() but with unix_serve(). |
| 455 |
async def start_server(): |
| 456 |
return await unix_serve(default_handler, path) |
| 457 |
|
| 458 |
self.server = self.loop.run_until_complete(start_server()) |
| 459 |
|
| 460 |
try: |
| 461 |
# Like self.start_client() but with unix_connect() |
| 462 |
async def start_client(): |
| 463 |
return await unix_connect(path) |
| 464 |
|
| 465 |
self.client = self.loop.run_until_complete(start_client()) |
| 466 |
|
| 467 |
try: |
| 468 |
self.loop.run_until_complete(self.client.send("Hello!")) |
| 469 |
reply = self.loop.run_until_complete(self.client.recv()) |
| 470 |
self.assertEqual(reply, "Hello!") |
| 471 |
|
| 472 |
finally: |
| 473 |
self.stop_client() |
| 474 |
|
| 475 |
finally: |
| 476 |
self.stop_server() |
| 477 |
|
| 478 |
def test_ws_handler_argument_backwards_compatibility(self): |
| 479 |
async def handler_with_path(ws, path): |
| 480 |
await ws.send(path) |
| 481 |
|
| 482 |
with self.temp_server( |
| 483 |
handler=handler_with_path, |
| 484 |
deprecation_warnings=["remove second argument of ws_handler"], |
| 485 |
): |
| 486 |
with self.temp_client("/path"): |
| 487 |
self.assertEqual( |
| 488 |
self.loop.run_until_complete(self.client.recv()), |
| 489 |
"/path", |
| 490 |
) |
| 491 |
|
| 492 |
def test_ws_handler_argument_backwards_compatibility_partial(self): |
| 493 |
async def handler_with_path(ws, path, extra): |
| 494 |
await ws.send(path) |
| 495 |
|
| 496 |
bound_handler_with_path = functools.partial(handler_with_path, extra=None) |
| 497 |
|
| 498 |
with self.temp_server( |
| 499 |
handler=bound_handler_with_path, |
| 500 |
deprecation_warnings=["remove second argument of ws_handler"], |
| 501 |
): |
| 502 |
with self.temp_client("/path"): |
| 503 |
self.assertEqual( |
| 504 |
self.loop.run_until_complete(self.client.recv()), |
| 505 |
"/path", |
| 506 |
) |
| 507 |
|
| 508 |
async def process_request_OK(path, request_headers): |
| 509 |
return http.HTTPStatus.OK, [], b"OK\n" |
| 510 |
|
| 511 |
@with_server(process_request=process_request_OK) |
| 512 |
def test_process_request_argument(self): |
| 513 |
response = self.loop.run_until_complete(self.make_http_request("/")) |
| 514 |
|
| 515 |
with contextlib.closing(response): |
| 516 |
self.assertEqual(response.code, 200) |
| 517 |
|
| 518 |
def legacy_process_request_OK(path, request_headers): |
| 519 |
return http.HTTPStatus.OK, [], b"OK\n" |
| 520 |
|
| 521 |
@with_server(process_request=legacy_process_request_OK) |
| 522 |
def test_process_request_argument_backwards_compatibility(self): |
| 523 |
with warnings.catch_warnings(record=True) as recorded_warnings: |
| 524 |
warnings.simplefilter("always") |
| 525 |
response = self.loop.run_until_complete(self.make_http_request("/")) |
| 526 |
|
| 527 |
with contextlib.closing(response): |
| 528 |
self.assertEqual(response.code, 200) |
| 529 |
|
| 530 |
self.assertDeprecationWarnings( |
| 531 |
recorded_warnings, ["declare process_request as a coroutine"] |
| 532 |
) |
| 533 |
|
| 534 |
class ProcessRequestOKServerProtocol(WebSocketServerProtocol): |
| 535 |
async def process_request(self, path, request_headers): |
| 536 |
return http.HTTPStatus.OK, [], b"OK\n" |
| 537 |
|
| 538 |
@with_server(create_protocol=ProcessRequestOKServerProtocol) |
| 539 |
def test_process_request_override(self): |
| 540 |
response = self.loop.run_until_complete(self.make_http_request("/")) |
| 541 |
|
| 542 |
with contextlib.closing(response): |
| 543 |
self.assertEqual(response.code, 200) |
| 544 |
|
| 545 |
class LegacyProcessRequestOKServerProtocol(WebSocketServerProtocol): |
| 546 |
def process_request(self, path, request_headers): |
| 547 |
return http.HTTPStatus.OK, [], b"OK\n" |
| 548 |
|
| 549 |
@with_server(create_protocol=LegacyProcessRequestOKServerProtocol) |
| 550 |
def test_process_request_override_backwards_compatibility(self): |
| 551 |
with warnings.catch_warnings(record=True) as recorded_warnings: |
| 552 |
warnings.simplefilter("always") |
| 553 |
response = self.loop.run_until_complete(self.make_http_request("/")) |
| 554 |
|
| 555 |
with contextlib.closing(response): |
| 556 |
self.assertEqual(response.code, 200) |
| 557 |
|
| 558 |
self.assertDeprecationWarnings( |
| 559 |
recorded_warnings, ["declare process_request as a coroutine"] |
| 560 |
) |
| 561 |
|
| 562 |
def select_subprotocol_chat(client_subprotocols, server_subprotocols): |
| 563 |
return "chat" |
| 564 |
|
| 565 |
@with_server( |
| 566 |
subprotocols=["superchat", "chat"], select_subprotocol=select_subprotocol_chat |
| 567 |
) |
| 568 |
@with_client("/subprotocol", subprotocols=["superchat", "chat"]) |
| 569 |
def test_select_subprotocol_argument(self): |
| 570 |
server_subprotocol = self.loop.run_until_complete(self.client.recv()) |
| 571 |
self.assertEqual(server_subprotocol, repr("chat")) |
| 572 |
self.assertEqual(self.client.subprotocol, "chat") |
| 573 |
|
| 574 |
class SelectSubprotocolChatServerProtocol(WebSocketServerProtocol): |
| 575 |
def select_subprotocol(self, client_subprotocols, server_subprotocols): |
| 576 |
return "chat" |
| 577 |
|
| 578 |
@with_server( |
| 579 |
subprotocols=["superchat", "chat"], |
| 580 |
create_protocol=SelectSubprotocolChatServerProtocol, |
| 581 |
) |
| 582 |
@with_client("/subprotocol", subprotocols=["superchat", "chat"]) |
| 583 |
def test_select_subprotocol_override(self): |
| 584 |
server_subprotocol = self.loop.run_until_complete(self.client.recv()) |
| 585 |
self.assertEqual(server_subprotocol, repr("chat")) |
| 586 |
self.assertEqual(self.client.subprotocol, "chat") |
| 587 |
|
| 588 |
@with_server() |
| 589 |
@with_client("/deprecated_attributes") |
| 590 |
def test_protocol_deprecated_attributes(self): |
| 591 |
# The test could be connecting with IPv6 or IPv4. |
| 592 |
expected_client_attrs = [ |
| 593 |
server_socket.getsockname()[:2] + (self.secure,) |
| 594 |
for server_socket in self.server.sockets |
| 595 |
] |
| 596 |
with warnings.catch_warnings(record=True) as recorded_warnings: |
| 597 |
warnings.simplefilter("always") |
| 598 |
client_attrs = (self.client.host, self.client.port, self.client.secure) |
| 599 |
self.assertDeprecationWarnings( |
| 600 |
recorded_warnings, |
| 601 |
[ |
| 602 |
"use remote_address[0] instead of host", |
| 603 |
"use remote_address[1] instead of port", |
| 604 |
"don't use secure", |
| 605 |
], |
| 606 |
) |
| 607 |
self.assertIn(client_attrs, expected_client_attrs) |
| 608 |
|
| 609 |
expected_server_attrs = ("localhost", 0, self.secure) |
| 610 |
with warnings.catch_warnings(record=True) as recorded_warnings: |
| 611 |
warnings.simplefilter("always") |
| 612 |
self.loop.run_until_complete(self.client.send("")) |
| 613 |
server_attrs = self.loop.run_until_complete(self.client.recv()) |
| 614 |
self.assertDeprecationWarnings( |
| 615 |
recorded_warnings, |
| 616 |
[ |
| 617 |
"use local_address[0] instead of host", |
| 618 |
"use local_address[1] instead of port", |
| 619 |
"don't use secure", |
| 620 |
], |
| 621 |
) |
| 622 |
self.assertEqual(server_attrs, repr(expected_server_attrs)) |
| 623 |
|
| 624 |
@with_server() |
| 625 |
@with_client("/path") |
| 626 |
def test_protocol_path(self): |
| 627 |
client_path = self.client.path |
| 628 |
self.assertEqual(client_path, "/path") |
| 629 |
server_path = self.loop.run_until_complete(self.client.recv()) |
| 630 |
self.assertEqual(server_path, "/path") |
| 631 |
|
| 632 |
@with_server() |
| 633 |
@with_client("/headers") |
| 634 |
def test_protocol_headers(self): |
| 635 |
client_req = self.client.request_headers |
| 636 |
client_resp = self.client.response_headers |
| 637 |
self.assertEqual(client_req["User-Agent"], USER_AGENT) |
| 638 |
self.assertEqual(client_resp["Server"], USER_AGENT) |
| 639 |
server_req = self.loop.run_until_complete(self.client.recv()) |
| 640 |
server_resp = self.loop.run_until_complete(self.client.recv()) |
| 641 |
self.assertEqual(server_req, repr(client_req)) |
| 642 |
self.assertEqual(server_resp, repr(client_resp)) |
| 643 |
|
| 644 |
@with_server() |
| 645 |
@with_client("/headers", extra_headers={"X-Spam": "Eggs"}) |
| 646 |
def test_protocol_custom_request_headers(self): |
| 647 |
req_headers = self.loop.run_until_complete(self.client.recv()) |
| 648 |
self.loop.run_until_complete(self.client.recv()) |
| 649 |
self.assertIn("('X-Spam', 'Eggs')", req_headers) |
| 650 |
|
| 651 |
@with_server() |
| 652 |
@with_client("/headers", extra_headers={"User-Agent": "websockets"}) |
| 653 |
def test_protocol_custom_user_agent_header_legacy(self): |
| 654 |
req_headers = self.loop.run_until_complete(self.client.recv()) |
| 655 |
self.loop.run_until_complete(self.client.recv()) |
| 656 |
self.assertEqual(req_headers.count("User-Agent"), 1) |
| 657 |
self.assertIn("('User-Agent', 'websockets')", req_headers) |
| 658 |
|
| 659 |
@with_server() |
| 660 |
@with_client("/headers", user_agent_header=None) |
| 661 |
def test_protocol_no_user_agent_header(self): |
| 662 |
req_headers = self.loop.run_until_complete(self.client.recv()) |
| 663 |
self.loop.run_until_complete(self.client.recv()) |
| 664 |
self.assertNotIn("User-Agent", req_headers) |
| 665 |
|
| 666 |
@with_server() |
| 667 |
@with_client("/headers", user_agent_header="websockets") |
| 668 |
def test_protocol_custom_user_agent_header(self): |
| 669 |
req_headers = self.loop.run_until_complete(self.client.recv()) |
| 670 |
self.loop.run_until_complete(self.client.recv()) |
| 671 |
self.assertEqual(req_headers.count("User-Agent"), 1) |
| 672 |
self.assertIn("('User-Agent', 'websockets')", req_headers) |
| 673 |
|
| 674 |
@with_server(extra_headers=lambda p, r: {"X-Spam": "Eggs"}) |
| 675 |
@with_client("/headers") |
| 676 |
def test_protocol_custom_response_headers_callable(self): |
| 677 |
self.loop.run_until_complete(self.client.recv()) |
| 678 |
resp_headers = self.loop.run_until_complete(self.client.recv()) |
| 679 |
self.assertIn("('X-Spam', 'Eggs')", resp_headers) |
| 680 |
|
| 681 |
@with_server(extra_headers=lambda p, r: None) |
| 682 |
@with_client("/headers") |
| 683 |
def test_protocol_custom_response_headers_callable_none(self): |
| 684 |
self.loop.run_until_complete(self.client.recv()) # doesn't crash |
| 685 |
self.loop.run_until_complete(self.client.recv()) # nothing to check |
| 686 |
|
| 687 |
@with_server(extra_headers={"X-Spam": "Eggs"}) |
| 688 |
@with_client("/headers") |
| 689 |
def test_protocol_custom_response_headers(self): |
| 690 |
self.loop.run_until_complete(self.client.recv()) |
| 691 |
resp_headers = self.loop.run_until_complete(self.client.recv()) |
| 692 |
self.assertIn("('X-Spam', 'Eggs')", resp_headers) |
| 693 |
|
| 694 |
@with_server(extra_headers={"Server": "websockets"}) |
| 695 |
@with_client("/headers") |
| 696 |
def test_protocol_custom_server_header_legacy(self): |
| 697 |
self.loop.run_until_complete(self.client.recv()) |
| 698 |
resp_headers = self.loop.run_until_complete(self.client.recv()) |
| 699 |
self.assertEqual(resp_headers.count("Server"), 1) |
| 700 |
self.assertIn("('Server', 'websockets')", resp_headers) |
| 701 |
|
| 702 |
@with_server(server_header=None) |
| 703 |
@with_client("/headers") |
| 704 |
def test_protocol_no_server_header(self): |
| 705 |
self.loop.run_until_complete(self.client.recv()) |
| 706 |
resp_headers = self.loop.run_until_complete(self.client.recv()) |
| 707 |
self.assertNotIn("Server", resp_headers) |
| 708 |
|
| 709 |
@with_server(server_header="websockets") |
| 710 |
@with_client("/headers") |
| 711 |
def test_protocol_custom_server_header(self): |
| 712 |
self.loop.run_until_complete(self.client.recv()) |
| 713 |
resp_headers = self.loop.run_until_complete(self.client.recv()) |
| 714 |
self.assertEqual(resp_headers.count("Server"), 1) |
| 715 |
self.assertIn("('Server', 'websockets')", resp_headers) |
| 716 |
|
| 717 |
@with_server(create_protocol=HealthCheckServerProtocol) |
| 718 |
def test_http_request_http_endpoint(self): |
| 719 |
# Making an HTTP request to an HTTP endpoint succeeds. |
| 720 |
response = self.loop.run_until_complete(self.make_http_request("/__health__/")) |
| 721 |
|
| 722 |
with contextlib.closing(response): |
| 723 |
self.assertEqual(response.code, 200) |
| 724 |
self.assertEqual(response.read(), b"status = green\n") |
| 725 |
|
| 726 |
@with_server(create_protocol=HealthCheckServerProtocol) |
| 727 |
def test_http_request_ws_endpoint(self): |
| 728 |
# Making an HTTP request to a WS endpoint fails. |
| 729 |
with self.assertRaises(urllib.error.HTTPError) as raised: |
| 730 |
self.loop.run_until_complete(self.make_http_request()) |
| 731 |
|
| 732 |
with contextlib.closing(raised.exception): |
| 733 |
self.assertEqual(raised.exception.code, 426) |
| 734 |
self.assertEqual(raised.exception.headers["Upgrade"], "websocket") |
| 735 |
|
| 736 |
@with_server(create_protocol=HealthCheckServerProtocol) |
| 737 |
def test_ws_connection_http_endpoint(self): |
| 738 |
# Making a WS connection to an HTTP endpoint fails. |
| 739 |
with self.assertRaises(InvalidStatusCode) as raised: |
| 740 |
self.start_client("/__health__/") |
| 741 |
|
| 742 |
self.assertEqual(raised.exception.status_code, 200) |
| 743 |
|
| 744 |
@with_server(create_protocol=HealthCheckServerProtocol) |
| 745 |
def test_ws_connection_ws_endpoint(self): |
| 746 |
# Making a WS connection to a WS endpoint succeeds. |
| 747 |
self.start_client() |
| 748 |
self.loop.run_until_complete(self.client.send("Hello!")) |
| 749 |
self.loop.run_until_complete(self.client.recv()) |
| 750 |
self.stop_client() |
| 751 |
|
| 752 |
@with_server(create_protocol=HealthCheckServerProtocol, server_header=None) |
| 753 |
def test_http_request_no_server_header(self): |
| 754 |
response = self.loop.run_until_complete(self.make_http_request("/__health__/")) |
| 755 |
|
| 756 |
with contextlib.closing(response): |
| 757 |
self.assertNotIn("Server", response.headers) |
| 758 |
|
| 759 |
@with_server(create_protocol=HealthCheckServerProtocol, server_header="websockets") |
| 760 |
def test_http_request_custom_server_header(self): |
| 761 |
response = self.loop.run_until_complete(self.make_http_request("/__health__/")) |
| 762 |
|
| 763 |
with contextlib.closing(response): |
| 764 |
self.assertEqual(response.headers["Server"], "websockets") |
| 765 |
|
| 766 |
@with_server(create_protocol=ProcessRequestReturningIntProtocol) |
| 767 |
def test_process_request_returns_int_status(self): |
| 768 |
response = self.loop.run_until_complete(self.make_http_request("/__health__/")) |
| 769 |
|
| 770 |
with contextlib.closing(response): |
| 771 |
self.assertEqual(response.code, 200) |
| 772 |
self.assertEqual(response.read(), b"OK\n") |
| 773 |
|
| 774 |
def assert_client_raises_code(self, status_code): |
| 775 |
with self.assertRaises(InvalidStatusCode) as raised: |
| 776 |
self.start_client() |
| 777 |
self.assertEqual(raised.exception.status_code, status_code) |
| 778 |
|
| 779 |
@with_server(create_protocol=UnauthorizedServerProtocol) |
| 780 |
def test_server_create_protocol(self): |
| 781 |
self.assert_client_raises_code(401) |
| 782 |
|
| 783 |
def create_unauthorized_server_protocol(*args, **kwargs): |
| 784 |
return UnauthorizedServerProtocol(*args, **kwargs) |
| 785 |
|
| 786 |
@with_server(create_protocol=create_unauthorized_server_protocol) |
| 787 |
def test_server_create_protocol_function(self): |
| 788 |
self.assert_client_raises_code(401) |
| 789 |
|
| 790 |
@with_server( |
| 791 |
klass=UnauthorizedServerProtocol, |
| 792 |
deprecation_warnings=["rename klass to create_protocol"], |
| 793 |
) |
| 794 |
def test_server_klass_backwards_compatibility(self): |
| 795 |
self.assert_client_raises_code(401) |
| 796 |
|
| 797 |
@with_server( |
| 798 |
create_protocol=ForbiddenServerProtocol, |
| 799 |
klass=UnauthorizedServerProtocol, |
| 800 |
deprecation_warnings=["rename klass to create_protocol"], |
| 801 |
) |
| 802 |
def test_server_create_protocol_over_klass(self): |
| 803 |
self.assert_client_raises_code(403) |
| 804 |
|
| 805 |
@with_server() |
| 806 |
@with_client("/path", create_protocol=FooClientProtocol) |
| 807 |
def test_client_create_protocol(self): |
| 808 |
self.assertIsInstance(self.client, FooClientProtocol) |
| 809 |
|
| 810 |
@with_server() |
| 811 |
@with_client( |
| 812 |
"/path", |
| 813 |
create_protocol=(lambda *args, **kwargs: FooClientProtocol(*args, **kwargs)), |
| 814 |
) |
| 815 |
def test_client_create_protocol_function(self): |
| 816 |
self.assertIsInstance(self.client, FooClientProtocol) |
| 817 |
|
| 818 |
@with_server() |
| 819 |
@with_client( |
| 820 |
"/path", |
| 821 |
klass=FooClientProtocol, |
| 822 |
deprecation_warnings=["rename klass to create_protocol"], |
| 823 |
) |
| 824 |
def test_client_klass(self): |
| 825 |
self.assertIsInstance(self.client, FooClientProtocol) |
| 826 |
|
| 827 |
@with_server() |
| 828 |
@with_client( |
| 829 |
"/path", |
| 830 |
create_protocol=BarClientProtocol, |
| 831 |
klass=FooClientProtocol, |
| 832 |
deprecation_warnings=["rename klass to create_protocol"], |
| 833 |
) |
| 834 |
def test_client_create_protocol_over_klass(self): |
| 835 |
self.assertIsInstance(self.client, BarClientProtocol) |
| 836 |
|
| 837 |
@with_server(close_timeout=7) |
| 838 |
@with_client("/close_timeout") |
| 839 |
def test_server_close_timeout(self): |
| 840 |
close_timeout = self.loop.run_until_complete(self.client.recv()) |
| 841 |
self.assertEqual(eval(close_timeout), 7) |
| 842 |
|
| 843 |
@with_server(timeout=6, deprecation_warnings=["rename timeout to close_timeout"]) |
| 844 |
@with_client("/close_timeout") |
| 845 |
def test_server_timeout_backwards_compatibility(self): |
| 846 |
close_timeout = self.loop.run_until_complete(self.client.recv()) |
| 847 |
self.assertEqual(eval(close_timeout), 6) |
| 848 |
|
| 849 |
@with_server( |
| 850 |
close_timeout=7, |
| 851 |
timeout=6, |
| 852 |
deprecation_warnings=["rename timeout to close_timeout"], |
| 853 |
) |
| 854 |
@with_client("/close_timeout") |
| 855 |
def test_server_close_timeout_over_timeout(self): |
| 856 |
close_timeout = self.loop.run_until_complete(self.client.recv()) |
| 857 |
self.assertEqual(eval(close_timeout), 7) |
| 858 |
|
| 859 |
@with_server() |
| 860 |
@with_client("/close_timeout", close_timeout=7) |
| 861 |
def test_client_close_timeout(self): |
| 862 |
self.assertEqual(self.client.close_timeout, 7) |
| 863 |
|
| 864 |
@with_server() |
| 865 |
@with_client( |
| 866 |
"/close_timeout", |
| 867 |
timeout=6, |
| 868 |
deprecation_warnings=["rename timeout to close_timeout"], |
| 869 |
) |
| 870 |
def test_client_timeout_backwards_compatibility(self): |
| 871 |
self.assertEqual(self.client.close_timeout, 6) |
| 872 |
|
| 873 |
@with_server() |
| 874 |
@with_client( |
| 875 |
"/close_timeout", |
| 876 |
close_timeout=7, |
| 877 |
timeout=6, |
| 878 |
deprecation_warnings=["rename timeout to close_timeout"], |
| 879 |
) |
| 880 |
def test_client_close_timeout_over_timeout(self): |
| 881 |
self.assertEqual(self.client.close_timeout, 7) |
| 882 |
|
| 883 |
@with_server() |
| 884 |
@with_client("/extensions") |
| 885 |
def test_no_extension(self): |
| 886 |
server_extensions = self.loop.run_until_complete(self.client.recv()) |
| 887 |
self.assertEqual(server_extensions, repr([])) |
| 888 |
self.assertEqual(repr(self.client.extensions), repr([])) |
| 889 |
|
| 890 |
@with_server(extensions=[ServerNoOpExtensionFactory()]) |
| 891 |
@with_client("/extensions", extensions=[ClientNoOpExtensionFactory()]) |
| 892 |
def test_extension(self): |
| 893 |
server_extensions = self.loop.run_until_complete(self.client.recv()) |
| 894 |
self.assertEqual(server_extensions, repr([NoOpExtension()])) |
| 895 |
self.assertEqual(repr(self.client.extensions), repr([NoOpExtension()])) |
| 896 |
|
| 897 |
@with_server() |
| 898 |
@with_client("/extensions", extensions=[ClientNoOpExtensionFactory()]) |
| 899 |
def test_extension_not_accepted(self): |
| 900 |
server_extensions = self.loop.run_until_complete(self.client.recv()) |
| 901 |
self.assertEqual(server_extensions, repr([])) |
| 902 |
self.assertEqual(repr(self.client.extensions), repr([])) |
| 903 |
|
| 904 |
@with_server(extensions=[ServerNoOpExtensionFactory()]) |
| 905 |
@with_client("/extensions") |
| 906 |
def test_extension_not_requested(self): |
| 907 |
server_extensions = self.loop.run_until_complete(self.client.recv()) |
| 908 |
self.assertEqual(server_extensions, repr([])) |
| 909 |
self.assertEqual(repr(self.client.extensions), repr([])) |
| 910 |
|
| 911 |
@with_server(extensions=[ServerNoOpExtensionFactory([("foo", None)])]) |
| 912 |
def test_extension_client_rejection(self): |
| 913 |
with self.assertRaises(NegotiationError): |
| 914 |
self.start_client("/extensions", extensions=[ClientNoOpExtensionFactory()]) |
| 915 |
|
| 916 |
@with_server( |
| 917 |
extensions=[ |
| 918 |
# No match because the client doesn't send client_max_window_bits. |
| 919 |
ServerPerMessageDeflateFactory( |
| 920 |
client_max_window_bits=10, |
| 921 |
require_client_max_window_bits=True, |
| 922 |
), |
| 923 |
ServerPerMessageDeflateFactory(), |
| 924 |
] |
| 925 |
) |
| 926 |
@with_client( |
| 927 |
"/extensions", |
| 928 |
extensions=[ |
| 929 |
ClientPerMessageDeflateFactory(client_max_window_bits=None), |
| 930 |
], |
| 931 |
) |
| 932 |
def test_extension_no_match_then_match(self): |
| 933 |
# The order requested by the client has priority. |
| 934 |
server_extensions = self.loop.run_until_complete(self.client.recv()) |
| 935 |
self.assertEqual( |
| 936 |
server_extensions, repr([PerMessageDeflate(False, False, 15, 15)]) |
| 937 |
) |
| 938 |
self.assertEqual( |
| 939 |
repr(self.client.extensions), |
| 940 |
repr([PerMessageDeflate(False, False, 15, 15)]), |
| 941 |
) |
| 942 |
|
| 943 |
@with_server(extensions=[ServerPerMessageDeflateFactory()]) |
| 944 |
@with_client("/extensions", extensions=[ClientNoOpExtensionFactory()]) |
| 945 |
def test_extension_mismatch(self): |
| 946 |
server_extensions = self.loop.run_until_complete(self.client.recv()) |
| 947 |
self.assertEqual(server_extensions, repr([])) |
| 948 |
self.assertEqual(repr(self.client.extensions), repr([])) |
| 949 |
|
| 950 |
@with_server( |
| 951 |
extensions=[ServerNoOpExtensionFactory(), ServerPerMessageDeflateFactory()] |
| 952 |
) |
| 953 |
@with_client( |
| 954 |
"/extensions", |
| 955 |
extensions=[ClientPerMessageDeflateFactory(), ClientNoOpExtensionFactory()], |
| 956 |
) |
| 957 |
def test_extension_order(self): |
| 958 |
# The order requested by the client has priority. |
| 959 |
server_extensions = self.loop.run_until_complete(self.client.recv()) |
| 960 |
self.assertEqual( |
| 961 |
server_extensions, |
| 962 |
repr([PerMessageDeflate(False, False, 15, 15), NoOpExtension()]), |
| 963 |
) |
| 964 |
self.assertEqual( |
| 965 |
repr(self.client.extensions), |
| 966 |
repr([PerMessageDeflate(False, False, 15, 15), NoOpExtension()]), |
| 967 |
) |
| 968 |
|
| 969 |
@with_server(extensions=[ServerNoOpExtensionFactory()]) |
| 970 |
@patch.object(WebSocketServerProtocol, "process_extensions") |
| 971 |
def test_extensions_error(self, _process_extensions): |
| 972 |
_process_extensions.return_value = "x-no-op", [NoOpExtension()] |
| 973 |
|
| 974 |
with self.assertRaises(NegotiationError): |
| 975 |
self.start_client( |
| 976 |
"/extensions", extensions=[ClientPerMessageDeflateFactory()] |
| 977 |
) |
| 978 |
|
| 979 |
@with_server(extensions=[ServerNoOpExtensionFactory()]) |
| 980 |
@patch.object(WebSocketServerProtocol, "process_extensions") |
| 981 |
def test_extensions_error_no_extensions(self, _process_extensions): |
| 982 |
_process_extensions.return_value = "x-no-op", [NoOpExtension()] |
| 983 |
|
| 984 |
with self.assertRaises(InvalidHandshake): |
| 985 |
self.start_client("/extensions") |
| 986 |
|
| 987 |
@with_server(compression="deflate") |
| 988 |
@with_client("/extensions", compression="deflate") |
| 989 |
def test_compression_deflate(self): |
| 990 |
server_extensions = self.loop.run_until_complete(self.client.recv()) |
| 991 |
self.assertEqual( |
| 992 |
server_extensions, repr([PerMessageDeflate(False, False, 12, 12)]) |
| 993 |
) |
| 994 |
self.assertEqual( |
| 995 |
repr(self.client.extensions), |
| 996 |
repr([PerMessageDeflate(False, False, 12, 12)]), |
| 997 |
) |
| 998 |
|
| 999 |
def test_compression_unsupported_server(self): |
| 1000 |
with self.assertRaises(ValueError): |
| 1001 |
self.start_server(compression="xz") |
| 1002 |
|
| 1003 |
@with_server() |
| 1004 |
def test_compression_unsupported_client(self): |
| 1005 |
with self.assertRaises(ValueError): |
| 1006 |
self.start_client(compression="xz") |
| 1007 |
|
| 1008 |
@with_server() |
| 1009 |
@with_client("/subprotocol") |
| 1010 |
def test_no_subprotocol(self): |
| 1011 |
server_subprotocol = self.loop.run_until_complete(self.client.recv()) |
| 1012 |
self.assertEqual(server_subprotocol, repr(None)) |
| 1013 |
self.assertEqual(self.client.subprotocol, None) |
| 1014 |
|
| 1015 |
@with_server(subprotocols=["superchat", "chat"]) |
| 1016 |
@with_client("/subprotocol", subprotocols=["otherchat", "chat"]) |
| 1017 |
def test_subprotocol(self): |
| 1018 |
server_subprotocol = self.loop.run_until_complete(self.client.recv()) |
| 1019 |
self.assertEqual(server_subprotocol, repr("chat")) |
| 1020 |
self.assertEqual(self.client.subprotocol, "chat") |
| 1021 |
|
| 1022 |
def test_invalid_subprotocol_server(self): |
| 1023 |
with self.assertRaises(TypeError): |
| 1024 |
self.start_server(subprotocols="sip") |
| 1025 |
|
| 1026 |
@with_server() |
| 1027 |
def test_invalid_subprotocol_client(self): |
| 1028 |
with self.assertRaises(TypeError): |
| 1029 |
self.start_client(subprotocols="sip") |
| 1030 |
|
| 1031 |
@with_server(subprotocols=["superchat"]) |
| 1032 |
@with_client("/subprotocol", subprotocols=["otherchat"]) |
| 1033 |
def test_subprotocol_not_accepted(self): |
| 1034 |
server_subprotocol = self.loop.run_until_complete(self.client.recv()) |
| 1035 |
self.assertEqual(server_subprotocol, repr(None)) |
| 1036 |
self.assertEqual(self.client.subprotocol, None) |
| 1037 |
|
| 1038 |
@with_server() |
| 1039 |
@with_client("/subprotocol", subprotocols=["otherchat", "chat"]) |
| 1040 |
def test_subprotocol_not_offered(self): |
| 1041 |
server_subprotocol = self.loop.run_until_complete(self.client.recv()) |
| 1042 |
self.assertEqual(server_subprotocol, repr(None)) |
| 1043 |
self.assertEqual(self.client.subprotocol, None) |
| 1044 |
|
| 1045 |
@with_server(subprotocols=["superchat", "chat"]) |
| 1046 |
@with_client("/subprotocol") |
| 1047 |
def test_subprotocol_not_requested(self): |
| 1048 |
server_subprotocol = self.loop.run_until_complete(self.client.recv()) |
| 1049 |
self.assertEqual(server_subprotocol, repr(None)) |
| 1050 |
self.assertEqual(self.client.subprotocol, None) |
| 1051 |
|
| 1052 |
@with_server(subprotocols=["superchat"]) |
| 1053 |
@patch.object(WebSocketServerProtocol, "process_subprotocol") |
| 1054 |
def test_subprotocol_error(self, _process_subprotocol): |
| 1055 |
_process_subprotocol.return_value = "superchat" |
| 1056 |
|
| 1057 |
with self.assertRaises(NegotiationError): |
| 1058 |
self.start_client("/subprotocol", subprotocols=["otherchat"]) |
| 1059 |
self.run_loop_once() |
| 1060 |
|
| 1061 |
@with_server(subprotocols=["superchat"]) |
| 1062 |
@patch.object(WebSocketServerProtocol, "process_subprotocol") |
| 1063 |
def test_subprotocol_error_no_subprotocols(self, _process_subprotocol): |
| 1064 |
_process_subprotocol.return_value = "superchat" |
| 1065 |
|
| 1066 |
with self.assertRaises(InvalidHandshake): |
| 1067 |
self.start_client("/subprotocol") |
| 1068 |
self.run_loop_once() |
| 1069 |
|
| 1070 |
@with_server(subprotocols=["superchat", "chat"]) |
| 1071 |
@patch.object(WebSocketServerProtocol, "process_subprotocol") |
| 1072 |
def test_subprotocol_error_two_subprotocols(self, _process_subprotocol): |
| 1073 |
_process_subprotocol.return_value = "superchat, chat" |
| 1074 |
|
| 1075 |
with self.assertRaises(InvalidHandshake): |
| 1076 |
self.start_client("/subprotocol", subprotocols=["superchat", "chat"]) |
| 1077 |
self.run_loop_once() |
| 1078 |
|
| 1079 |
@with_server() |
| 1080 |
@patch("websockets.legacy.server.read_request") |
| 1081 |
def test_server_receives_malformed_request(self, _read_request): |
| 1082 |
_read_request.side_effect = ValueError("read_request failed") |
| 1083 |
|
| 1084 |
with self.assertRaises(InvalidHandshake): |
| 1085 |
self.start_client() |
| 1086 |
|
| 1087 |
@with_server() |
| 1088 |
@patch("websockets.legacy.client.read_response") |
| 1089 |
def test_client_receives_malformed_response(self, _read_response): |
| 1090 |
_read_response.side_effect = ValueError("read_response failed") |
| 1091 |
|
| 1092 |
with self.assertRaises(InvalidHandshake): |
| 1093 |
self.start_client() |
| 1094 |
self.run_loop_once() |
| 1095 |
|
| 1096 |
@with_server() |
| 1097 |
@patch("websockets.legacy.client.build_request") |
| 1098 |
def test_client_sends_invalid_handshake_request(self, _build_request): |
| 1099 |
def wrong_build_request(headers): |
| 1100 |
return "42" |
| 1101 |
|
| 1102 |
_build_request.side_effect = wrong_build_request |
| 1103 |
|
| 1104 |
with self.assertRaises(InvalidHandshake): |
| 1105 |
self.start_client() |
| 1106 |
|
| 1107 |
@with_server() |
| 1108 |
@patch("websockets.legacy.server.build_response") |
| 1109 |
def test_server_sends_invalid_handshake_response(self, _build_response): |
| 1110 |
def wrong_build_response(headers, key): |
| 1111 |
return build_response(headers, "42") |
| 1112 |
|
| 1113 |
_build_response.side_effect = wrong_build_response |
| 1114 |
|
| 1115 |
with self.assertRaises(InvalidHandshake): |
| 1116 |
self.start_client() |
| 1117 |
|
| 1118 |
@with_server() |
| 1119 |
@patch("websockets.legacy.client.read_response") |
| 1120 |
def test_server_does_not_switch_protocols(self, _read_response): |
| 1121 |
async def wrong_read_response(stream): |
| 1122 |
status_code, reason, headers = await read_response(stream) |
| 1123 |
return 400, "Bad Request", headers |
| 1124 |
|
| 1125 |
_read_response.side_effect = wrong_read_response |
| 1126 |
|
| 1127 |
with self.assertRaises(InvalidStatusCode): |
| 1128 |
self.start_client() |
| 1129 |
self.run_loop_once() |
| 1130 |
|
| 1131 |
@with_server() |
| 1132 |
@patch("websockets.legacy.server.WebSocketServerProtocol.process_request") |
| 1133 |
def test_server_error_in_handshake(self, _process_request): |
| 1134 |
_process_request.side_effect = Exception("process_request crashed") |
| 1135 |
|
| 1136 |
with self.assertRaises(InvalidHandshake): |
| 1137 |
self.start_client() |
| 1138 |
|
| 1139 |
@with_server(create_protocol=SlowOpeningHandshakeProtocol) |
| 1140 |
def test_client_connect_canceled_during_handshake(self): |
| 1141 |
sock = socket.create_connection(get_server_address(self.server)) |
| 1142 |
sock.send(b"") # socket is connected |
| 1143 |
|
| 1144 |
async def cancelled_client(): |
| 1145 |
start_client = connect(get_server_uri(self.server), sock=sock) |
| 1146 |
async with asyncio.timeout(5 * MS): |
| 1147 |
await start_client |
| 1148 |
|
| 1149 |
with self.assertRaises(asyncio.TimeoutError): |
| 1150 |
self.loop.run_until_complete(cancelled_client()) |
| 1151 |
|
| 1152 |
with self.assertRaises(OSError): |
| 1153 |
sock.send(b"") # socket is closed |
| 1154 |
|
| 1155 |
@with_server() |
| 1156 |
@patch("websockets.legacy.server.WebSocketServerProtocol.send") |
| 1157 |
def test_server_handler_crashes(self, send): |
| 1158 |
send.side_effect = ValueError("send failed") |
| 1159 |
|
| 1160 |
with self.temp_client(): |
| 1161 |
self.loop.run_until_complete(self.client.send("Hello!")) |
| 1162 |
with self.assertRaises(ConnectionClosed): |
| 1163 |
self.loop.run_until_complete(self.client.recv()) |
| 1164 |
|
| 1165 |
# Connection ends with an unexpected error. |
| 1166 |
self.assertEqual(self.client.close_code, CloseCode.INTERNAL_ERROR) |
| 1167 |
|
| 1168 |
@with_server() |
| 1169 |
@patch("websockets.legacy.server.WebSocketServerProtocol.close") |
| 1170 |
def test_server_close_crashes(self, close): |
| 1171 |
close.side_effect = ValueError("close failed") |
| 1172 |
|
| 1173 |
with self.temp_client(): |
| 1174 |
self.loop.run_until_complete(self.client.send("Hello!")) |
| 1175 |
reply = self.loop.run_until_complete(self.client.recv()) |
| 1176 |
self.assertEqual(reply, "Hello!") |
| 1177 |
|
| 1178 |
# Connection ends with an abnormal closure. |
| 1179 |
self.assertEqual(self.client.close_code, CloseCode.ABNORMAL_CLOSURE) |
| 1180 |
|
| 1181 |
@with_server() |
| 1182 |
@with_client() |
| 1183 |
@patch.object(WebSocketClientProtocol, "handshake") |
| 1184 |
def test_client_closes_connection_before_handshake(self, handshake): |
| 1185 |
# We have mocked the handshake() method to prevent the client from |
| 1186 |
# performing the opening handshake. Force it to close the connection. |
| 1187 |
self.client.transport.close() |
| 1188 |
# The server should stop properly anyway. It used to hang because the |
| 1189 |
# task handling the connection was waiting for the opening handshake. |
| 1190 |
|
| 1191 |
@with_server(create_protocol=SlowOpeningHandshakeProtocol) |
| 1192 |
def test_server_shuts_down_during_opening_handshake(self): |
| 1193 |
self.loop.call_later(5 * MS, self.server.close) |
| 1194 |
with self.assertRaises(InvalidStatusCode) as raised: |
| 1195 |
self.start_client() |
| 1196 |
exception = raised.exception |
| 1197 |
self.assertEqual( |
| 1198 |
str(exception), "server rejected WebSocket connection: HTTP 503" |
| 1199 |
) |
| 1200 |
self.assertEqual(exception.status_code, 503) |
| 1201 |
|
| 1202 |
@with_server() |
| 1203 |
def test_server_shuts_down_during_connection_handling(self): |
| 1204 |
with self.temp_client(): |
| 1205 |
server_ws = next(iter(self.server.websockets)) |
| 1206 |
self.server.close() |
| 1207 |
with self.assertRaises(ConnectionClosed): |
| 1208 |
self.loop.run_until_complete(self.client.send("Hello!")) |
| 1209 |
self.loop.run_until_complete(self.client.recv()) |
| 1210 |
|
| 1211 |
# Server closed the connection with 1001 Going Away. |
| 1212 |
self.assertEqual(self.client.close_code, CloseCode.GOING_AWAY) |
| 1213 |
self.assertEqual(server_ws.close_code, CloseCode.GOING_AWAY) |
| 1214 |
|
| 1215 |
@with_server() |
| 1216 |
def test_server_shuts_down_gracefully_during_connection_handling(self): |
| 1217 |
with self.temp_client(): |
| 1218 |
server_ws = next(iter(self.server.websockets)) |
| 1219 |
self.server.close(close_connections=False) |
| 1220 |
self.loop.run_until_complete(self.client.send("Hello!")) |
| 1221 |
self.loop.run_until_complete(self.client.recv()) |
| 1222 |
|
| 1223 |
# Client closed the connection with 1000 OK. |
| 1224 |
self.assertEqual(self.client.close_code, CloseCode.NORMAL_CLOSURE) |
| 1225 |
self.assertEqual(server_ws.close_code, CloseCode.NORMAL_CLOSURE) |
| 1226 |
|
| 1227 |
@with_server() |
| 1228 |
def test_server_shuts_down_and_waits_until_handlers_terminate(self): |
| 1229 |
# This handler waits a bit after the connection is closed in order |
| 1230 |
# to test that wait_closed() really waits for handlers to complete. |
| 1231 |
self.start_client("/slow_stop") |
| 1232 |
server_ws = next(iter(self.server.websockets)) |
| 1233 |
|
| 1234 |
# Test that the handler task keeps running after close(). |
| 1235 |
self.server.close() |
| 1236 |
self.loop.run_until_complete(asyncio.sleep(MS)) |
| 1237 |
self.assertFalse(server_ws.handler_task.done()) |
| 1238 |
|
| 1239 |
# Test that the handler task terminates before wait_closed() returns. |
| 1240 |
self.loop.run_until_complete(self.server.wait_closed()) |
| 1241 |
self.assertTrue(server_ws.handler_task.done()) |
| 1242 |
|
| 1243 |
@with_server(create_protocol=ForbiddenServerProtocol) |
| 1244 |
def test_invalid_status_error_during_client_connect(self): |
| 1245 |
with self.assertRaises(InvalidStatusCode) as raised: |
| 1246 |
self.start_client() |
| 1247 |
exception = raised.exception |
| 1248 |
self.assertEqual( |
| 1249 |
str(exception), "server rejected WebSocket connection: HTTP 403" |
| 1250 |
) |
| 1251 |
self.assertEqual(exception.status_code, 403) |
| 1252 |
|
| 1253 |
@with_server() |
| 1254 |
@patch("websockets.legacy.server.WebSocketServerProtocol.write_http_response") |
| 1255 |
@patch("websockets.legacy.server.WebSocketServerProtocol.read_http_request") |
| 1256 |
def test_connection_error_during_opening_handshake( |
| 1257 |
self, _read_http_request, _write_http_response |
| 1258 |
): |
| 1259 |
_read_http_request.side_effect = ConnectionError |
| 1260 |
|
| 1261 |
# This exception is currently platform-dependent. It was observed to |
| 1262 |
# be ConnectionResetError on Linux in the non-TLS case, and |
| 1263 |
# InvalidMessage otherwise (including both Linux and macOS). This |
| 1264 |
# doesn't matter though since this test is primarily for testing a |
| 1265 |
# code path on the server side. |
| 1266 |
with self.assertRaises(Exception): |
| 1267 |
self.start_client() |
| 1268 |
|
| 1269 |
# No response must not be written if the network connection is broken. |
| 1270 |
_write_http_response.assert_not_called() |
| 1271 |
|
| 1272 |
@with_server() |
| 1273 |
@patch("websockets.legacy.server.WebSocketServerProtocol.close") |
| 1274 |
def test_connection_error_during_closing_handshake(self, close): |
| 1275 |
close.side_effect = ConnectionError |
| 1276 |
|
| 1277 |
with self.temp_client(): |
| 1278 |
self.loop.run_until_complete(self.client.send("Hello!")) |
| 1279 |
reply = self.loop.run_until_complete(self.client.recv()) |
| 1280 |
self.assertEqual(reply, "Hello!") |
| 1281 |
|
| 1282 |
# Connection ends with an abnormal closure. |
| 1283 |
self.assertEqual(self.client.close_code, CloseCode.ABNORMAL_CLOSURE) |
| 1284 |
|
| 1285 |
|
| 1286 |
class ClientServerTests( |
| 1287 |
CommonClientServerTests, ClientServerTestsMixin, AsyncioTestCase |
| 1288 |
): |
| 1289 |
def test_redirect_secure(self): |
| 1290 |
with temp_test_redirecting_server(self): |
| 1291 |
# websockets doesn't support serving non-TLS and TLS connections |
| 1292 |
# from the same server and this test suite makes it difficult to |
| 1293 |
# run two servers. Therefore, we expect the redirect to create a |
| 1294 |
# TLS client connection to a non-TLS server, which will fail. |
| 1295 |
with self.assertRaises(ssl.SSLError): |
| 1296 |
with self.temp_client("/force_secure"): |
| 1297 |
self.fail("did not raise") |
| 1298 |
|
| 1299 |
|
| 1300 |
class SecureClientServerTests( |
| 1301 |
CommonClientServerTests, SecureClientServerTestsMixin, AsyncioTestCase |
| 1302 |
): |
| 1303 |
# The implementation of this test makes it hard to run it over TLS. |
| 1304 |
test_client_connect_canceled_during_handshake = None |
| 1305 |
|
| 1306 |
# TLS over Unix sockets doesn't make sense. |
| 1307 |
test_unix_socket = None |
| 1308 |
|
| 1309 |
# This test fails under PyPy due to a difference with CPython. |
| 1310 |
if platform.python_implementation() == "PyPy": # pragma: no cover |
| 1311 |
test_http_request_ws_endpoint = None |
| 1312 |
|
| 1313 |
@with_server() |
| 1314 |
def test_ws_uri_is_rejected(self): |
| 1315 |
with self.assertRaises(ValueError): |
| 1316 |
self.start_client( |
| 1317 |
uri=get_server_uri(self.server, secure=False), ssl=self.client_context |
| 1318 |
) |
| 1319 |
|
| 1320 |
def test_redirect_insecure(self): |
| 1321 |
with temp_test_redirecting_server(self): |
| 1322 |
with self.assertRaises(InvalidHandshake): |
| 1323 |
with self.temp_client("/force_insecure"): |
| 1324 |
self.fail("did not raise") |
| 1325 |
|
| 1326 |
|
| 1327 |
class ClientServerOriginTests(ClientServerTestsMixin, AsyncioTestCase): |
| 1328 |
@with_server(origins=["http://localhost"]) |
| 1329 |
@with_client(origin="http://localhost") |
| 1330 |
def test_checking_origin_succeeds(self): |
| 1331 |
self.loop.run_until_complete(self.client.send("Hello!")) |
| 1332 |
self.assertEqual(self.loop.run_until_complete(self.client.recv()), "Hello!") |
| 1333 |
|
| 1334 |
@with_server(origins=["http://localhost"]) |
| 1335 |
def test_checking_origin_fails(self): |
| 1336 |
with self.assertRaises(InvalidHandshake) as raised: |
| 1337 |
self.start_client(origin="http://otherhost") |
| 1338 |
self.assertEqual( |
| 1339 |
str(raised.exception), |
| 1340 |
"server rejected WebSocket connection: HTTP 403", |
| 1341 |
) |
| 1342 |
|
| 1343 |
@with_server(origins=["http://localhost"]) |
| 1344 |
def test_checking_origins_fails_with_multiple_headers(self): |
| 1345 |
with self.assertRaises(InvalidHandshake) as raised: |
| 1346 |
self.start_client( |
| 1347 |
origin="http://localhost", |
| 1348 |
extra_headers=[("Origin", "http://otherhost")], |
| 1349 |
) |
| 1350 |
self.assertEqual( |
| 1351 |
str(raised.exception), |
| 1352 |
"server rejected WebSocket connection: HTTP 400", |
| 1353 |
) |
| 1354 |
|
| 1355 |
@with_server(origins=[None]) |
| 1356 |
@with_client() |
| 1357 |
def test_checking_lack_of_origin_succeeds(self): |
| 1358 |
self.loop.run_until_complete(self.client.send("Hello!")) |
| 1359 |
self.assertEqual(self.loop.run_until_complete(self.client.recv()), "Hello!") |
| 1360 |
|
| 1361 |
@with_server(origins=[""]) |
| 1362 |
# The deprecation warning is raised when a client connects to the server. |
| 1363 |
@with_client(deprecation_warnings=["use None instead of '' in origins"]) |
| 1364 |
def test_checking_lack_of_origin_succeeds_backwards_compatibility(self): |
| 1365 |
self.loop.run_until_complete(self.client.send("Hello!")) |
| 1366 |
self.assertEqual(self.loop.run_until_complete(self.client.recv()), "Hello!") |
| 1367 |
|
| 1368 |
|
| 1369 |
class AsyncAwaitTests(ClientServerTestsMixin, AsyncioTestCase): |
| 1370 |
@with_server() |
| 1371 |
def test_client(self): |
| 1372 |
async def run_client(): |
| 1373 |
# Await connect. |
| 1374 |
client = await connect(get_server_uri(self.server)) |
| 1375 |
self.assertEqual(client.state, State.OPEN) |
| 1376 |
await client.close() |
| 1377 |
self.assertEqual(client.state, State.CLOSED) |
| 1378 |
|
| 1379 |
self.loop.run_until_complete(run_client()) |
| 1380 |
|
| 1381 |
def test_server(self): |
| 1382 |
async def run_server(): |
| 1383 |
# Await serve. |
| 1384 |
server = await serve(default_handler, "localhost", 0) |
| 1385 |
self.assertTrue(server.sockets) |
| 1386 |
server.close() |
| 1387 |
await server.wait_closed() |
| 1388 |
self.assertFalse(server.sockets) |
| 1389 |
|
| 1390 |
self.loop.run_until_complete(run_server()) |
| 1391 |
|
| 1392 |
|
| 1393 |
class ContextManagerTests(ClientServerTestsMixin, AsyncioTestCase): |
| 1394 |
@with_server() |
| 1395 |
def test_client(self): |
| 1396 |
async def run_client(): |
| 1397 |
# Use connect as an asynchronous context manager. |
| 1398 |
async with connect(get_server_uri(self.server)) as client: |
| 1399 |
self.assertEqual(client.state, State.OPEN) |
| 1400 |
|
| 1401 |
# Check that exiting the context manager closed the connection. |
| 1402 |
self.assertEqual(client.state, State.CLOSED) |
| 1403 |
|
| 1404 |
self.loop.run_until_complete(run_client()) |
| 1405 |
|
| 1406 |
def test_server(self): |
| 1407 |
async def run_server(): |
| 1408 |
# Use serve as an asynchronous context manager. |
| 1409 |
async with serve(default_handler, "localhost", 0) as server: |
| 1410 |
self.assertTrue(server.sockets) |
| 1411 |
|
| 1412 |
# Check that exiting the context manager closed the server. |
| 1413 |
self.assertFalse(server.sockets) |
| 1414 |
|
| 1415 |
self.loop.run_until_complete(run_server()) |
| 1416 |
|
| 1417 |
@unittest.skipUnless(hasattr(socket, "AF_UNIX"), "this test requires Unix sockets") |
| 1418 |
def test_unix_server(self): |
| 1419 |
async def run_server(path): |
| 1420 |
async with unix_serve(default_handler, path) as server: |
| 1421 |
self.assertTrue(server.sockets) |
| 1422 |
|
| 1423 |
# Check that exiting the context manager closed the server. |
| 1424 |
self.assertFalse(server.sockets) |
| 1425 |
|
| 1426 |
with temp_unix_socket_path() as path: |
| 1427 |
self.loop.run_until_complete(run_server(path)) |
| 1428 |
|
| 1429 |
|
| 1430 |
class AsyncIteratorTests(ClientServerTestsMixin, AsyncioTestCase): |
| 1431 |
# This is a protocol-level feature, but since it's a high-level API, it is |
| 1432 |
# much easier to exercise at the client or server level. |
| 1433 |
|
| 1434 |
MESSAGES = ["3", "2", "1", "Fire!"] |
| 1435 |
|
| 1436 |
async def echo_handler(ws): |
| 1437 |
for message in AsyncIteratorTests.MESSAGES: |
| 1438 |
await ws.send(message) |
| 1439 |
|
| 1440 |
@with_server(handler=echo_handler) |
| 1441 |
def test_iterate_on_messages(self): |
| 1442 |
messages = [] |
| 1443 |
|
| 1444 |
async def run_client(): |
| 1445 |
nonlocal messages |
| 1446 |
async with connect(get_server_uri(self.server)) as ws: |
| 1447 |
async for message in ws: |
| 1448 |
messages.append(message) |
| 1449 |
|
| 1450 |
self.loop.run_until_complete(run_client()) |
| 1451 |
|
| 1452 |
self.assertEqual(messages, self.MESSAGES) |
| 1453 |
|
| 1454 |
async def echo_handler_going_away(ws): |
| 1455 |
for message in AsyncIteratorTests.MESSAGES: |
| 1456 |
await ws.send(message) |
| 1457 |
await ws.close(CloseCode.GOING_AWAY) |
| 1458 |
|
| 1459 |
@with_server(handler=echo_handler_going_away) |
| 1460 |
def test_iterate_on_messages_going_away_exit_ok(self): |
| 1461 |
messages = [] |
| 1462 |
|
| 1463 |
async def run_client(): |
| 1464 |
nonlocal messages |
| 1465 |
async with connect(get_server_uri(self.server)) as ws: |
| 1466 |
async for message in ws: |
| 1467 |
messages.append(message) |
| 1468 |
|
| 1469 |
self.loop.run_until_complete(run_client()) |
| 1470 |
|
| 1471 |
self.assertEqual(messages, self.MESSAGES) |
| 1472 |
|
| 1473 |
async def echo_handler_internal_error(ws): |
| 1474 |
for message in AsyncIteratorTests.MESSAGES: |
| 1475 |
await ws.send(message) |
| 1476 |
await ws.close(CloseCode.INTERNAL_ERROR) |
| 1477 |
|
| 1478 |
@with_server(handler=echo_handler_internal_error) |
| 1479 |
def test_iterate_on_messages_internal_error_exit_not_ok(self): |
| 1480 |
messages = [] |
| 1481 |
|
| 1482 |
async def run_client(): |
| 1483 |
nonlocal messages |
| 1484 |
async with connect(get_server_uri(self.server)) as ws: |
| 1485 |
async for message in ws: |
| 1486 |
messages.append(message) |
| 1487 |
|
| 1488 |
with self.assertRaises(ConnectionClosed): |
| 1489 |
self.loop.run_until_complete(run_client()) |
| 1490 |
|
| 1491 |
self.assertEqual(messages, self.MESSAGES) |
| 1492 |
|
| 1493 |
|
| 1494 |
class ReconnectionTests(ClientServerTestsMixin, AsyncioTestCase): |
| 1495 |
async def echo_handler(ws): |
| 1496 |
async for msg in ws: |
| 1497 |
await ws.send(msg) |
| 1498 |
|
| 1499 |
service_available = True |
| 1500 |
|
| 1501 |
async def maybe_service_unavailable(path, headers): |
| 1502 |
if not ReconnectionTests.service_available: |
| 1503 |
return http.HTTPStatus.SERVICE_UNAVAILABLE, [], b"" |
| 1504 |
|
| 1505 |
async def disable_server(self, duration): |
| 1506 |
ReconnectionTests.service_available = False |
| 1507 |
await asyncio.sleep(duration) |
| 1508 |
ReconnectionTests.service_available = True |
| 1509 |
|
| 1510 |
@with_server(handler=echo_handler, process_request=maybe_service_unavailable) |
| 1511 |
def test_reconnect(self): |
| 1512 |
# Big, ugly integration test :-( |
| 1513 |
|
| 1514 |
async def run_client(): |
| 1515 |
iteration = 0 |
| 1516 |
connect_inst = connect(get_server_uri(self.server)) |
| 1517 |
connect_inst.BACKOFF_MIN = 10 * MS |
| 1518 |
connect_inst.BACKOFF_MAX = 99 * MS |
| 1519 |
connect_inst.BACKOFF_INITIAL = 0 |
| 1520 |
# coverage has a hard time dealing with this code - I give up. |
| 1521 |
async for ws in connect_inst: # pragma: no cover |
| 1522 |
await ws.send("spam") |
| 1523 |
msg = await ws.recv() |
| 1524 |
self.assertEqual(msg, "spam") |
| 1525 |
|
| 1526 |
iteration += 1 |
| 1527 |
if iteration == 1: |
| 1528 |
# Exit block normally. |
| 1529 |
pass |
| 1530 |
elif iteration == 2: |
| 1531 |
# Disable server for a little bit |
| 1532 |
asyncio.create_task(self.disable_server(50 * MS)) |
| 1533 |
await asyncio.sleep(0) |
| 1534 |
elif iteration == 3: |
| 1535 |
# Exit block after catching connection error. |
| 1536 |
server_ws = next(iter(self.server.websockets)) |
| 1537 |
await server_ws.close() |
| 1538 |
with self.assertRaises(ConnectionClosed): |
| 1539 |
await ws.recv() |
| 1540 |
else: |
| 1541 |
# Exit block with an exception. |
| 1542 |
raise Exception("BOOM") |
| 1543 |
|
| 1544 |
with self.assertLogs("websockets", logging.INFO) as logs: |
| 1545 |
with self.assertRaises(Exception) as raised: |
| 1546 |
self.loop.run_until_complete(run_client()) |
| 1547 |
self.assertEqual(str(raised.exception), "BOOM") |
| 1548 |
|
| 1549 |
# Iteration 1 |
| 1550 |
self.assertEqual( |
| 1551 |
[record.getMessage() for record in logs.records][:2], |
| 1552 |
[ |
| 1553 |
"connection open", |
| 1554 |
"connection closed", |
| 1555 |
], |
| 1556 |
) |
| 1557 |
# Iteration 2 |
| 1558 |
self.assertEqual( |
| 1559 |
[record.getMessage() for record in logs.records][2:4], |
| 1560 |
[ |
| 1561 |
"connection open", |
| 1562 |
"connection closed", |
| 1563 |
], |
| 1564 |
) |
| 1565 |
# Iteration 3 |
| 1566 |
exc = ( |
| 1567 |
"websockets.legacy.exceptions.InvalidStatusCode: " |
| 1568 |
"server rejected WebSocket connection: HTTP 503" |
| 1569 |
) |
| 1570 |
self.assertEqual( |
| 1571 |
[ |
| 1572 |
re.sub(r"[0-9\.]+ seconds", "X seconds", record.getMessage()) |
| 1573 |
for record in logs.records |
| 1574 |
][4:-1], |
| 1575 |
[ |
| 1576 |
"connection rejected (503 Service Unavailable)", |
| 1577 |
"connection closed", |
| 1578 |
f"connect failed; reconnecting in X seconds: {exc}", |
| 1579 |
] |
| 1580 |
+ [ |
| 1581 |
"connection rejected (503 Service Unavailable)", |
| 1582 |
"connection closed", |
| 1583 |
f"connect failed again; retrying in X seconds: {exc}", |
| 1584 |
] |
| 1585 |
* ((len(logs.records) - 8) // 3) |
| 1586 |
+ [ |
| 1587 |
"connection open", |
| 1588 |
"connection closed", |
| 1589 |
], |
| 1590 |
) |
| 1591 |
# Iteration 4 |
| 1592 |
self.assertEqual( |
| 1593 |
[record.getMessage() for record in logs.records][-1:], |
| 1594 |
[ |
| 1595 |
"connection open", |
| 1596 |
], |
| 1597 |
) |
| 1598 |
|
| 1599 |
|
| 1600 |
class LoggerTests(ClientServerTestsMixin, AsyncioTestCase): |
| 1601 |
def test_logger_client(self): |
| 1602 |
with self.assertLogs("test.server", logging.DEBUG) as server_logs: |
| 1603 |
self.start_server(logger=logging.getLogger("test.server")) |
| 1604 |
with self.assertLogs("test.client", logging.DEBUG) as client_logs: |
| 1605 |
self.start_client(logger=logging.getLogger("test.client")) |
| 1606 |
self.loop.run_until_complete(self.client.send("Hello!")) |
| 1607 |
self.loop.run_until_complete(self.client.recv()) |
| 1608 |
self.stop_client() |
| 1609 |
self.stop_server() |
| 1610 |
|
| 1611 |
self.assertGreater(len(server_logs.records), 0) |
| 1612 |
self.assertGreater(len(client_logs.records), 0) |