| 1 |
|
| 2 |
from __future__ import annotations |
| 3 |
|
| 4 |
import asyncio |
| 5 |
import json |
| 6 |
from contextlib import nullcontext as does_not_raise |
| 7 |
from unittest.mock import AsyncMock, MagicMock, patch |
| 8 |
|
| 9 |
import aiohttp |
| 10 |
import pytest |
| 11 |
import yarl |
| 12 |
|
| 13 |
from nice_go import WebSocketError |
| 14 |
from nice_go._exceptions import ReconnectWebSocketError |
| 15 |
from nice_go._ws_client import EventListener, WebSocketClient |
| 16 |
|
| 17 |
|
| 18 |
async def test_ws_connect(mock_ws_client: WebSocketClient) -> None: |
| 19 |
assert mock_ws_client.ws is not None |
| 20 |
assert isinstance(mock_ws_client.ws, AsyncMock) |
| 21 |
mock_session = MagicMock() |
| 22 |
mock_session.ws_connect = AsyncMock() |
| 23 |
mock_session.ws_connect.return_value = AsyncMock(closed=False) |
| 24 |
mock_session.ws_connect.return_value.receive = AsyncMock() |
| 25 |
mock_session.ws_connect.return_value.receive.return_value = MagicMock( |
| 26 |
data=json.dumps({"type": "connection_ack"}), |
| 27 |
) |
| 28 |
mock_ws_client.client_session = mock_session |
| 29 |
mock_ws_client._dispatch = MagicMock() |
| 30 |
await mock_ws_client.connect( |
| 31 |
"test_token", |
| 32 |
yarl.URL("wss://test_endpoint"), |
| 33 |
"events", |
| 34 |
MagicMock(), |
| 35 |
"test_host", |
| 36 |
) |
| 37 |
mock_session.ws_connect.assert_called_once() |
| 38 |
mock_ws_client._dispatch.assert_called_once() |
| 39 |
mock_ws_client.ws.receive.assert_called_once() |
| 40 |
mock_ws_client.ws.send_json.assert_called_once() |
| 41 |
|
| 42 |
|
| 43 |
async def test_ws_init_unexpected_type(mock_ws_client: WebSocketClient) -> None: |
| 44 |
assert mock_ws_client.ws is not None |
| 45 |
assert isinstance(mock_ws_client.ws, AsyncMock) |
| 46 |
mock_ws_client.ws.receive = AsyncMock() |
| 47 |
mock_ws_client.ws.receive.return_value = MagicMock( |
| 48 |
data=json.dumps({"type": "unexpected_type"}), |
| 49 |
) |
| 50 |
with pytest.raises(WebSocketError): |
| 51 |
await mock_ws_client.init() |
| 52 |
|
| 53 |
|
| 54 |
async def test_ws_init_timeout(mock_ws_client: WebSocketClient) -> None: |
| 55 |
assert mock_ws_client.ws is not None |
| 56 |
assert isinstance(mock_ws_client.ws, AsyncMock) |
| 57 |
mock_ws_client.ws.receive = AsyncMock() |
| 58 |
mock_ws_client.ws.receive.side_effect = asyncio.TimeoutError |
| 59 |
with pytest.raises(WebSocketError): |
| 60 |
await mock_ws_client.init() |
| 61 |
|
| 62 |
|
| 63 |
async def test_ws_send_json(mock_ws_client: WebSocketClient) -> None: |
| 64 |
assert mock_ws_client.ws is not None |
| 65 |
assert isinstance(mock_ws_client.ws, AsyncMock) |
| 66 |
mock_ws_client.ws.send_json = AsyncMock() |
| 67 |
await mock_ws_client.send({"type": "test_type"}) |
| 68 |
mock_ws_client.ws.send_json.assert_called_once() |
| 69 |
|
| 70 |
|
| 71 |
async def test_ws_send_str(mock_ws_client: WebSocketClient) -> None: |
| 72 |
assert mock_ws_client.ws is not None |
| 73 |
assert isinstance(mock_ws_client.ws, AsyncMock) |
| 74 |
mock_ws_client.ws.send_str = AsyncMock() |
| 75 |
await mock_ws_client.send("test_message") |
| 76 |
mock_ws_client.ws.send_str.assert_called_once() |
| 77 |
|
| 78 |
|
| 79 |
async def test_ws_subscribe_and_close(mock_ws_client: WebSocketClient) -> None: |
| 80 |
assert mock_ws_client.ws is not None |
| 81 |
assert isinstance(mock_ws_client.ws, AsyncMock) |
| 82 |
|
| 83 |
mock_ws_client.ws.send_json = AsyncMock() |
| 84 |
mock_ws_client.ws.close = AsyncMock() |
| 85 |
mock_ws_client.ws.receive = AsyncMock() |
| 86 |
|
| 87 |
subscription_id = "test_id" |
| 88 |
mock_ws_client.ws.receive.return_value = MagicMock( |
| 89 |
data=json.dumps({"id": subscription_id, "type": "start_ack"}), |
| 90 |
type=aiohttp.WSMsgType.TEXT, |
| 91 |
) |
| 92 |
|
| 93 |
mock_ws_client.api_type = "events" |
| 94 |
|
| 95 |
with patch("nice_go._ws_client.uuid.uuid4") as mock_uuid: |
| 96 |
mock_uuid.return_value = subscription_id |
| 97 |
subscribe_task = asyncio.create_task(mock_ws_client.subscribe("test_query")) |
| 98 |
await asyncio.sleep(0.1) |
| 99 |
mock_ws_client.ws.send_json.assert_called_once() |
| 100 |
await mock_ws_client.poll() |
| 101 |
await subscribe_task |
| 102 |
mock_ws_client._timeout_task = MagicMock(cancel=MagicMock()) |
| 103 |
await mock_ws_client.close() |
| 104 |
call_count_should_be = 2 |
| 105 |
assert mock_ws_client.ws.send_json.call_count == call_count_should_be |
| 106 |
mock_ws_client.ws.close.assert_called_once() |
| 107 |
|
| 108 |
|
| 109 |
@pytest.mark.parametrize( |
| 110 |
"msg_type", |
| 111 |
[ |
| 112 |
aiohttp.WSMsgType.ERROR, |
| 113 |
aiohttp.WSMsgType.CLOSE, |
| 114 |
aiohttp.WSMsgType.CLOSING, |
| 115 |
aiohttp.WSMsgType.CLOSED, |
| 116 |
], |
| 117 |
) |
| 118 |
async def test_ws_poll_errors( |
| 119 |
mock_ws_client: WebSocketClient, |
| 120 |
msg_type: aiohttp.WSMsgType, |
| 121 |
) -> None: |
| 122 |
assert mock_ws_client.ws is not None |
| 123 |
assert isinstance(mock_ws_client.ws, AsyncMock) |
| 124 |
mock_ws_client.ws.receive = AsyncMock() |
| 125 |
mock_ws_client.ws.receive.return_value = MagicMock(type=msg_type) |
| 126 |
mock_ws_client._timeout_task = MagicMock() |
| 127 |
with pytest.raises(WebSocketError): |
| 128 |
await mock_ws_client.poll() |
| 129 |
|
| 130 |
|
| 131 |
async def test_ws_received_message(mock_ws_client: WebSocketClient) -> None: |
| 132 |
mock_ws_client._dispatch = MagicMock() |
| 133 |
mock_ws_client.api_type = "device" |
| 134 |
await mock_ws_client.received_message( |
| 135 |
json.dumps({"type": "data", "payload": "test_payload"}), |
| 136 |
) |
| 137 |
mock_ws_client._dispatch.assert_called_once() |
| 138 |
|
| 139 |
with pytest.raises(WebSocketError): |
| 140 |
await mock_ws_client.received_message(json.dumps({"type": "error"})) |
| 141 |
|
| 142 |
with pytest.raises(WebSocketError): |
| 143 |
await mock_ws_client.received_message("invalid_json") |
| 144 |
|
| 145 |
mock_ws_client._timeout_task = MagicMock(done=MagicMock(return_value=False)) |
| 146 |
mock_ws_client._timeout_task.cancel = MagicMock() |
| 147 |
mock_ws_client._watch_keepalive = MagicMock() |
| 148 |
|
| 149 |
with patch("nice_go._ws_client.asyncio.create_task") as mock_create_task: |
| 150 |
await mock_ws_client.received_message(json.dumps({"type": "ka"})) |
| 151 |
mock_create_task.assert_called_once() |
| 152 |
|
| 153 |
|
| 154 |
async def test_ws_received_message_dispatch_listener_skip_type( |
| 155 |
mock_ws_client: WebSocketClient, |
| 156 |
) -> None: |
| 157 |
mock_ws_client._dispatch_listeners = [ |
| 158 |
EventListener( |
| 159 |
predicate=AsyncMock(return_value=True), |
| 160 |
event="wrong_type", |
| 161 |
future=MagicMock(), |
| 162 |
result=MagicMock(), |
| 163 |
), |
| 164 |
] |
| 165 |
mock_ws_client.api_type = "device" |
| 166 |
await mock_ws_client.received_message( |
| 167 |
json.dumps({"type": "data", "payload": "test_payload"}), |
| 168 |
) |
| 169 |
assert len(mock_ws_client._dispatch_listeners) == 1 |
| 170 |
|
| 171 |
|
| 172 |
async def test_ws_received_message_dispatch_listener_cancelled( |
| 173 |
mock_ws_client: WebSocketClient, |
| 174 |
) -> None: |
| 175 |
mock_ws_client._dispatch_listeners = [ |
| 176 |
EventListener( |
| 177 |
predicate=AsyncMock(return_value=True), |
| 178 |
event="data", |
| 179 |
future=MagicMock(cancelled=MagicMock(return_value=True)), |
| 180 |
result=MagicMock(), |
| 181 |
), |
| 182 |
] |
| 183 |
mock_ws_client.api_type = "device" |
| 184 |
await mock_ws_client.received_message( |
| 185 |
json.dumps({"type": "data", "payload": "test_payload"}), |
| 186 |
) |
| 187 |
assert not mock_ws_client._dispatch_listeners |
| 188 |
|
| 189 |
|
| 190 |
async def test_ws_received_message_dispatch_listener_predicate_exception( |
| 191 |
mock_ws_client: WebSocketClient, |
| 192 |
) -> None: |
| 193 |
mock_ws_client._dispatch_listeners = [ |
| 194 |
EventListener( |
| 195 |
predicate=MagicMock(side_effect=Exception), |
| 196 |
event="data", |
| 197 |
future=MagicMock(cancelled=MagicMock(return_value=False)), |
| 198 |
result=MagicMock(), |
| 199 |
), |
| 200 |
] |
| 201 |
mock_ws_client.api_type = "device" |
| 202 |
await mock_ws_client.received_message( |
| 203 |
json.dumps({"type": "data", "payload": "test_payload"}), |
| 204 |
) |
| 205 |
assert not mock_ws_client._dispatch_listeners |
| 206 |
|
| 207 |
|
| 208 |
async def test_subscribe_timeout(mock_ws_client: WebSocketClient) -> None: |
| 209 |
with patch("nice_go._ws_client.asyncio.wait_for") as mock_wait_for: |
| 210 |
mock_wait_for.side_effect = asyncio.TimeoutError |
| 211 |
mock_ws_client.api_type = "events" |
| 212 |
with pytest.raises(WebSocketError): |
| 213 |
await mock_ws_client.subscribe("test_query") |
| 214 |
|
| 215 |
|
| 216 |
async def test_unsubscribe(mock_ws_client: WebSocketClient) -> None: |
| 217 |
mock_ws_client._subscriptions = ["test_id"] |
| 218 |
assert mock_ws_client.ws is not None |
| 219 |
assert isinstance(mock_ws_client.ws, AsyncMock) |
| 220 |
mock_ws_client.ws.send_json = AsyncMock() |
| 221 |
await mock_ws_client.unsubscribe("test_id") |
| 222 |
mock_ws_client.ws.send_json.assert_called_once() |
| 223 |
assert "test_id" not in mock_ws_client._subscriptions |
| 224 |
assert mock_ws_client.ws.send_json.call_args[0][0] == { |
| 225 |
"id": "test_id", |
| 226 |
"type": "stop", |
| 227 |
} |
| 228 |
|
| 229 |
|
| 230 |
async def test_closed_property(mock_ws_client: WebSocketClient) -> None: |
| 231 |
assert not mock_ws_client.closed |
| 232 |
mock_ws_client.ws = MagicMock() |
| 233 |
mock_ws_client.ws.closed = True |
| 234 |
assert mock_ws_client.closed |
| 235 |
|
| 236 |
|
| 237 |
async def test_connect_no_host(mock_ws_client: WebSocketClient) -> None: |
| 238 |
with pytest.raises(ValueError, match="host must be provided"): |
| 239 |
await mock_ws_client.connect( |
| 240 |
"test_token", |
| 241 |
yarl.URL("wss://test_endpoint"), |
| 242 |
"events", |
| 243 |
MagicMock(), |
| 244 |
None, |
| 245 |
) |
| 246 |
|
| 247 |
|
| 248 |
@pytest.mark.parametrize( |
| 249 |
("method", "args"), |
| 250 |
[ |
| 251 |
("init", ()), |
| 252 |
("send", ({"type": "test_type"},)), |
| 253 |
("poll", ()), |
| 254 |
], |
| 255 |
) |
| 256 |
async def test_closed_error( |
| 257 |
mock_ws_client: WebSocketClient, |
| 258 |
method: str, |
| 259 |
args: tuple[dict[str, str] | None], |
| 260 |
) -> None: |
| 261 |
mock_ws_client.ws = None |
| 262 |
with pytest.raises(WebSocketError, match="WebSocket connection is closed"): |
| 263 |
await getattr(mock_ws_client, method)(*args) |
| 264 |
|
| 265 |
|
| 266 |
async def test_close_already_closed( |
| 267 |
mock_ws_client: WebSocketClient, |
| 268 |
) -> None: |
| 269 |
mock_ws_client.ws = MagicMock() |
| 270 |
mock_ws_client.ws.closed = True |
| 271 |
await mock_ws_client.close() |
| 272 |
assert mock_ws_client.ws.close.call_count == 0 |
| 273 |
|
| 274 |
|
| 275 |
async def test_received_message_no_predicate( |
| 276 |
mock_ws_client: WebSocketClient, |
| 277 |
) -> None: |
| 278 |
mock_ws_client._dispatch_listeners = [ |
| 279 |
EventListener( |
| 280 |
predicate=None, |
| 281 |
event="data", |
| 282 |
future=MagicMock(cancelled=MagicMock(return_value=False)), |
| 283 |
result=MagicMock(), |
| 284 |
), |
| 285 |
] |
| 286 |
mock_ws_client.api_type = "device" |
| 287 |
await mock_ws_client.received_message( |
| 288 |
json.dumps({"type": "data", "payload": "test_payload"}), |
| 289 |
) |
| 290 |
assert not mock_ws_client._dispatch_listeners |
| 291 |
|
| 292 |
|
| 293 |
async def test_received_message_type_or_payload_missing( |
| 294 |
mock_ws_client: WebSocketClient, |
| 295 |
) -> None: |
| 296 |
with pytest.raises(WebSocketError): |
| 297 |
await mock_ws_client.received_message(json.dumps({"payload": "test_payload"})) |
| 298 |
|
| 299 |
|
| 300 |
async def test_barrier_obstructed(mock_ws_client: WebSocketClient) -> None: |
| 301 |
mock_ws_client.api_type = "events" |
| 302 |
mock_ws_client._dispatch = MagicMock() |
| 303 |
mock_ws_client.dispatch_message( |
| 304 |
{ |
| 305 |
"type": "data", |
| 306 |
"payload": { |
| 307 |
"data": { |
| 308 |
"eventsFeed": { |
| 309 |
"item": { |
| 310 |
"eventId": "event-error-barrier-obstructed", |
| 311 |
}, |
| 312 |
}, |
| 313 |
}, |
| 314 |
}, |
| 315 |
}, |
| 316 |
) |
| 317 |
assert mock_ws_client._dispatch.call_count == 1 |
| 318 |
|
| 319 |
|
| 320 |
async def test_event_not_barrier_obstructed(mock_ws_client: WebSocketClient) -> None: |
| 321 |
mock_ws_client.api_type = "events" |
| 322 |
mock_ws_client._dispatch = MagicMock() |
| 323 |
mock_ws_client.dispatch_message( |
| 324 |
{ |
| 325 |
"type": "data", |
| 326 |
"payload": { |
| 327 |
"data": { |
| 328 |
"eventsFeed": { |
| 329 |
"item": { |
| 330 |
"eventId": "event-user-barrier-opened", |
| 331 |
}, |
| 332 |
}, |
| 333 |
}, |
| 334 |
}, |
| 335 |
}, |
| 336 |
) |
| 337 |
assert mock_ws_client._dispatch.call_count == 0 |
| 338 |
|
| 339 |
|
| 340 |
async def test_unsubscribe_nonexistent_subscription( |
| 341 |
mock_ws_client: WebSocketClient, |
| 342 |
) -> None: |
| 343 |
mock_ws_client._subscriptions = [] |
| 344 |
mock_ws_client.client_session = MagicMock(send_json=AsyncMock()) |
| 345 |
await mock_ws_client.unsubscribe("test_id") |
| 346 |
|
| 347 |
assert mock_ws_client.client_session.send_json.call_count == 0 |
| 348 |
|
| 349 |
|
| 350 |
async def test_watch_keepalive( |
| 351 |
mock_ws_client: WebSocketClient, |
| 352 |
) -> None: |
| 353 |
mock_ws_client.ws = MagicMock(closed=False) |
| 354 |
mock_ws_client.ws.send_json = AsyncMock() |
| 355 |
mock_ws_client.ws.receive = AsyncMock() |
| 356 |
mock_ws_client.ws.receive.return_value = MagicMock( |
| 357 |
data=json.dumps({"type": "ka"}), |
| 358 |
type=aiohttp.WSMsgType.TEXT, |
| 359 |
) |
| 360 |
mock_ws_client.ws.close = AsyncMock() |
| 361 |
mock_ws_client._timeout = 0.1 |
| 362 |
mock_ws_client._timeout_task = MagicMock(cancel=MagicMock()) |
| 363 |
|
| 364 |
with pytest.raises(ReconnectWebSocketError): |
| 365 |
await mock_ws_client._watch_keepalive() |
| 366 |
|
| 367 |
mock_ws_client.ws.close.assert_called_once() |
| 368 |
|
| 369 |
|
| 370 |
async def test_watch_keepalive_no_ws( |
| 371 |
mock_ws_client: WebSocketClient, |
| 372 |
) -> None: |
| 373 |
mock_ws_client.ws = None |
| 374 |
with pytest.raises(WebSocketError, match="WebSocket connection is closed"): |
| 375 |
await mock_ws_client._watch_keepalive() |
| 376 |
|
| 377 |
|
| 378 |
async def test_reconnect_no_ws( |
| 379 |
mock_ws_client: WebSocketClient, |
| 380 |
) -> None: |
| 381 |
mock_ws_client.ws = None |
| 382 |
with pytest.raises(WebSocketError, match="WebSocket connection is closed"): |
| 383 |
await mock_ws_client._reconnect() |
| 384 |
|
| 385 |
|
| 386 |
async def test_close_timeout_task_cancelled( |
| 387 |
mock_ws_client: WebSocketClient, |
| 388 |
) -> None: |
| 389 |
mock_ws_client._timeout_task = asyncio.create_task(asyncio.sleep(0)) |
| 390 |
mock_ws_client._timeout_task.cancel() |
| 391 |
|
| 392 |
assert mock_ws_client.ws is not None |
| 393 |
assert not mock_ws_client.ws.closed |
| 394 |
|
| 395 |
assert not mock_ws_client._timeout_task.done() |
| 396 |
|
| 397 |
await mock_ws_client.close() |
| 398 |
|
| 399 |
|
| 400 |
async def test_poll_timeout_task_cancelled( |
| 401 |
mock_ws_client: WebSocketClient, |
| 402 |
) -> None: |
| 403 |
mock_ws_client._timeout_task = asyncio.create_task(asyncio.sleep(0)) |
| 404 |
mock_ws_client._timeout_task.cancel() |
| 405 |
|
| 406 |
assert mock_ws_client.ws is not None |
| 407 |
assert not mock_ws_client.ws.closed |
| 408 |
|
| 409 |
assert not mock_ws_client._timeout_task.done() |
| 410 |
|
| 411 |
mock_ws_client.ws = MagicMock(closed=False) |
| 412 |
mock_ws_client.ws.receive = AsyncMock( |
| 413 |
return_value=MagicMock( |
| 414 |
type=aiohttp.WSMsgType.CLOSED, |
| 415 |
), |
| 416 |
) |
| 417 |
|
| 418 |
with pytest.raises(WebSocketError): |
| 419 |
await mock_ws_client.poll() |
| 420 |
|
| 421 |
|
| 422 |
async def test_poll_ws_closed_reconnecting( |
| 423 |
mock_ws_client: WebSocketClient, |
| 424 |
) -> None: |
| 425 |
mock_ws_client.reconnecting = True |
| 426 |
mock_ws_client.ws = MagicMock( |
| 427 |
receive=AsyncMock( |
| 428 |
return_value=MagicMock( |
| 429 |
type=aiohttp.WSMsgType.CLOSED, |
| 430 |
), |
| 431 |
), |
| 432 |
closed=False, |
| 433 |
) |
| 434 |
with does_not_raise(): |
| 435 |
await mock_ws_client.poll() |
| 436 |
|
| 437 |
|
| 438 |
async def test_close_timeout_task_exception( |
| 439 |
mock_ws_client: WebSocketClient, |
| 440 |
) -> None: |
| 441 |
mock_timeout_task = MagicMock() |
| 442 |
mock_timeout_task.done.return_value = False |
| 443 |
mock_timeout_task.cancel = MagicMock() |
| 444 |
mock_timeout_task.__await__ = MagicMock(side_effect=Exception("Test exception")) |
| 445 |
|
| 446 |
mock_ws_client._timeout_task = mock_timeout_task |
| 447 |
|
| 448 |
with patch("nice_go._ws_client._LOGGER") as mock_logger: |
| 449 |
await mock_ws_client.close() |
| 450 |
|
| 451 |
mock_timeout_task.cancel.assert_called_once() |
| 452 |
mock_timeout_task.done.assert_called_once() |
| 453 |
mock_logger.debug.assert_any_call("Cancelling keepalive task") |
| 454 |
mock_logger.exception.assert_called_once_with( |
| 455 |
"Exception occurred while cancelling keepalive task", |
| 456 |
) |