Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions hyperliquid/websocket_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ def subscription_to_identifier(subscription: Subscription) -> str:
def ws_msg_to_identifier(ws_msg: WsMsg) -> Optional[str]:
if ws_msg["channel"] == "pong":
return "pong"
elif ws_msg["channel"] == "error":
return "error"
elif ws_msg["channel"] == "allMids":
return "allMids"
elif ws_msg["channel"] == "l2Book":
Expand Down Expand Up @@ -114,6 +116,9 @@ def on_message(self, _ws, message):
if identifier == "pong":
logging.debug("Websocket received pong")
return
if identifier == "error":
logging.warning(f"Websocket received error message: {message}")
return
if identifier is None:
logging.debug("Websocket not handling empty message")
return
Expand Down
39 changes: 39 additions & 0 deletions tests/websocket_manager_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import json
import logging
from collections import defaultdict
from unittest.mock import MagicMock

import pytest

from hyperliquid.websocket_manager import WebsocketManager, ws_msg_to_identifier

ERROR_MESSAGE = json.dumps({"channel": "error", "data": {"error": "Invalid subscription: unknown coin"}})


def make_manager():
manager = object.__new__(WebsocketManager)
manager.active_subscriptions = defaultdict(list)
return manager


def test_ws_msg_to_identifier_error_channel():
ws_msg = {"channel": "error", "data": {"error": "Invalid subscription: unknown coin"}}
assert ws_msg_to_identifier(ws_msg) == "error"


def test_error_channel_message_logs_warning(caplog):
manager = make_manager()
with caplog.at_level(logging.WARNING):
manager.on_message(None, ERROR_MESSAGE)
warnings = [record for record in caplog.records if record.levelno == logging.WARNING]
assert len(warnings) == 1
assert "Invalid subscription" in warnings[0].getMessage()


def test_error_channel_message_not_routed_to_subscriptions(capsys):
manager = make_manager()
callback = MagicMock()
manager.active_subscriptions["allMids"].append(callback)
manager.on_message(None, ERROR_MESSAGE)
callback.assert_not_called()
assert "unexpected subscription" not in capsys.readouterr().out