| 1 |
import contextlib |
| 2 |
import dataclasses |
| 3 |
import logging |
| 4 |
import types |
| 5 |
import unittest |
| 6 |
from unittest.mock import patch |
| 7 |
|
| 8 |
from websockets.client import * |
| 9 |
from websockets.client import backoff, process_exception |
| 10 |
from websockets.datastructures import Headers |
| 11 |
from websockets.exceptions import ( |
| 12 |
InvalidHandshake, |
| 13 |
InvalidHeader, |
| 14 |
InvalidMessage, |
| 15 |
InvalidStatus, |
| 16 |
StatusLineTooLong, |
| 17 |
) |
| 18 |
from websockets.frames import TEXT, Frame |
| 19 |
from websockets.http11 import Request, Response |
| 20 |
from websockets.protocol import CONNECTING, OPEN |
| 21 |
from websockets.uri import parse_uri |
| 22 |
from websockets.utils import accept_key |
| 23 |
|
| 24 |
from .extensions.utils import ( |
| 25 |
ClientOpExtensionFactory, |
| 26 |
ClientRsv2ExtensionFactory, |
| 27 |
OpExtension, |
| 28 |
Rsv2Extension, |
| 29 |
) |
| 30 |
from .test_utils import ACCEPT, KEY |
| 31 |
from .utils import DATE, DeprecationTestCase |
| 32 |
|
| 33 |
|
| 34 |
URI = parse_uri("wss://example.com/test") # for tests where the URI doesn't matter |
| 35 |
|
| 36 |
|
| 37 |
@patch("websockets.client.generate_key", return_value=KEY) |
| 38 |
class BasicTests(unittest.TestCase): |
| 39 |
"""Test basic opening handshake scenarios.""" |
| 40 |
|
| 41 |
def test_send_request(self, _generate_key): |
| 42 |
"""Client sends a handshake request.""" |
| 43 |
client = ClientProtocol(URI) |
| 44 |
request = client.connect() |
| 45 |
client.send_request(request) |
| 46 |
|
| 47 |
self.assertEqual( |
| 48 |
client.data_to_send(), |
| 49 |
[ |
| 50 |
f"GET /test HTTP/1.1\r\n" |
| 51 |
f"Host: example.com\r\n" |
| 52 |
f"Upgrade: websocket\r\n" |
| 53 |
f"Connection: Upgrade\r\n" |
| 54 |
f"Sec-WebSocket-Key: {KEY}\r\n" |
| 55 |
f"Sec-WebSocket-Version: 13\r\n" |
| 56 |
f"\r\n".encode() |
| 57 |
], |
| 58 |
) |
| 59 |
self.assertFalse(client.close_expected()) |
| 60 |
self.assertEqual(client.state, CONNECTING) |
| 61 |
|
| 62 |
def test_receive_successful_response(self, _generate_key): |
| 63 |
"""Client receives a successful handshake response.""" |
| 64 |
client = ClientProtocol(URI) |
| 65 |
client.receive_data( |
| 66 |
( |
| 67 |
f"HTTP/1.1 101 Switching Protocols\r\n" |
| 68 |
f"Upgrade: websocket\r\n" |
| 69 |
f"Connection: Upgrade\r\n" |
| 70 |
f"Sec-WebSocket-Accept: {ACCEPT}\r\n" |
| 71 |
f"Date: {DATE}\r\n" |
| 72 |
f"\r\n" |
| 73 |
).encode(), |
| 74 |
) |
| 75 |
|
| 76 |
self.assertEqual(client.data_to_send(), []) |
| 77 |
self.assertFalse(client.close_expected()) |
| 78 |
self.assertEqual(client.state, OPEN) |
| 79 |
|
| 80 |
def test_receive_failed_response(self, _generate_key): |
| 81 |
"""Client receives a failed handshake response.""" |
| 82 |
client = ClientProtocol(URI) |
| 83 |
client.receive_data( |
| 84 |
( |
| 85 |
f"HTTP/1.1 404 Not Found\r\n" |
| 86 |
f"Date: {DATE}\r\n" |
| 87 |
f"Content-Length: 13\r\n" |
| 88 |
f"Content-Type: text/plain; charset=utf-8\r\n" |
| 89 |
f"Connection: close\r\n" |
| 90 |
f"\r\n" |
| 91 |
f"Sorry folks.\n" |
| 92 |
).encode(), |
| 93 |
) |
| 94 |
|
| 95 |
self.assertEqual(client.data_to_send(), [b""]) |
| 96 |
self.assertTrue(client.close_expected()) |
| 97 |
self.assertEqual(client.state, CONNECTING) |
| 98 |
|
| 99 |
|
| 100 |
class RequestTests(unittest.TestCase): |
| 101 |
"""Test generating opening handshake requests.""" |
| 102 |
|
| 103 |
@patch("websockets.client.generate_key", return_value=KEY) |
| 104 |
def test_connect(self, _generate_key): |
| 105 |
"""connect() creates an opening handshake request.""" |
| 106 |
client = ClientProtocol(URI) |
| 107 |
request = client.connect() |
| 108 |
|
| 109 |
self.assertIsInstance(request, Request) |
| 110 |
self.assertEqual(request.path, "/test") |
| 111 |
self.assertEqual( |
| 112 |
request.headers, |
| 113 |
Headers( |
| 114 |
{ |
| 115 |
"Host": "example.com", |
| 116 |
"Upgrade": "websocket", |
| 117 |
"Connection": "Upgrade", |
| 118 |
"Sec-WebSocket-Key": KEY, |
| 119 |
"Sec-WebSocket-Version": "13", |
| 120 |
} |
| 121 |
), |
| 122 |
) |
| 123 |
|
| 124 |
def test_path(self): |
| 125 |
"""connect() uses the path from the URI.""" |
| 126 |
client = ClientProtocol(parse_uri("wss://example.com/endpoint?test=1")) |
| 127 |
request = client.connect() |
| 128 |
|
| 129 |
self.assertEqual(request.path, "/endpoint?test=1") |
| 130 |
|
| 131 |
def test_port(self): |
| 132 |
"""connect() uses the port from the URI or the default port.""" |
| 133 |
for uri, host in [ |
| 134 |
("ws://example.com/", "example.com"), |
| 135 |
("ws://example.com:80/", "example.com"), |
| 136 |
("ws://example.com:8080/", "example.com:8080"), |
| 137 |
("wss://example.com/", "example.com"), |
| 138 |
("wss://example.com:443/", "example.com"), |
| 139 |
("wss://example.com:8443/", "example.com:8443"), |
| 140 |
]: |
| 141 |
with self.subTest(uri=uri): |
| 142 |
client = ClientProtocol(parse_uri(uri)) |
| 143 |
request = client.connect() |
| 144 |
|
| 145 |
self.assertEqual(request.headers["Host"], host) |
| 146 |
|
| 147 |
def test_user_info(self): |
| 148 |
"""connect() performs HTTP Basic Authentication with user info from the URI.""" |
| 149 |
client = ClientProtocol(parse_uri("wss://hello:[email protected]/")) |
| 150 |
request = client.connect() |
| 151 |
|
| 152 |
self.assertEqual(request.headers["Authorization"], "Basic aGVsbG86aWxvdmV5b3U=") |
| 153 |
|
| 154 |
def test_origin(self): |
| 155 |
"""connect(origin=...) generates an Origin header.""" |
| 156 |
client = ClientProtocol(URI, origin="https://example.com") |
| 157 |
request = client.connect() |
| 158 |
|
| 159 |
self.assertEqual(request.headers["Origin"], "https://example.com") |
| 160 |
|
| 161 |
def test_extensions(self): |
| 162 |
"""connect(extensions=...) generates a Sec-WebSocket-Extensions header.""" |
| 163 |
client = ClientProtocol(URI, extensions=[ClientOpExtensionFactory()]) |
| 164 |
request = client.connect() |
| 165 |
|
| 166 |
self.assertEqual(request.headers["Sec-WebSocket-Extensions"], "x-op; op") |
| 167 |
|
| 168 |
def test_subprotocols(self): |
| 169 |
"""connect(subprotocols=...) generates a Sec-WebSocket-Protocol header.""" |
| 170 |
client = ClientProtocol(URI, subprotocols=["chat"]) |
| 171 |
request = client.connect() |
| 172 |
|
| 173 |
self.assertEqual(request.headers["Sec-WebSocket-Protocol"], "chat") |
| 174 |
|
| 175 |
|
| 176 |
@patch("websockets.client.generate_key", return_value=KEY) |
| 177 |
class ResponseTests(unittest.TestCase): |
| 178 |
"""Test receiving opening handshake responses.""" |
| 179 |
|
| 180 |
def test_receive_successful_response(self, _generate_key): |
| 181 |
"""Client receives a successful handshake response.""" |
| 182 |
client = ClientProtocol(URI) |
| 183 |
client.receive_data( |
| 184 |
( |
| 185 |
f"HTTP/1.1 101 Switching Protocols\r\n" |
| 186 |
f"Upgrade: websocket\r\n" |
| 187 |
f"Connection: Upgrade\r\n" |
| 188 |
f"Sec-WebSocket-Accept: {ACCEPT}\r\n" |
| 189 |
f"Date: {DATE}\r\n" |
| 190 |
f"\r\n" |
| 191 |
).encode(), |
| 192 |
) |
| 193 |
[response] = client.events_received() |
| 194 |
|
| 195 |
self.assertEqual(response.status_code, 101) |
| 196 |
self.assertEqual(response.reason_phrase, "Switching Protocols") |
| 197 |
self.assertEqual( |
| 198 |
response.headers, |
| 199 |
Headers( |
| 200 |
{ |
| 201 |
"Upgrade": "websocket", |
| 202 |
"Connection": "Upgrade", |
| 203 |
"Sec-WebSocket-Accept": ACCEPT, |
| 204 |
"Date": DATE, |
| 205 |
} |
| 206 |
), |
| 207 |
) |
| 208 |
self.assertEqual(response.body, b"") |
| 209 |
self.assertIsNone(client.handshake_exc) |
| 210 |
|
| 211 |
def test_receive_failed_response(self, _generate_key): |
| 212 |
"""Client receives a failed handshake response.""" |
| 213 |
client = ClientProtocol(URI) |
| 214 |
client.receive_data( |
| 215 |
( |
| 216 |
f"HTTP/1.1 404 Not Found\r\n" |
| 217 |
f"Date: {DATE}\r\n" |
| 218 |
f"Content-Length: 13\r\n" |
| 219 |
f"Content-Type: text/plain; charset=utf-8\r\n" |
| 220 |
f"Connection: close\r\n" |
| 221 |
f"\r\n" |
| 222 |
f"Sorry folks.\n" |
| 223 |
).encode(), |
| 224 |
) |
| 225 |
[response] = client.events_received() |
| 226 |
|
| 227 |
self.assertEqual(response.status_code, 404) |
| 228 |
self.assertEqual(response.reason_phrase, "Not Found") |
| 229 |
self.assertEqual( |
| 230 |
response.headers, |
| 231 |
Headers( |
| 232 |
{ |
| 233 |
"Date": DATE, |
| 234 |
"Content-Length": "13", |
| 235 |
"Content-Type": "text/plain; charset=utf-8", |
| 236 |
"Connection": "close", |
| 237 |
} |
| 238 |
), |
| 239 |
) |
| 240 |
self.assertEqual(response.body, b"Sorry folks.\n") |
| 241 |
self.assertIsInstance(client.handshake_exc, InvalidStatus) |
| 242 |
self.assertEqual( |
| 243 |
str(client.handshake_exc), |
| 244 |
"server rejected WebSocket connection: HTTP 404", |
| 245 |
) |
| 246 |
|
| 247 |
def test_receive_no_response(self, _generate_key): |
| 248 |
"""Client receives no handshake response.""" |
| 249 |
client = ClientProtocol(URI) |
| 250 |
client.receive_eof() |
| 251 |
|
| 252 |
self.assertEqual(client.events_received(), []) |
| 253 |
self.assertIsInstance(client.handshake_exc, InvalidMessage) |
| 254 |
self.assertEqual( |
| 255 |
str(client.handshake_exc), |
| 256 |
"did not receive a valid HTTP response", |
| 257 |
) |
| 258 |
self.assertIsInstance(client.handshake_exc.__cause__, EOFError) |
| 259 |
self.assertEqual( |
| 260 |
str(client.handshake_exc.__cause__), |
| 261 |
"connection closed while reading HTTP status line", |
| 262 |
) |
| 263 |
|
| 264 |
def test_receive_truncated_response(self, _generate_key): |
| 265 |
"""Client receives a truncated handshake response.""" |
| 266 |
client = ClientProtocol(URI) |
| 267 |
client.receive_data(b"HTTP/1.1 101 Switching Protocols\r\n") |
| 268 |
client.receive_eof() |
| 269 |
|
| 270 |
self.assertEqual(client.events_received(), []) |
| 271 |
self.assertIsInstance(client.handshake_exc, InvalidMessage) |
| 272 |
self.assertEqual( |
| 273 |
str(client.handshake_exc), |
| 274 |
"did not receive a valid HTTP response", |
| 275 |
) |
| 276 |
self.assertIsInstance(client.handshake_exc.__cause__, EOFError) |
| 277 |
self.assertEqual( |
| 278 |
str(client.handshake_exc.__cause__), |
| 279 |
"connection closed while reading HTTP headers", |
| 280 |
) |
| 281 |
|
| 282 |
def test_receive_junk_response(self, _generate_key): |
| 283 |
"""Client receives a junk handshake response.""" |
| 284 |
client = ClientProtocol(URI) |
| 285 |
client.receive_data(b"220 smtp.invalid\r\n") |
| 286 |
client.receive_data(b"250 Hello relay.invalid\r\n") |
| 287 |
client.receive_data(b"250 Ok\r\n") |
| 288 |
client.receive_data(b"250 Ok\r\n") |
| 289 |
|
| 290 |
self.assertEqual(client.events_received(), []) |
| 291 |
self.assertIsInstance(client.handshake_exc, InvalidMessage) |
| 292 |
self.assertEqual( |
| 293 |
str(client.handshake_exc), |
| 294 |
"did not receive a valid HTTP response", |
| 295 |
) |
| 296 |
self.assertIsInstance(client.handshake_exc.__cause__, ValueError) |
| 297 |
self.assertEqual( |
| 298 |
str(client.handshake_exc.__cause__), |
| 299 |
"invalid HTTP status line: 220 smtp.invalid", |
| 300 |
) |
| 301 |
|
| 302 |
def test_receive_status_line_too_long(self, _generate_key): |
| 303 |
"""Client receives a handshake response with a status line that's too long.""" |
| 304 |
client = ClientProtocol(URI) |
| 305 |
client.receive_data(b"HTTP/1.1 " + b"a" * 8191 + b"\r\n\r\n") |
| 306 |
|
| 307 |
self.assertEqual(client.events_received(), []) |
| 308 |
self.assertIsInstance(client.handshake_exc, StatusLineTooLong) |
| 309 |
self.assertEqual( |
| 310 |
str(client.handshake_exc), |
| 311 |
"read 8202 bytes, expected no more than 8192 bytes", |
| 312 |
) |
| 313 |
|
| 314 |
|
| 315 |
@contextlib.contextmanager |
| 316 |
def alter_and_receive_response(client): |
| 317 |
"""Generate a handshake response that can be altered for testing.""" |
| 318 |
# We could start by sending a handshake request, i.e.: |
| 319 |
# request = client.connect() |
| 320 |
# client.send_request(request) |
| 321 |
# However, in the current implementation, these calls have no effect on the |
| 322 |
# state of the client. Therefore, they're unnecessary and can be skipped. |
| 323 |
response = Response( |
| 324 |
status_code=101, |
| 325 |
reason_phrase="Switching Protocols", |
| 326 |
headers=Headers( |
| 327 |
{ |
| 328 |
"Upgrade": "websocket", |
| 329 |
"Connection": "Upgrade", |
| 330 |
"Sec-WebSocket-Accept": accept_key(client.key), |
| 331 |
} |
| 332 |
), |
| 333 |
) |
| 334 |
yield response |
| 335 |
client.receive_data(response.serialize()) |
| 336 |
[parsed_response] = client.events_received() |
| 337 |
assert response == dataclasses.replace(parsed_response, _exception=None) |
| 338 |
|
| 339 |
|
| 340 |
class HandshakeTests(unittest.TestCase): |
| 341 |
"""Test processing of handshake responses to configure the connection.""" |
| 342 |
|
| 343 |
def assertHandshakeSuccess(self, client): |
| 344 |
"""Assert that the opening handshake succeeded.""" |
| 345 |
self.assertEqual(client.state, OPEN) |
| 346 |
self.assertIsNone(client.handshake_exc) |
| 347 |
|
| 348 |
def assertHandshakeError(self, client, exc_type, msg): |
| 349 |
"""Assert that the opening handshake failed with the given exception.""" |
| 350 |
self.assertEqual(client.state, CONNECTING) |
| 351 |
self.assertIsInstance(client.handshake_exc, exc_type) |
| 352 |
# Exception chaining isn't used is client handshake implementation. |
| 353 |
assert client.handshake_exc.__cause__ is None |
| 354 |
self.assertEqual(str(client.handshake_exc), msg) |
| 355 |
|
| 356 |
def test_basic(self): |
| 357 |
"""Handshake succeeds.""" |
| 358 |
client = ClientProtocol(URI) |
| 359 |
with alter_and_receive_response(client): |
| 360 |
pass |
| 361 |
|
| 362 |
self.assertHandshakeSuccess(client) |
| 363 |
|
| 364 |
def test_missing_connection(self): |
| 365 |
"""Handshake fails when the Connection header is missing.""" |
| 366 |
client = ClientProtocol(URI) |
| 367 |
with alter_and_receive_response(client) as response: |
| 368 |
del response.headers["Connection"] |
| 369 |
|
| 370 |
self.assertHandshakeError( |
| 371 |
client, |
| 372 |
InvalidHeader, |
| 373 |
"missing Connection header", |
| 374 |
) |
| 375 |
|
| 376 |
def test_invalid_connection(self): |
| 377 |
"""Handshake fails when the Connection header is invalid.""" |
| 378 |
client = ClientProtocol(URI) |
| 379 |
with alter_and_receive_response(client) as response: |
| 380 |
del response.headers["Connection"] |
| 381 |
response.headers["Connection"] = "close" |
| 382 |
|
| 383 |
self.assertHandshakeError( |
| 384 |
client, |
| 385 |
InvalidHeader, |
| 386 |
"invalid Connection header: close", |
| 387 |
) |
| 388 |
|
| 389 |
def test_missing_upgrade(self): |
| 390 |
"""Handshake fails when the Upgrade header is missing.""" |
| 391 |
client = ClientProtocol(URI) |
| 392 |
with alter_and_receive_response(client) as response: |
| 393 |
del response.headers["Upgrade"] |
| 394 |
|
| 395 |
self.assertHandshakeError( |
| 396 |
client, |
| 397 |
InvalidHeader, |
| 398 |
"missing Upgrade header", |
| 399 |
) |
| 400 |
|
| 401 |
def test_invalid_upgrade(self): |
| 402 |
"""Handshake fails when the Upgrade header is invalid.""" |
| 403 |
client = ClientProtocol(URI) |
| 404 |
with alter_and_receive_response(client) as response: |
| 405 |
del response.headers["Upgrade"] |
| 406 |
response.headers["Upgrade"] = "h2c" |
| 407 |
|
| 408 |
self.assertHandshakeError( |
| 409 |
client, |
| 410 |
InvalidHeader, |
| 411 |
"invalid Upgrade header: h2c", |
| 412 |
) |
| 413 |
|
| 414 |
def test_missing_accept(self): |
| 415 |
"""Handshake fails when the Sec-WebSocket-Accept header is missing.""" |
| 416 |
client = ClientProtocol(URI) |
| 417 |
with alter_and_receive_response(client) as response: |
| 418 |
del response.headers["Sec-WebSocket-Accept"] |
| 419 |
|
| 420 |
self.assertHandshakeError( |
| 421 |
client, |
| 422 |
InvalidHeader, |
| 423 |
"missing Sec-WebSocket-Accept header", |
| 424 |
) |
| 425 |
|
| 426 |
def test_multiple_accept(self): |
| 427 |
"""Handshake fails when the Sec-WebSocket-Accept header is repeated.""" |
| 428 |
client = ClientProtocol(URI) |
| 429 |
with alter_and_receive_response(client) as response: |
| 430 |
response.headers["Sec-WebSocket-Accept"] = ACCEPT |
| 431 |
|
| 432 |
self.assertHandshakeError( |
| 433 |
client, |
| 434 |
InvalidHeader, |
| 435 |
"invalid Sec-WebSocket-Accept header: multiple values", |
| 436 |
) |
| 437 |
|
| 438 |
def test_invalid_accept(self): |
| 439 |
"""Handshake fails when the Sec-WebSocket-Accept header is invalid.""" |
| 440 |
client = ClientProtocol(URI) |
| 441 |
with alter_and_receive_response(client) as response: |
| 442 |
del response.headers["Sec-WebSocket-Accept"] |
| 443 |
response.headers["Sec-WebSocket-Accept"] = ACCEPT |
| 444 |
|
| 445 |
self.assertHandshakeError( |
| 446 |
client, |
| 447 |
InvalidHeader, |
| 448 |
f"invalid Sec-WebSocket-Accept header: {ACCEPT}", |
| 449 |
) |
| 450 |
|
| 451 |
def test_no_extensions(self): |
| 452 |
"""Handshake succeeds without extensions.""" |
| 453 |
client = ClientProtocol(URI) |
| 454 |
with alter_and_receive_response(client): |
| 455 |
pass |
| 456 |
|
| 457 |
self.assertHandshakeSuccess(client) |
| 458 |
self.assertEqual(client.extensions, []) |
| 459 |
|
| 460 |
def test_offer_extension(self): |
| 461 |
"""Client offers an extension.""" |
| 462 |
client = ClientProtocol(URI, extensions=[ClientRsv2ExtensionFactory()]) |
| 463 |
request = client.connect() |
| 464 |
|
| 465 |
self.assertEqual(request.headers["Sec-WebSocket-Extensions"], "x-rsv2") |
| 466 |
|
| 467 |
def test_enable_extension(self): |
| 468 |
"""Client offers an extension and the server enables it.""" |
| 469 |
client = ClientProtocol(URI, extensions=[ClientRsv2ExtensionFactory()]) |
| 470 |
with alter_and_receive_response(client) as response: |
| 471 |
response.headers["Sec-WebSocket-Extensions"] = "x-rsv2" |
| 472 |
|
| 473 |
self.assertHandshakeSuccess(client) |
| 474 |
self.assertEqual(client.extensions, [Rsv2Extension()]) |
| 475 |
|
| 476 |
def test_extension_not_enabled(self): |
| 477 |
"""Client offers an extension, but the server doesn't enable it.""" |
| 478 |
client = ClientProtocol(URI, extensions=[ClientRsv2ExtensionFactory()]) |
| 479 |
with alter_and_receive_response(client): |
| 480 |
pass |
| 481 |
|
| 482 |
self.assertHandshakeSuccess(client) |
| 483 |
self.assertEqual(client.extensions, []) |
| 484 |
|
| 485 |
def test_no_extensions_offered(self): |
| 486 |
"""Server enables an extension when the client didn't offer any.""" |
| 487 |
client = ClientProtocol(URI) |
| 488 |
with alter_and_receive_response(client) as response: |
| 489 |
response.headers["Sec-WebSocket-Extensions"] = "x-rsv2" |
| 490 |
|
| 491 |
self.assertHandshakeError( |
| 492 |
client, |
| 493 |
InvalidHandshake, |
| 494 |
"no extensions supported", |
| 495 |
) |
| 496 |
|
| 497 |
def test_extension_not_offered(self): |
| 498 |
"""Server enables an extension that the client didn't offer.""" |
| 499 |
client = ClientProtocol(URI, extensions=[ClientRsv2ExtensionFactory()]) |
| 500 |
with alter_and_receive_response(client) as response: |
| 501 |
response.headers["Sec-WebSocket-Extensions"] = "x-op; op" |
| 502 |
|
| 503 |
self.assertHandshakeError( |
| 504 |
client, |
| 505 |
InvalidHandshake, |
| 506 |
"Unsupported extension: name = x-op, params = [('op', None)]", |
| 507 |
) |
| 508 |
|
| 509 |
def test_supported_extension_parameters(self): |
| 510 |
"""Server enables an extension with parameters supported by the client.""" |
| 511 |
client = ClientProtocol(URI, extensions=[ClientOpExtensionFactory("this")]) |
| 512 |
with alter_and_receive_response(client) as response: |
| 513 |
response.headers["Sec-WebSocket-Extensions"] = "x-op; op=this" |
| 514 |
|
| 515 |
self.assertHandshakeSuccess(client) |
| 516 |
self.assertEqual(client.extensions, [OpExtension("this")]) |
| 517 |
|
| 518 |
def test_unsupported_extension_parameters(self): |
| 519 |
"""Server enables an extension with parameters unsupported by the client.""" |
| 520 |
client = ClientProtocol(URI, extensions=[ClientOpExtensionFactory("this")]) |
| 521 |
with alter_and_receive_response(client) as response: |
| 522 |
response.headers["Sec-WebSocket-Extensions"] = "x-op; op=that" |
| 523 |
|
| 524 |
self.assertHandshakeError( |
| 525 |
client, |
| 526 |
InvalidHandshake, |
| 527 |
"Unsupported extension: name = x-op, params = [('op', 'that')]", |
| 528 |
) |
| 529 |
|
| 530 |
def test_multiple_supported_extension_parameters(self): |
| 531 |
"""Client offers the same extension with several parameters.""" |
| 532 |
client = ClientProtocol( |
| 533 |
URI, |
| 534 |
extensions=[ |
| 535 |
ClientOpExtensionFactory("this"), |
| 536 |
ClientOpExtensionFactory("that"), |
| 537 |
], |
| 538 |
) |
| 539 |
with alter_and_receive_response(client) as response: |
| 540 |
response.headers["Sec-WebSocket-Extensions"] = "x-op; op=that" |
| 541 |
|
| 542 |
self.assertHandshakeSuccess(client) |
| 543 |
self.assertEqual(client.extensions, [OpExtension("that")]) |
| 544 |
|
| 545 |
def test_multiple_extensions(self): |
| 546 |
"""Client offers several extensions and the server enables them.""" |
| 547 |
client = ClientProtocol( |
| 548 |
URI, |
| 549 |
extensions=[ |
| 550 |
ClientOpExtensionFactory(), |
| 551 |
ClientRsv2ExtensionFactory(), |
| 552 |
], |
| 553 |
) |
| 554 |
with alter_and_receive_response(client) as response: |
| 555 |
response.headers["Sec-WebSocket-Extensions"] = "x-op; op" |
| 556 |
response.headers["Sec-WebSocket-Extensions"] = "x-rsv2" |
| 557 |
|
| 558 |
self.assertHandshakeSuccess(client) |
| 559 |
self.assertEqual(client.extensions, [OpExtension(), Rsv2Extension()]) |
| 560 |
|
| 561 |
def test_multiple_extensions_order(self): |
| 562 |
"""Client respects the order of extensions chosen by the server.""" |
| 563 |
client = ClientProtocol( |
| 564 |
URI, |
| 565 |
extensions=[ |
| 566 |
ClientOpExtensionFactory(), |
| 567 |
ClientRsv2ExtensionFactory(), |
| 568 |
], |
| 569 |
) |
| 570 |
with alter_and_receive_response(client) as response: |
| 571 |
response.headers["Sec-WebSocket-Extensions"] = "x-rsv2" |
| 572 |
response.headers["Sec-WebSocket-Extensions"] = "x-op; op" |
| 573 |
|
| 574 |
self.assertHandshakeSuccess(client) |
| 575 |
self.assertEqual(client.extensions, [Rsv2Extension(), OpExtension()]) |
| 576 |
|
| 577 |
def test_no_subprotocols(self): |
| 578 |
"""Handshake succeeds without subprotocols.""" |
| 579 |
client = ClientProtocol(URI) |
| 580 |
with alter_and_receive_response(client): |
| 581 |
pass |
| 582 |
|
| 583 |
self.assertHandshakeSuccess(client) |
| 584 |
self.assertIsNone(client.subprotocol) |
| 585 |
|
| 586 |
def test_no_subprotocol_requested(self): |
| 587 |
"""Client doesn't offer a subprotocol, but the server enables one.""" |
| 588 |
client = ClientProtocol(URI) |
| 589 |
with alter_and_receive_response(client) as response: |
| 590 |
response.headers["Sec-WebSocket-Protocol"] = "chat" |
| 591 |
|
| 592 |
self.assertHandshakeError( |
| 593 |
client, |
| 594 |
InvalidHandshake, |
| 595 |
"no subprotocols supported", |
| 596 |
) |
| 597 |
|
| 598 |
def test_offer_subprotocol(self): |
| 599 |
"""Client offers a subprotocol.""" |
| 600 |
client = ClientProtocol(URI, subprotocols=["chat"]) |
| 601 |
request = client.connect() |
| 602 |
|
| 603 |
self.assertEqual(request.headers["Sec-WebSocket-Protocol"], "chat") |
| 604 |
|
| 605 |
def test_enable_subprotocol(self): |
| 606 |
"""Client offers a subprotocol and the server enables it.""" |
| 607 |
client = ClientProtocol(URI, subprotocols=["chat"]) |
| 608 |
with alter_and_receive_response(client) as response: |
| 609 |
response.headers["Sec-WebSocket-Protocol"] = "chat" |
| 610 |
|
| 611 |
self.assertHandshakeSuccess(client) |
| 612 |
self.assertEqual(client.subprotocol, "chat") |
| 613 |
|
| 614 |
def test_no_subprotocol_accepted(self): |
| 615 |
"""Client offers a subprotocol, but the server doesn't enable it.""" |
| 616 |
client = ClientProtocol(URI, subprotocols=["chat"]) |
| 617 |
with alter_and_receive_response(client): |
| 618 |
pass |
| 619 |
|
| 620 |
self.assertHandshakeSuccess(client) |
| 621 |
self.assertIsNone(client.subprotocol) |
| 622 |
|
| 623 |
def test_multiple_subprotocols(self): |
| 624 |
"""Client offers several subprotocols and the server enables one.""" |
| 625 |
client = ClientProtocol(URI, subprotocols=["superchat", "chat"]) |
| 626 |
with alter_and_receive_response(client) as response: |
| 627 |
response.headers["Sec-WebSocket-Protocol"] = "chat" |
| 628 |
|
| 629 |
self.assertHandshakeSuccess(client) |
| 630 |
self.assertEqual(client.subprotocol, "chat") |
| 631 |
|
| 632 |
def test_unsupported_subprotocol(self): |
| 633 |
"""Client offers subprotocols but the server enables another one.""" |
| 634 |
client = ClientProtocol(URI, subprotocols=["superchat", "chat"]) |
| 635 |
with alter_and_receive_response(client) as response: |
| 636 |
response.headers["Sec-WebSocket-Protocol"] = "otherchat" |
| 637 |
|
| 638 |
self.assertHandshakeError( |
| 639 |
client, |
| 640 |
InvalidHandshake, |
| 641 |
"unsupported subprotocol: otherchat", |
| 642 |
) |
| 643 |
|
| 644 |
def test_multiple_subprotocols_accepted(self): |
| 645 |
"""Server attempts to enable multiple subprotocols.""" |
| 646 |
client = ClientProtocol(URI, subprotocols=["superchat", "chat"]) |
| 647 |
with alter_and_receive_response(client) as response: |
| 648 |
response.headers["Sec-WebSocket-Protocol"] = "superchat" |
| 649 |
response.headers["Sec-WebSocket-Protocol"] = "chat" |
| 650 |
|
| 651 |
self.assertHandshakeError( |
| 652 |
client, |
| 653 |
InvalidHandshake, |
| 654 |
"invalid Sec-WebSocket-Protocol header: multiple values: superchat, chat", |
| 655 |
) |
| 656 |
|
| 657 |
|
| 658 |
class MiscTests(unittest.TestCase): |
| 659 |
def test_bypass_handshake(self): |
| 660 |
"""ClientProtocol bypasses the opening handshake.""" |
| 661 |
client = ClientProtocol(URI, state=OPEN) |
| 662 |
client.receive_data(b"\x81\x06Hello!") |
| 663 |
[frame] = client.events_received() |
| 664 |
self.assertEqual(frame, Frame(TEXT, b"Hello!")) |
| 665 |
|
| 666 |
def test_custom_logger(self): |
| 667 |
"""ClientProtocol accepts a logger argument.""" |
| 668 |
logger = logging.getLogger("test") |
| 669 |
with self.assertLogs("test", logging.DEBUG) as logs: |
| 670 |
ClientProtocol(URI, logger=logger) |
| 671 |
self.assertEqual(len(logs.records), 1) |
| 672 |
|
| 673 |
|
| 674 |
class BackwardsCompatibilityTests(DeprecationTestCase): |
| 675 |
def test_client_connection_class(self): |
| 676 |
"""ClientConnection is a deprecated alias for ClientProtocol.""" |
| 677 |
with self.assertDeprecationWarning( |
| 678 |
"ClientConnection was renamed to ClientProtocol" |
| 679 |
): |
| 680 |
from websockets.client import ClientConnection |
| 681 |
|
| 682 |
client = ClientConnection("ws://localhost/") |
| 683 |
|
| 684 |
self.assertIsInstance(client, ClientProtocol) |
| 685 |
|
| 686 |
|
| 687 |
class ProcessExceptionTests(unittest.TestCase): |
| 688 |
def test_process_exception_retryable(self): |
| 689 |
"""process_exception(exc) returns None on retriable errors.""" |
| 690 |
connection_closed_exc = InvalidMessage("did not receive a valid HTTP response") |
| 691 |
connection_closed_exc.__cause__ = EOFError( |
| 692 |
"connection closed while reading HTTP status line" |
| 693 |
) |
| 694 |
for exc in [ |
| 695 |
ConnectionRefusedError(61, "Connection refused"), |
| 696 |
TimeoutError("timed out while waiting for handshake response"), |
| 697 |
connection_closed_exc, |
| 698 |
InvalidStatus(Response(503, "Service Unavailable", Headers(), b"")), |
| 699 |
]: |
| 700 |
with self.subTest(exc=exc): |
| 701 |
self.assertIsNone(process_exception(exc)) |
| 702 |
|
| 703 |
def test_process_exception_fatal(self): |
| 704 |
"""process_exception(exc) returns exc on fatal errors.""" |
| 705 |
for exc in [ |
| 706 |
InvalidStatus(Response(410, "Gone", Headers(), b"")), |
| 707 |
AssertionError("unexpected error"), |
| 708 |
]: |
| 709 |
with self.subTest(exc=exc): |
| 710 |
self.assertIs(process_exception(exc), exc) |
| 711 |
|
| 712 |
|
| 713 |
class BackoffTests(unittest.TestCase): |
| 714 |
def test_backoff(self): |
| 715 |
"""backoff() yields a random delay, then exponentially increasing delays.""" |
| 716 |
backoff_gen = backoff() |
| 717 |
self.assertIsInstance(backoff_gen, types.GeneratorType) |
| 718 |
|
| 719 |
initial_delay = next(backoff_gen) |
| 720 |
self.assertGreaterEqual(initial_delay, 0) |
| 721 |
self.assertLess(initial_delay, 5) |
| 722 |
|
| 723 |
following_delays = [int(next(backoff_gen)) for _ in range(9)] |
| 724 |
self.assertEqual(following_delays, [3, 5, 8, 13, 21, 34, 55, 89, 90]) |