|
| 1 | +import asyncio |
| 2 | +import json |
| 3 | +from unittest.mock import MagicMock |
| 4 | + |
| 5 | +from jupyter_client.jsonutil import json_clean, json_default |
| 6 | +from jupyter_client.session import Session |
| 7 | +from tornado.httpserver import HTTPRequest |
| 8 | +from tornado.websocket import WebSocketHandler |
| 9 | + |
| 10 | +from jupyter_server.serverapp import ServerApp |
| 11 | +from jupyter_server.services.kernels.connection.channels import ( |
| 12 | + ZMQChannelsWebsocketConnection, |
| 13 | +) |
| 14 | + |
| 15 | + |
| 16 | +async def test_websocket_connection(jp_serverapp): |
| 17 | + app: ServerApp = jp_serverapp |
| 18 | + kernel_id = await app.kernel_manager.start_kernel() |
| 19 | + kernel = app.kernel_manager.get_kernel(kernel_id) |
| 20 | + request = HTTPRequest("foo", "GET") |
| 21 | + request.connection = MagicMock() |
| 22 | + handler = WebSocketHandler(app.web_app, request) |
| 23 | + handler.ws_connection = MagicMock() |
| 24 | + handler.ws_connection.is_closing = lambda: False |
| 25 | + conn = ZMQChannelsWebsocketConnection(parent=kernel, websocket_handler=handler) |
| 26 | + await conn.prepare() |
| 27 | + conn.connect() |
| 28 | + await asyncio.wrap_future(conn.nudge()) |
| 29 | + session: Session = kernel.session |
| 30 | + msg = session.msg("data_pub", content={"a": "b"}) |
| 31 | + data = json.dumps( |
| 32 | + json_clean(msg), |
| 33 | + default=json_default, |
| 34 | + ensure_ascii=False, |
| 35 | + allow_nan=False, |
| 36 | + ) |
| 37 | + conn.handle_incoming_message(data) |
| 38 | + conn.handle_outgoing_message("iopub", session.serialize(msg)) |
| 39 | + assert ( |
| 40 | + conn.select_subprotocol(["v1.kernel.websocket.jupyter.org"]) |
| 41 | + == "v1.kernel.websocket.jupyter.org" |
| 42 | + ) |
| 43 | + conn.write_stderr("test", {}) |
| 44 | + conn.on_kernel_restarted() |
| 45 | + conn.on_restart_failed() |
| 46 | + conn._on_error("shell", msg, session.serialize(msg)) |
0 commit comments