| 1 |
import asyncio |
| 2 |
import dataclasses |
| 3 |
import hmac |
| 4 |
import http |
| 5 |
import logging |
| 6 |
import pathlib |
| 7 |
import socket |
| 8 |
import unittest |
| 9 |
|
| 10 |
from websockets.asyncio.client import connect, unix_connect |
| 11 |
from websockets.asyncio.server import * |
| 12 |
from websockets.exceptions import ( |
| 13 |
ConnectionClosedError, |
| 14 |
ConnectionClosedOK, |
| 15 |
InvalidHandshake, |
| 16 |
InvalidStatus, |
| 17 |
NegotiationError, |
| 18 |
) |
| 19 |
from websockets.http11 import Request, Response |
| 20 |
|
| 21 |
from ..utils import ( |
| 22 |
CLIENT_CONTEXT, |
| 23 |
MS, |
| 24 |
SERVER_CONTEXT, |
| 25 |
LoggingTestCase, |
| 26 |
temp_unix_socket_path, |
| 27 |
) |
| 28 |
from .server import ( |
| 29 |
EvalShellMixin, |
| 30 |
args, |
| 31 |
get_host_port, |
| 32 |
get_uri, |
| 33 |
handler, |
| 34 |
) |
| 35 |
|
| 36 |
|
| 37 |
class ServerTests(EvalShellMixin, LoggingTestCase, unittest.IsolatedAsyncioTestCase): |
| 38 |
async def test_connection(self): |
| 39 |
"""Server receives connection from client and the handshake succeeds.""" |
| 40 |
async with serve(*args) as server: |
| 41 |
async with connect(get_uri(server)) as client: |
| 42 |
await self.assertEval(client, "ws.protocol.state.name", "OPEN") |
| 43 |
|
| 44 |
async def test_connection_handler_returns(self): |
| 45 |
"""Connection handler returns.""" |
| 46 |
async with serve(*args) as server: |
| 47 |
async with connect(get_uri(server) + "/no-op") as client: |
| 48 |
with self.assertRaises(ConnectionClosedOK) as raised: |
| 49 |
await client.recv() |
| 50 |
self.assertEqual( |
| 51 |
str(raised.exception), |
| 52 |
"received 1000 (OK); then sent 1000 (OK)", |
| 53 |
) |
| 54 |
|
| 55 |
async def test_connection_handler_raises_exception(self): |
| 56 |
"""Connection handler raises an exception.""" |
| 57 |
async with serve(*args) as server: |
| 58 |
async with connect(get_uri(server) + "/crash") as client: |
| 59 |
with self.assertRaises(ConnectionClosedError) as raised: |
| 60 |
await client.recv() |
| 61 |
self.assertEqual( |
| 62 |
str(raised.exception), |
| 63 |
"received 1011 (internal error); then sent 1011 (internal error)", |
| 64 |
) |
| 65 |
|
| 66 |
async def test_existing_socket(self): |
| 67 |
"""Server receives connection using a pre-existing socket.""" |
| 68 |
with socket.create_server(("localhost", 0)) as sock: |
| 69 |
host, port = sock.getsockname() |
| 70 |
async with serve(handler, sock=sock): |
| 71 |
async with connect(f"ws://{host}:{port}/") as client: |
| 72 |
await self.assertEval(client, "ws.protocol.state.name", "OPEN") |
| 73 |
|
| 74 |
async def test_select_subprotocol(self): |
| 75 |
"""Server selects a subprotocol with the select_subprotocol callable.""" |
| 76 |
|
| 77 |
def select_subprotocol(ws, subprotocols): |
| 78 |
ws.select_subprotocol_ran = True |
| 79 |
assert "chat" in subprotocols |
| 80 |
return "chat" |
| 81 |
|
| 82 |
async with serve( |
| 83 |
*args, |
| 84 |
subprotocols=["chat"], |
| 85 |
select_subprotocol=select_subprotocol, |
| 86 |
) as server: |
| 87 |
async with connect(get_uri(server), subprotocols=["chat"]) as client: |
| 88 |
await self.assertEval(client, "ws.select_subprotocol_ran", "True") |
| 89 |
await self.assertEval(client, "ws.subprotocol", "chat") |
| 90 |
|
| 91 |
async def test_select_subprotocol_rejects_handshake(self): |
| 92 |
"""Server rejects handshake if select_subprotocol raises NegotiationError.""" |
| 93 |
|
| 94 |
def select_subprotocol(ws, subprotocols): |
| 95 |
raise NegotiationError |
| 96 |
|
| 97 |
async with serve(*args, select_subprotocol=select_subprotocol) as server: |
| 98 |
with self.assertRaises(InvalidStatus) as raised: |
| 99 |
async with connect(get_uri(server)): |
| 100 |
self.fail("did not raise") |
| 101 |
self.assertEqual( |
| 102 |
str(raised.exception), |
| 103 |
"server rejected WebSocket connection: HTTP 400", |
| 104 |
) |
| 105 |
|
| 106 |
async def test_select_subprotocol_raises_exception(self): |
| 107 |
"""Server returns an error if select_subprotocol raises an exception.""" |
| 108 |
|
| 109 |
def select_subprotocol(ws, subprotocols): |
| 110 |
raise RuntimeError |
| 111 |
|
| 112 |
async with serve(*args, select_subprotocol=select_subprotocol) as server: |
| 113 |
with self.assertRaises(InvalidStatus) as raised: |
| 114 |
async with connect(get_uri(server)): |
| 115 |
self.fail("did not raise") |
| 116 |
self.assertEqual( |
| 117 |
str(raised.exception), |
| 118 |
"server rejected WebSocket connection: HTTP 500", |
| 119 |
) |
| 120 |
|
| 121 |
async def test_compression_is_enabled(self): |
| 122 |
"""Server enables compression by default.""" |
| 123 |
async with serve(*args) as server: |
| 124 |
async with connect(get_uri(server)) as client: |
| 125 |
await self.assertEval( |
| 126 |
client, |
| 127 |
"[type(ext).__name__ for ext in ws.protocol.extensions]", |
| 128 |
"['PerMessageDeflate']", |
| 129 |
) |
| 130 |
|
| 131 |
async def test_disable_compression(self): |
| 132 |
"""Server disables compression.""" |
| 133 |
async with serve(*args, compression=None) as server: |
| 134 |
async with connect(get_uri(server)) as client: |
| 135 |
await self.assertEval(client, "ws.protocol.extensions", "[]") |
| 136 |
|
| 137 |
async def test_process_request_returns_none(self): |
| 138 |
"""Server runs process_request and continues the handshake.""" |
| 139 |
|
| 140 |
def process_request(ws, request): |
| 141 |
self.assertIsInstance(request, Request) |
| 142 |
ws.process_request_ran = True |
| 143 |
|
| 144 |
async with serve(*args, process_request=process_request) as server: |
| 145 |
async with connect(get_uri(server)) as client: |
| 146 |
await self.assertEval(client, "ws.process_request_ran", "True") |
| 147 |
|
| 148 |
async def test_async_process_request_returns_none(self): |
| 149 |
"""Server runs async process_request and continues the handshake.""" |
| 150 |
|
| 151 |
async def process_request(ws, request): |
| 152 |
self.assertIsInstance(request, Request) |
| 153 |
ws.process_request_ran = True |
| 154 |
|
| 155 |
async with serve(*args, process_request=process_request) as server: |
| 156 |
async with connect(get_uri(server)) as client: |
| 157 |
await self.assertEval(client, "ws.process_request_ran", "True") |
| 158 |
|
| 159 |
async def test_process_request_returns_response(self): |
| 160 |
"""Server aborts handshake if process_request returns a response.""" |
| 161 |
|
| 162 |
def process_request(ws, request): |
| 163 |
return ws.respond(http.HTTPStatus.FORBIDDEN, "Forbidden") |
| 164 |
|
| 165 |
async def handler(ws): |
| 166 |
self.fail("handler must not run") |
| 167 |
|
| 168 |
with self.assertNoLogs("websockets", logging.ERROR): |
| 169 |
async with serve( |
| 170 |
handler, *args[1:], process_request=process_request |
| 171 |
) as server: |
| 172 |
with self.assertRaises(InvalidStatus) as raised: |
| 173 |
async with connect(get_uri(server)): |
| 174 |
self.fail("did not raise") |
| 175 |
self.assertEqual( |
| 176 |
str(raised.exception), |
| 177 |
"server rejected WebSocket connection: HTTP 403", |
| 178 |
) |
| 179 |
|
| 180 |
async def test_async_process_request_returns_response(self): |
| 181 |
"""Server aborts handshake if async process_request returns a response.""" |
| 182 |
|
| 183 |
async def process_request(ws, request): |
| 184 |
return ws.respond(http.HTTPStatus.FORBIDDEN, "Forbidden") |
| 185 |
|
| 186 |
async def handler(ws): |
| 187 |
self.fail("handler must not run") |
| 188 |
|
| 189 |
with self.assertNoLogs("websockets", logging.ERROR): |
| 190 |
async with serve( |
| 191 |
handler, *args[1:], process_request=process_request |
| 192 |
) as server: |
| 193 |
with self.assertRaises(InvalidStatus) as raised: |
| 194 |
async with connect(get_uri(server)): |
| 195 |
self.fail("did not raise") |
| 196 |
self.assertEqual( |
| 197 |
str(raised.exception), |
| 198 |
"server rejected WebSocket connection: HTTP 403", |
| 199 |
) |
| 200 |
|
| 201 |
async def test_process_request_raises_exception(self): |
| 202 |
"""Server returns an error if process_request raises an exception.""" |
| 203 |
|
| 204 |
def process_request(ws, request): |
| 205 |
raise RuntimeError("BOOM") |
| 206 |
|
| 207 |
with self.assertLogs("websockets", logging.ERROR) as logs: |
| 208 |
async with serve(*args, process_request=process_request) as server: |
| 209 |
with self.assertRaises(InvalidStatus) as raised: |
| 210 |
async with connect(get_uri(server)): |
| 211 |
self.fail("did not raise") |
| 212 |
self.assertEqual( |
| 213 |
str(raised.exception), |
| 214 |
"server rejected WebSocket connection: HTTP 500", |
| 215 |
) |
| 216 |
self.assertExceptionLogged(logs, "process_request failed", "BOOM") |
| 217 |
|
| 218 |
async def test_async_process_request_raises_exception(self): |
| 219 |
"""Server returns an error if async process_request raises an exception.""" |
| 220 |
|
| 221 |
async def process_request(ws, request): |
| 222 |
raise RuntimeError("BOOM") |
| 223 |
|
| 224 |
with self.assertLogs("websockets", logging.ERROR) as logs: |
| 225 |
async with serve(*args, process_request=process_request) as server: |
| 226 |
with self.assertRaises(InvalidStatus) as raised: |
| 227 |
async with connect(get_uri(server)): |
| 228 |
self.fail("did not raise") |
| 229 |
self.assertEqual( |
| 230 |
str(raised.exception), |
| 231 |
"server rejected WebSocket connection: HTTP 500", |
| 232 |
) |
| 233 |
self.assertExceptionLogged(logs, "process_request failed", "BOOM") |
| 234 |
|
| 235 |
async def test_process_response_returns_none(self): |
| 236 |
"""Server runs process_response but keeps the handshake response.""" |
| 237 |
|
| 238 |
def process_response(ws, request, response): |
| 239 |
self.assertIsInstance(request, Request) |
| 240 |
self.assertIsInstance(response, Response) |
| 241 |
ws.process_response_ran = True |
| 242 |
|
| 243 |
async with serve(*args, process_response=process_response) as server: |
| 244 |
async with connect(get_uri(server)) as client: |
| 245 |
await self.assertEval(client, "ws.process_response_ran", "True") |
| 246 |
|
| 247 |
async def test_async_process_response_returns_none(self): |
| 248 |
"""Server runs async process_response but keeps the handshake response.""" |
| 249 |
|
| 250 |
async def process_response(ws, request, response): |
| 251 |
self.assertIsInstance(request, Request) |
| 252 |
self.assertIsInstance(response, Response) |
| 253 |
ws.process_response_ran = True |
| 254 |
|
| 255 |
async with serve(*args, process_response=process_response) as server: |
| 256 |
async with connect(get_uri(server)) as client: |
| 257 |
await self.assertEval(client, "ws.process_response_ran", "True") |
| 258 |
|
| 259 |
async def test_process_response_modifies_response(self): |
| 260 |
"""Server runs process_response and modifies the handshake response.""" |
| 261 |
|
| 262 |
def process_response(ws, request, response): |
| 263 |
response.headers["X-ProcessResponse"] = "OK" |
| 264 |
|
| 265 |
async with serve(*args, process_response=process_response) as server: |
| 266 |
async with connect(get_uri(server)) as client: |
| 267 |
self.assertEqual(client.response.headers["X-ProcessResponse"], "OK") |
| 268 |
|
| 269 |
async def test_async_process_response_modifies_response(self): |
| 270 |
"""Server runs async process_response and modifies the handshake response.""" |
| 271 |
|
| 272 |
async def process_response(ws, request, response): |
| 273 |
response.headers["X-ProcessResponse"] = "OK" |
| 274 |
|
| 275 |
async with serve(*args, process_response=process_response) as server: |
| 276 |
async with connect(get_uri(server)) as client: |
| 277 |
self.assertEqual(client.response.headers["X-ProcessResponse"], "OK") |
| 278 |
|
| 279 |
async def test_process_response_replaces_response(self): |
| 280 |
"""Server runs process_response and replaces the handshake response.""" |
| 281 |
|
| 282 |
def process_response(ws, request, response): |
| 283 |
headers = response.headers.copy() |
| 284 |
headers["X-ProcessResponse"] = "OK" |
| 285 |
return dataclasses.replace(response, headers=headers) |
| 286 |
|
| 287 |
async with serve(*args, process_response=process_response) as server: |
| 288 |
async with connect(get_uri(server)) as client: |
| 289 |
self.assertEqual(client.response.headers["X-ProcessResponse"], "OK") |
| 290 |
|
| 291 |
async def test_async_process_response_replaces_response(self): |
| 292 |
"""Server runs async process_response and replaces the handshake response.""" |
| 293 |
|
| 294 |
async def process_response(ws, request, response): |
| 295 |
headers = response.headers.copy() |
| 296 |
headers["X-ProcessResponse"] = "OK" |
| 297 |
return dataclasses.replace(response, headers=headers) |
| 298 |
|
| 299 |
async with serve(*args, process_response=process_response) as server: |
| 300 |
async with connect(get_uri(server)) as client: |
| 301 |
self.assertEqual(client.response.headers["X-ProcessResponse"], "OK") |
| 302 |
|
| 303 |
async def test_process_response_raises_exception(self): |
| 304 |
"""Server returns an error if process_response raises an exception.""" |
| 305 |
|
| 306 |
def process_response(ws, request, response): |
| 307 |
raise RuntimeError("BOOM") |
| 308 |
|
| 309 |
with self.assertLogs("websockets", logging.ERROR) as logs: |
| 310 |
async with serve(*args, process_response=process_response) as server: |
| 311 |
with self.assertRaises(InvalidStatus) as raised: |
| 312 |
async with connect(get_uri(server)): |
| 313 |
self.fail("did not raise") |
| 314 |
self.assertEqual( |
| 315 |
str(raised.exception), |
| 316 |
"server rejected WebSocket connection: HTTP 500", |
| 317 |
) |
| 318 |
self.assertExceptionLogged(logs, "process_response failed", "BOOM") |
| 319 |
|
| 320 |
async def test_async_process_response_raises_exception(self): |
| 321 |
"""Server returns an error if async process_response raises an exception.""" |
| 322 |
|
| 323 |
async def process_response(ws, request, response): |
| 324 |
raise RuntimeError("BOOM") |
| 325 |
|
| 326 |
with self.assertLogs("websockets", logging.ERROR) as logs: |
| 327 |
async with serve(*args, process_response=process_response) as server: |
| 328 |
with self.assertRaises(InvalidStatus) as raised: |
| 329 |
async with connect(get_uri(server)): |
| 330 |
self.fail("did not raise") |
| 331 |
self.assertEqual( |
| 332 |
str(raised.exception), |
| 333 |
"server rejected WebSocket connection: HTTP 500", |
| 334 |
) |
| 335 |
self.assertExceptionLogged(logs, "process_response failed", "BOOM") |
| 336 |
|
| 337 |
async def test_override_server_header(self): |
| 338 |
"""Server can override Server header with server_header.""" |
| 339 |
async with serve(*args, server_header="Neo") as server: |
| 340 |
async with connect(get_uri(server)) as client: |
| 341 |
await self.assertEval(client, "ws.response.headers['Server']", "Neo") |
| 342 |
|
| 343 |
async def test_remove_server_header(self): |
| 344 |
"""Server can remove Server header with server_header.""" |
| 345 |
async with serve(*args, server_header=None) as server: |
| 346 |
async with connect(get_uri(server)) as client: |
| 347 |
await self.assertEval( |
| 348 |
client, "'Server' in ws.response.headers", "False" |
| 349 |
) |
| 350 |
|
| 351 |
async def test_keepalive_is_enabled(self): |
| 352 |
"""Server enables keepalive and measures latency.""" |
| 353 |
async with serve(*args, ping_interval=MS) as server: |
| 354 |
async with connect(get_uri(server)) as client: |
| 355 |
await client.send("ws.latency") |
| 356 |
latency = eval(await client.recv()) |
| 357 |
self.assertEqual(latency, 0) |
| 358 |
await asyncio.sleep(2 * MS) |
| 359 |
await client.send("ws.latency") |
| 360 |
latency = eval(await client.recv()) |
| 361 |
self.assertGreater(latency, 0) |
| 362 |
|
| 363 |
async def test_disable_keepalive(self): |
| 364 |
"""Server disables keepalive.""" |
| 365 |
async with serve(*args, ping_interval=None) as server: |
| 366 |
async with connect(get_uri(server)) as client: |
| 367 |
await asyncio.sleep(2 * MS) |
| 368 |
await client.send("ws.latency") |
| 369 |
latency = eval(await client.recv()) |
| 370 |
self.assertEqual(latency, 0) |
| 371 |
|
| 372 |
async def test_logger(self): |
| 373 |
"""Server accepts a logger argument.""" |
| 374 |
logger = logging.getLogger("test") |
| 375 |
async with serve(*args, logger=logger) as server: |
| 376 |
self.assertEqual(server.logger.name, logger.name) |
| 377 |
|
| 378 |
async def test_custom_connection_factory(self): |
| 379 |
"""Server runs ServerConnection factory provided in create_connection.""" |
| 380 |
|
| 381 |
def create_connection(*args, **kwargs): |
| 382 |
server = ServerConnection(*args, **kwargs) |
| 383 |
server.create_connection_ran = True |
| 384 |
return server |
| 385 |
|
| 386 |
async with serve(*args, create_connection=create_connection) as server: |
| 387 |
async with connect(get_uri(server)) as client: |
| 388 |
await self.assertEval(client, "ws.create_connection_ran", "True") |
| 389 |
|
| 390 |
async def test_connections(self): |
| 391 |
"""Server provides a connections property.""" |
| 392 |
async with serve(*args) as server: |
| 393 |
self.assertEqual(server.connections, set()) |
| 394 |
async with ( |
| 395 |
connect(get_uri(server)) as client1, |
| 396 |
connect(get_uri(server)) as client2, |
| 397 |
): |
| 398 |
await client1.send("ws.id") |
| 399 |
await client2.send("ws.id") |
| 400 |
self.assertEqual( |
| 401 |
{str(connection.id) for connection in server.connections}, |
| 402 |
{await client1.recv(), await client2.recv()}, |
| 403 |
) |
| 404 |
self.assertEqual(server.connections, set()) |
| 405 |
|
| 406 |
async def test_handshake_fails(self): |
| 407 |
"""Server receives connection from client but the handshake fails.""" |
| 408 |
|
| 409 |
def remove_key_header(self, request): |
| 410 |
del request.headers["Sec-WebSocket-Key"] |
| 411 |
|
| 412 |
async with serve(*args, process_request=remove_key_header) as server: |
| 413 |
with self.assertRaises(InvalidStatus) as raised: |
| 414 |
async with connect(get_uri(server)): |
| 415 |
self.fail("did not raise") |
| 416 |
self.assertEqual( |
| 417 |
str(raised.exception), |
| 418 |
"server rejected WebSocket connection: HTTP 400", |
| 419 |
) |
| 420 |
|
| 421 |
async def test_timeout_before_handshake_request(self): |
| 422 |
"""Server times out before receiving handshake request from client.""" |
| 423 |
with self.assertLogs("websockets", logging.DEBUG) as logs: |
| 424 |
async with serve(*args, open_timeout=MS) as server: |
| 425 |
reader, writer = await asyncio.open_connection(*get_host_port(server)) |
| 426 |
try: |
| 427 |
# Wait for the server to close the connection. |
| 428 |
self.assertEqual(await reader.read(4096), b"") |
| 429 |
finally: |
| 430 |
writer.close() |
| 431 |
|
| 432 |
self.assertExceptionLogged( |
| 433 |
logs, |
| 434 |
"! no valid HTTP request", |
| 435 |
"connection closed while reading HTTP request line", |
| 436 |
) |
| 437 |
|
| 438 |
async def test_connection_closed_before_handshake_request(self): |
| 439 |
"""Server reads EOF before receiving handshake request from client.""" |
| 440 |
with self.assertLogs("websockets", logging.DEBUG) as logs: |
| 441 |
async with serve(*args) as server: |
| 442 |
_reader, writer = await asyncio.open_connection(*get_host_port(server)) |
| 443 |
writer.close() |
| 444 |
|
| 445 |
self.assertExceptionLogged( |
| 446 |
logs, |
| 447 |
"! no valid HTTP request", |
| 448 |
"connection closed while reading HTTP request line", |
| 449 |
) |
| 450 |
|
| 451 |
async def test_connection_closed_before_handshake_response(self): |
| 452 |
"""Server reads EOF before sending handshake response to client.""" |
| 453 |
|
| 454 |
async def process_request(ws, _request): |
| 455 |
ws.transport.close() |
| 456 |
await asyncio.sleep(0) |
| 457 |
|
| 458 |
with self.assertNoLogs("websockets", logging.ERROR): |
| 459 |
async with serve(*args, process_request=process_request) as server: |
| 460 |
with self.assertRaises(InvalidHandshake): |
| 461 |
async with connect(get_uri(server)): |
| 462 |
self.fail("did not raise") |
| 463 |
|
| 464 |
async def test_junk_handshake_request(self): |
| 465 |
"""Server closes the connection when receiving non-HTTP request from client.""" |
| 466 |
with self.assertLogs("websockets", logging.DEBUG) as logs: |
| 467 |
async with serve(*args) as server: |
| 468 |
reader, writer = await asyncio.open_connection(*get_host_port(server)) |
| 469 |
writer.write(b"HELO relay.invalid\r\n") |
| 470 |
try: |
| 471 |
# Wait for the server to close the connection. |
| 472 |
self.assertEqual(await reader.read(4096), b"") |
| 473 |
finally: |
| 474 |
writer.close() |
| 475 |
|
| 476 |
self.assertExceptionLogged( |
| 477 |
logs, |
| 478 |
"! no valid HTTP request", |
| 479 |
"invalid HTTP request line: HELO relay.invalid", |
| 480 |
) |
| 481 |
|
| 482 |
async def test_close_stops_accepting_connections(self): |
| 483 |
"""Server stops accepting connections.""" |
| 484 |
async with serve(*args) as server: |
| 485 |
# Connect a client and disable close_connections to delay closing. |
| 486 |
uri = get_uri(server) |
| 487 |
async with connect(uri): |
| 488 |
server.close(close_connections=False) |
| 489 |
await asyncio.sleep(0) |
| 490 |
|
| 491 |
# Server cannot receive new connections. |
| 492 |
with self.assertRaises(OSError): |
| 493 |
async with connect(uri): |
| 494 |
self.fail("did not raise") |
| 495 |
|
| 496 |
async def test_close_rejects_connecting_connections(self): |
| 497 |
"""Server rejects connecting connections with HTTP 503.""" |
| 498 |
|
| 499 |
async def process_request(ws, _request): |
| 500 |
while ws.server.is_serving(): |
| 501 |
await asyncio.sleep(0) # pragma: no cover |
| 502 |
|
| 503 |
async with serve(*args, process_request=process_request) as server: |
| 504 |
asyncio.get_running_loop().call_later(2 * MS, server.close) |
| 505 |
with self.assertRaises(InvalidStatus) as raised: |
| 506 |
async with connect(get_uri(server)): |
| 507 |
self.fail("did not raise") |
| 508 |
self.assertEqual( |
| 509 |
str(raised.exception), |
| 510 |
"server rejected WebSocket connection: HTTP 503", |
| 511 |
) |
| 512 |
|
| 513 |
async def test_close_closes_open_connections(self): |
| 514 |
"""Server closes open connections with close code 1001.""" |
| 515 |
async with serve(*args) as server: |
| 516 |
async with connect(get_uri(server)) as client: |
| 517 |
server.close() |
| 518 |
with self.assertRaises(ConnectionClosedOK) as raised: |
| 519 |
await client.recv() |
| 520 |
self.assertEqual( |
| 521 |
str(raised.exception), |
| 522 |
"received 1001 (going away); then sent 1001 (going away)", |
| 523 |
) |
| 524 |
|
| 525 |
async def test_close_closes_open_connections_with_code_and_reason(self): |
| 526 |
"""Server closes open connections with custom code and reason.""" |
| 527 |
async with serve(*args) as server: |
| 528 |
async with connect(get_uri(server)) as client: |
| 529 |
server.close(code=1012, reason="restarting") |
| 530 |
with self.assertRaises(ConnectionClosedError) as raised: |
| 531 |
await client.recv() |
| 532 |
self.assertEqual( |
| 533 |
str(raised.exception), |
| 534 |
"received 1012 (service restart) restarting; " |
| 535 |
"then sent 1012 (service restart) restarting", |
| 536 |
) |
| 537 |
|
| 538 |
async def test_close_keeps_connections_open(self): |
| 539 |
"""Server waits for the client to close open connections.""" |
| 540 |
async with serve(*args) as server: |
| 541 |
async with connect(get_uri(server)): |
| 542 |
server.close(close_connections=False) |
| 543 |
|
| 544 |
# The server waits for the client to close the connection. |
| 545 |
with self.assertRaises(TimeoutError): |
| 546 |
async with asyncio.timeout(MS): |
| 547 |
await server.wait_closed() |
| 548 |
|
| 549 |
# Once the client closes the connection, the server terminates. |
| 550 |
async with asyncio.timeout(MS): |
| 551 |
await server.wait_closed() |
| 552 |
|
| 553 |
async def test_close_keeps_handlers_running(self): |
| 554 |
"""Server waits for connection handlers to terminate.""" |
| 555 |
async with serve(*args) as server: |
| 556 |
async with connect(get_uri(server) + "/delay") as client: |
| 557 |
# Delay termination of connection handler. |
| 558 |
await client.send(str(3 * MS)) |
| 559 |
|
| 560 |
server.close() |
| 561 |
|
| 562 |
# The server waits for the connection handler to terminate. |
| 563 |
with self.assertRaises(TimeoutError): |
| 564 |
async with asyncio.timeout(2 * MS): |
| 565 |
await server.wait_closed() |
| 566 |
|
| 567 |
# Set a longer timeout here, else the test becomes flaky. |
| 568 |
async with asyncio.timeout(5 * MS): |
| 569 |
await server.wait_closed() |
| 570 |
|
| 571 |
async def test_get_loop(self): |
| 572 |
"""Server provides a get_loop() method.""" |
| 573 |
async with serve(*args) as server: |
| 574 |
self.assertIs(server.get_loop(), asyncio.get_running_loop()) |
| 575 |
|
| 576 |
async def test_start_serving(self): |
| 577 |
"""Server starts serving when start_serving() is called.""" |
| 578 |
server = await serve(*args, start_serving=False) |
| 579 |
try: |
| 580 |
self.assertFalse(server.is_serving()) |
| 581 |
await server.start_serving() |
| 582 |
self.assertTrue(server.is_serving()) |
| 583 |
finally: |
| 584 |
server.close() |
| 585 |
await server.wait_closed() |
| 586 |
|
| 587 |
async def test_serve_forever(self): |
| 588 |
"""Server runs until canceled when serve_forever() is called.""" |
| 589 |
server = await serve(*args) |
| 590 |
try: |
| 591 |
serve_forever_task = asyncio.get_running_loop().create_task( |
| 592 |
server.serve_forever() |
| 593 |
) |
| 594 |
await asyncio.sleep(0) |
| 595 |
|
| 596 |
self.assertTrue(server.is_serving()) |
| 597 |
|
| 598 |
serve_forever_task.cancel() |
| 599 |
with self.assertRaises(asyncio.CancelledError): |
| 600 |
await serve_forever_task |
| 601 |
|
| 602 |
self.assertFalse(server.is_serving()) |
| 603 |
|
| 604 |
finally: |
| 605 |
server.close() |
| 606 |
await server.wait_closed() |
| 607 |
|
| 608 |
async def test_serve_forever_starts_serving(self): |
| 609 |
"""Server starts serving when serve_forever() is called.""" |
| 610 |
server = await serve(*args, start_serving=False) |
| 611 |
try: |
| 612 |
self.assertFalse(server.is_serving()) |
| 613 |
|
| 614 |
serve_forever_task = asyncio.get_running_loop().create_task( |
| 615 |
server.serve_forever() |
| 616 |
) |
| 617 |
await asyncio.sleep(0) |
| 618 |
|
| 619 |
self.assertTrue(server.is_serving()) |
| 620 |
|
| 621 |
serve_forever_task.cancel() |
| 622 |
with self.assertRaises(asyncio.CancelledError): |
| 623 |
await serve_forever_task |
| 624 |
|
| 625 |
finally: |
| 626 |
server.close() |
| 627 |
await server.wait_closed() |
| 628 |
|
| 629 |
async def test_canceling_serve_forever_closes_open_connections(self): |
| 630 |
"""Canceling serve_forever() closes open connections with code 1001.""" |
| 631 |
server = await serve(*args) |
| 632 |
try: |
| 633 |
serve_forever_task = asyncio.get_running_loop().create_task( |
| 634 |
server.serve_forever() |
| 635 |
) |
| 636 |
await asyncio.sleep(0) |
| 637 |
|
| 638 |
async with connect(get_uri(server)) as client: |
| 639 |
serve_forever_task.cancel() |
| 640 |
with self.assertRaises(ConnectionClosedOK) as raised: |
| 641 |
await client.recv() |
| 642 |
self.assertEqual( |
| 643 |
str(raised.exception), |
| 644 |
"received 1001 (going away); then sent 1001 (going away)", |
| 645 |
) |
| 646 |
|
| 647 |
with self.assertRaises(asyncio.CancelledError): |
| 648 |
await serve_forever_task |
| 649 |
|
| 650 |
finally: |
| 651 |
server.close() |
| 652 |
await server.wait_closed() |
| 653 |
|
| 654 |
async def test_close_exits_serve_forever(self): |
| 655 |
"""Closing the server exits serve_forever().""" |
| 656 |
server = await serve(*args) |
| 657 |
try: |
| 658 |
serve_forever_task = asyncio.get_running_loop().create_task( |
| 659 |
server.serve_forever() |
| 660 |
) |
| 661 |
await asyncio.sleep(0) |
| 662 |
server.close() |
| 663 |
|
| 664 |
async with asyncio.timeout(MS): |
| 665 |
await serve_forever_task |
| 666 |
|
| 667 |
finally: |
| 668 |
server.close() |
| 669 |
await server.wait_closed() |
| 670 |
|
| 671 |
async def test_is_serving(self): |
| 672 |
"""Server provides an is_serving() method.""" |
| 673 |
async with serve(*args) as server: |
| 674 |
self.assertTrue(server.is_serving()) |
| 675 |
self.assertFalse(server.is_serving()) |
| 676 |
|
| 677 |
async def test_wait_closed(self): |
| 678 |
"""Server provides a wait_closed() method.""" |
| 679 |
async with serve(*args) as server: |
| 680 |
wait_closed = asyncio.create_task(server.wait_closed()) |
| 681 |
await asyncio.sleep(0) |
| 682 |
self.assertFalse(wait_closed.done()) |
| 683 |
self.assertTrue(wait_closed.done()) |
| 684 |
|
| 685 |
async def test_sockets(self): |
| 686 |
"""Server provides a sockets property.""" |
| 687 |
async with serve(*args) as server: |
| 688 |
sock = server.sockets[0] |
| 689 |
self.assertIsInstance(sock.fileno(), int) |
| 690 |
self.assertEqual(server.sockets, ()) |
| 691 |
|
| 692 |
async def test_context_manager_closes_server(self): |
| 693 |
"""Server closes when exiting the asynchronous context manager.""" |
| 694 |
async with serve(handler, "localhost", 0) as server: |
| 695 |
self.assertTrue(server.is_serving()) |
| 696 |
|
| 697 |
self.assertFalse(server.is_serving()) |
| 698 |
|
| 699 |
async def test_context_manager_with_await_closes_server(self): |
| 700 |
"""Server closes when exiting the asynchronous context manager after await.""" |
| 701 |
# This is redundant, but has been historically supported. |
| 702 |
server = await serve(handler, "localhost", 0) |
| 703 |
async with server: |
| 704 |
self.assertTrue(server.is_serving()) |
| 705 |
|
| 706 |
self.assertFalse(server.is_serving()) |
| 707 |
|
| 708 |
|
| 709 |
SSL_OBJECT = "ws.transport.get_extra_info('ssl_object')" |
| 710 |
|
| 711 |
|
| 712 |
class SecureServerTests(EvalShellMixin, unittest.IsolatedAsyncioTestCase): |
| 713 |
async def test_connection(self): |
| 714 |
"""Server receives secure connection from client.""" |
| 715 |
async with serve(*args, ssl=SERVER_CONTEXT) as server: |
| 716 |
async with connect(get_uri(server), ssl=CLIENT_CONTEXT) as client: |
| 717 |
await self.assertEval(client, "ws.protocol.state.name", "OPEN") |
| 718 |
await self.assertEval(client, f"{SSL_OBJECT}.version()[:3]", "TLS") |
| 719 |
|
| 720 |
async def test_timeout_during_tls_handshake(self): |
| 721 |
"""Server times out before receiving TLS handshake request from client.""" |
| 722 |
async with serve(*args, ssl=SERVER_CONTEXT, open_timeout=MS) as server: |
| 723 |
reader, writer = await asyncio.open_connection(*get_host_port(server)) |
| 724 |
try: |
| 725 |
# Wait for the server to close the connection. |
| 726 |
self.assertEqual(await reader.read(4096), b"") |
| 727 |
finally: |
| 728 |
writer.close() |
| 729 |
|
| 730 |
async def test_connection_closed_during_tls_handshake(self): |
| 731 |
"""Server reads EOF before receiving TLS handshake request from client.""" |
| 732 |
async with serve(*args, ssl=SERVER_CONTEXT) as server: |
| 733 |
_reader, writer = await asyncio.open_connection(*get_host_port(server)) |
| 734 |
writer.close() |
| 735 |
|
| 736 |
|
| 737 |
@unittest.skipUnless(hasattr(socket, "AF_UNIX"), "this test requires Unix sockets") |
| 738 |
class UnixServerTests(EvalShellMixin, unittest.IsolatedAsyncioTestCase): |
| 739 |
async def test_connection(self): |
| 740 |
"""Server receives connection from client over a Unix socket.""" |
| 741 |
with temp_unix_socket_path() as path: |
| 742 |
async with unix_serve(handler, path): |
| 743 |
async with unix_connect(path) as client: |
| 744 |
await self.assertEval(client, "ws.protocol.state.name", "OPEN") |
| 745 |
|
| 746 |
async def test_pathlib_path(self): |
| 747 |
"""Server accepts a pathlib.Path object as the path argument.""" |
| 748 |
with temp_unix_socket_path() as path: |
| 749 |
async with unix_serve(handler, pathlib.Path(path)): |
| 750 |
async with unix_connect(path) as client: |
| 751 |
await self.assertEval(client, "ws.protocol.state.name", "OPEN") |
| 752 |
|
| 753 |
|
| 754 |
@unittest.skipUnless(hasattr(socket, "AF_UNIX"), "this test requires Unix sockets") |
| 755 |
class SecureUnixServerTests(EvalShellMixin, unittest.IsolatedAsyncioTestCase): |
| 756 |
async def test_connection(self): |
| 757 |
"""Server receives secure connection from client over a Unix socket.""" |
| 758 |
with temp_unix_socket_path() as path: |
| 759 |
async with unix_serve(handler, path, ssl=SERVER_CONTEXT): |
| 760 |
async with unix_connect(path, ssl=CLIENT_CONTEXT) as client: |
| 761 |
await self.assertEval(client, "ws.protocol.state.name", "OPEN") |
| 762 |
await self.assertEval(client, f"{SSL_OBJECT}.version()[:3]", "TLS") |
| 763 |
|
| 764 |
|
| 765 |
class ServerUsageErrorsTests(unittest.IsolatedAsyncioTestCase): |
| 766 |
async def test_host_and_sock(self): |
| 767 |
"""Server rejects host when sock is provided.""" |
| 768 |
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| 769 |
self.addCleanup(sock.close) |
| 770 |
with self.assertRaises(ValueError) as raised: |
| 771 |
await serve(handler, host="localhost", sock=sock) |
| 772 |
self.assertEqual( |
| 773 |
str(raised.exception), |
| 774 |
"host/port and sock can not be specified at the same time", |
| 775 |
) |
| 776 |
|
| 777 |
async def test_port_and_sock(self): |
| 778 |
"""Server rejects port when sock is provided.""" |
| 779 |
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| 780 |
self.addCleanup(sock.close) |
| 781 |
with self.assertRaises(ValueError) as raised: |
| 782 |
await serve(handler, port=0, sock=sock) |
| 783 |
self.assertEqual( |
| 784 |
str(raised.exception), |
| 785 |
"host/port and sock can not be specified at the same time", |
| 786 |
) |
| 787 |
|
| 788 |
async def test_unix_without_path_or_sock(self): |
| 789 |
"""Unix server requires path when sock isn't provided.""" |
| 790 |
with self.assertRaises(ValueError) as raised: |
| 791 |
await unix_serve(handler) |
| 792 |
self.assertEqual( |
| 793 |
str(raised.exception), |
| 794 |
"path was not specified, and no sock specified", |
| 795 |
) |
| 796 |
|
| 797 |
async def test_unix_with_path_and_sock(self): |
| 798 |
"""Unix server rejects path when sock is provided.""" |
| 799 |
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| 800 |
self.addCleanup(sock.close) |
| 801 |
with self.assertRaises(ValueError) as raised: |
| 802 |
await unix_serve(handler, path="/", sock=sock) |
| 803 |
self.assertEqual( |
| 804 |
str(raised.exception), |
| 805 |
"path and sock can not be specified at the same time", |
| 806 |
) |
| 807 |
|
| 808 |
async def test_invalid_subprotocol(self): |
| 809 |
"""Server rejects single value of subprotocols.""" |
| 810 |
with self.assertRaises(TypeError) as raised: |
| 811 |
await serve(*args, subprotocols="chat") |
| 812 |
self.assertEqual( |
| 813 |
str(raised.exception), |
| 814 |
"subprotocols must be a list, not a str", |
| 815 |
) |
| 816 |
|
| 817 |
async def test_unsupported_compression(self): |
| 818 |
"""Server rejects incorrect value of compression.""" |
| 819 |
with self.assertRaises(ValueError) as raised: |
| 820 |
await serve(*args, compression=False) |
| 821 |
self.assertEqual( |
| 822 |
str(raised.exception), |
| 823 |
"unsupported compression: False", |
| 824 |
) |
| 825 |
|
| 826 |
|
| 827 |
class BasicAuthTests(EvalShellMixin, unittest.IsolatedAsyncioTestCase): |
| 828 |
async def test_valid_authorization(self): |
| 829 |
"""basic_auth authenticates client with HTTP Basic Authentication.""" |
| 830 |
async with serve( |
| 831 |
*args, |
| 832 |
process_request=basic_auth(credentials=("hello", "iloveyou")), |
| 833 |
) as server: |
| 834 |
async with connect( |
| 835 |
get_uri(server), |
| 836 |
additional_headers={"Authorization": "Basic aGVsbG86aWxvdmV5b3U="}, |
| 837 |
) as client: |
| 838 |
await self.assertEval(client, "ws.username", "hello") |
| 839 |
|
| 840 |
async def test_missing_authorization(self): |
| 841 |
"""basic_auth rejects client without credentials.""" |
| 842 |
async with serve( |
| 843 |
*args, |
| 844 |
process_request=basic_auth(credentials=("hello", "iloveyou")), |
| 845 |
) as server: |
| 846 |
with self.assertRaises(InvalidStatus) as raised: |
| 847 |
async with connect(get_uri(server)): |
| 848 |
self.fail("did not raise") |
| 849 |
self.assertEqual( |
| 850 |
str(raised.exception), |
| 851 |
"server rejected WebSocket connection: HTTP 401", |
| 852 |
) |
| 853 |
|
| 854 |
async def test_unsupported_authorization(self): |
| 855 |
"""basic_auth rejects client with unsupported credentials.""" |
| 856 |
async with serve( |
| 857 |
*args, |
| 858 |
process_request=basic_auth(credentials=("hello", "iloveyou")), |
| 859 |
) as server: |
| 860 |
with self.assertRaises(InvalidStatus) as raised: |
| 861 |
async with connect( |
| 862 |
get_uri(server), |
| 863 |
additional_headers={"Authorization": "Negotiate ..."}, |
| 864 |
): |
| 865 |
self.fail("did not raise") |
| 866 |
self.assertEqual( |
| 867 |
str(raised.exception), |
| 868 |
"server rejected WebSocket connection: HTTP 401", |
| 869 |
) |
| 870 |
|
| 871 |
async def test_authorization_with_unknown_username(self): |
| 872 |
"""basic_auth rejects client with unknown username.""" |
| 873 |
async with serve( |
| 874 |
*args, |
| 875 |
process_request=basic_auth(credentials=("hello", "iloveyou")), |
| 876 |
) as server: |
| 877 |
with self.assertRaises(InvalidStatus) as raised: |
| 878 |
async with connect( |
| 879 |
get_uri(server), |
| 880 |
additional_headers={"Authorization": "Basic YnllOnlvdWxvdmVtZQ=="}, |
| 881 |
): |
| 882 |
self.fail("did not raise") |
| 883 |
self.assertEqual( |
| 884 |
str(raised.exception), |
| 885 |
"server rejected WebSocket connection: HTTP 401", |
| 886 |
) |
| 887 |
|
| 888 |
async def test_authorization_with_incorrect_password(self): |
| 889 |
"""basic_auth rejects client with incorrect password.""" |
| 890 |
async with serve( |
| 891 |
*args, |
| 892 |
process_request=basic_auth(credentials=("hello", "changeme")), |
| 893 |
) as server: |
| 894 |
with self.assertRaises(InvalidStatus) as raised: |
| 895 |
async with connect( |
| 896 |
get_uri(server), |
| 897 |
additional_headers={"Authorization": "Basic aGVsbG86aWxvdmV5b3U="}, |
| 898 |
): |
| 899 |
self.fail("did not raise") |
| 900 |
self.assertEqual( |
| 901 |
str(raised.exception), |
| 902 |
"server rejected WebSocket connection: HTTP 401", |
| 903 |
) |
| 904 |
|
| 905 |
async def test_list_of_credentials(self): |
| 906 |
"""basic_auth accepts a list of hard coded credentials.""" |
| 907 |
async with serve( |
| 908 |
*args, |
| 909 |
process_request=basic_auth( |
| 910 |
credentials=[ |
| 911 |
("hello", "iloveyou"), |
| 912 |
("bye", "youloveme"), |
| 913 |
] |
| 914 |
), |
| 915 |
) as server: |
| 916 |
async with connect( |
| 917 |
get_uri(server), |
| 918 |
additional_headers={"Authorization": "Basic YnllOnlvdWxvdmVtZQ=="}, |
| 919 |
) as client: |
| 920 |
await self.assertEval(client, "ws.username", "bye") |
| 921 |
|
| 922 |
async def test_check_credentials_function(self): |
| 923 |
"""basic_auth accepts a check_credentials function.""" |
| 924 |
|
| 925 |
def check_credentials(username, password): |
| 926 |
self.assertEqual(username, "hello") |
| 927 |
return hmac.compare_digest(password, "iloveyou") |
| 928 |
|
| 929 |
async with serve( |
| 930 |
*args, |
| 931 |
process_request=basic_auth(check_credentials=check_credentials), |
| 932 |
) as server: |
| 933 |
async with connect( |
| 934 |
get_uri(server), |
| 935 |
additional_headers={"Authorization": "Basic aGVsbG86aWxvdmV5b3U="}, |
| 936 |
) as client: |
| 937 |
await self.assertEval(client, "ws.username", "hello") |
| 938 |
|
| 939 |
async def test_check_credentials_coroutine(self): |
| 940 |
"""basic_auth accepts a check_credentials coroutine.""" |
| 941 |
|
| 942 |
async def check_credentials(username, password): |
| 943 |
self.assertEqual(username, "hello") |
| 944 |
return hmac.compare_digest(password, "iloveyou") |
| 945 |
|
| 946 |
async with serve( |
| 947 |
*args, |
| 948 |
process_request=basic_auth(check_credentials=check_credentials), |
| 949 |
) as server: |
| 950 |
async with connect( |
| 951 |
get_uri(server), |
| 952 |
additional_headers={"Authorization": "Basic aGVsbG86aWxvdmV5b3U="}, |
| 953 |
) as client: |
| 954 |
await self.assertEval(client, "ws.username", "hello") |
| 955 |
|
| 956 |
async def test_without_credentials_or_check_credentials(self): |
| 957 |
"""basic_auth requires either credentials or check_credentials.""" |
| 958 |
with self.assertRaises(ValueError) as raised: |
| 959 |
basic_auth() |
| 960 |
self.assertEqual( |
| 961 |
str(raised.exception), |
| 962 |
"provide either credentials or check_credentials", |
| 963 |
) |
| 964 |
|
| 965 |
async def test_with_credentials_and_check_credentials(self): |
| 966 |
"""basic_auth requires only one of credentials and check_credentials.""" |
| 967 |
with self.assertRaises(ValueError) as raised: |
| 968 |
basic_auth( |
| 969 |
credentials=("hello", "iloveyou"), |
| 970 |
check_credentials=lambda: False, # pragma: no cover |
| 971 |
) |
| 972 |
self.assertEqual( |
| 973 |
str(raised.exception), |
| 974 |
"provide either credentials or check_credentials", |
| 975 |
) |
| 976 |
|
| 977 |
async def test_bad_credentials(self): |
| 978 |
"""basic_auth receives an unsupported credentials argument.""" |
| 979 |
with self.assertRaises(TypeError) as raised: |
| 980 |
basic_auth(credentials=42) |
| 981 |
self.assertEqual( |
| 982 |
str(raised.exception), |
| 983 |
"invalid credentials argument: 42", |
| 984 |
) |
| 985 |
|
| 986 |
async def test_bad_list_of_credentials(self): |
| 987 |
"""basic_auth receives an unsupported credentials argument.""" |
| 988 |
with self.assertRaises(TypeError) as raised: |
| 989 |
basic_auth(credentials=[42]) |
| 990 |
self.assertEqual( |
| 991 |
str(raised.exception), |
| 992 |
"invalid credentials argument: [42]", |
| 993 |
) |