From b14a45c34a84062e1643dbdc763de2c92d38c66d Mon Sep 17 00:00:00 2001 From: goodboy Date: Tue, 1 Dec 2026 17:45:55 -0500 Subject: [PATCH] Check Kraken account and subscription diagnostics The paper selector exposed two different rejection reports for one order. Exercise the console and EMS paths with the same request. Tests cover, - Submit a paper buy and a buy for a foreign Kraken alias. Check both reports against the configured alias. Send a foreign cancel with an otherwise valid order ID and require zero WS sends. - Feed an unexpected list, an online greeting and a multiline rejection through the private socket. Check the quoted frame type, the INFO greeting and the escaped reason in both the WARNING and the exception. - Check the operation, pair and reqid in the order-send log. Deliver a rejected edit and verify the console quotes the action and exchange text while EMS receives the original reason. - Include a synthetic token in the rejected frame and check that neither the log nor the exception echoes it. (this patch was generated in some part by `Codex` using `GPT-6` (`OpenAI`)) --- tests/providers/test_kraken_order_control.py | 177 +++++++++++++++++-- 1 file changed, 161 insertions(+), 16 deletions(-) diff --git a/tests/providers/test_kraken_order_control.py b/tests/providers/test_kraken_order_control.py index eccc808a..43a858f3 100644 --- a/tests/providers/test_kraken_order_control.py +++ b/tests/providers/test_kraken_order_control.py @@ -241,7 +241,11 @@ def buy( ) -def cancel(oid: str, reqid: int) -> BrokerdCancel: +def cancel( + oid: str, + reqid: int, + account: str = 'kraken.spot', +) -> BrokerdCancel: ''' Build an acknowledged EMS cancel, which carries no symbol. @@ -250,7 +254,7 @@ def cancel(oid: str, reqid: int) -> BrokerdCancel: oid=oid, reqid=reqid, time_ns=2, - account='kraken.spot', + account=account, ) @@ -329,16 +333,26 @@ class OrderSession: Deliver one numbered ``openOrders`` update for an EMS reqid. ''' - async def updates() -> AsyncIterator[list[object]]: + await self.update([ + [{txid: {'userref': reqid, 'status': 'open'}}], + 'openOrders', + {'sequence': seq}, + ]) + + async def update( + self, + frame: WsFrame|list[object], + ) -> None: + ''' + Deliver one private-channel frame to the live update handler. + + ''' + async def updates() -> AsyncIterator[WsFrame|list[object]]: ''' - Yield a single Kraken v1 private-channel update. + Yield the frame and end this receive loop. ''' - yield [ - [{txid: {'userref': reqid, 'status': 'open'}}], - 'openOrders', - {'sequence': seq}, - ] + yield frame await broker.handle_order_updates( client=self.client, @@ -400,27 +414,57 @@ async def test_order_uses_configured_alias( assert frame['reqid'] == ack.reqid -@pytest.mark.parametrize('account', ['paper', 'kraken.other']) +@pytest.mark.parametrize( + 'account, cancel_order', + [ + pytest.param('paper', False, id='paper-buy'), + pytest.param('kraken.spot', False, id='foreign-buy'), + pytest.param('kraken.other', True, id='foreign-cancel'), + ], +) async def test_reject_foreign_account( client: api.Client, account: str, + cancel_order: bool, + caplog: pytest.LogCaptureFixture, ) -> None: ''' - Reject a buy addressed to another account before any WS send. + Reject requests addressed to another account before any WS send. - A live EMS relay can receive a buy from the paper selector. - Feed that request and an unconfigured alias through the live - ``broker.handle_order_requests()`` with ``kraken.spot`` active. - - Require a ``BrokerdError`` for the original order and zero - exchange messages. + With ``kraken.swing`` active, submit a paper or foreign buy, + or a symbol-less cancel carrying another account's name. + - The console included source indentation and EMS saw a literal + placeholder. Require one readable reason identifying both + accounts in both reports and zero exchange messages. ''' + client._key_descr = 'swing' + client.conf['accounts'] = {'swing': 'swing'} session: OrderSession = OrderSession(client) - await session.requests(request(buy('A', account=account))) + command: OrderCommand + if cancel_order: + command = cancel('A', reqid=17, account=account) + session.ids['A'] = 17 + session.txids[17] = 'KRAKEN-A' + + else: + command = buy('A', account=account) + + await session.requests(request(command)) session.ems.send.assert_awaited_once() error: object = session.ems.send.await_args.args[0] assert isinstance(error, BrokerdError) assert error.oid == 'A' + expected_account: str = 'kraken.swing' + expected: str = ( + f'Invalid Kraken account {account!r}, ' + f'expected {expected_account!r}' + ) + assert error.reason == expected + assert (broker.__name__, logging.ERROR, expected) in ( + caplog.record_tuples + ) assert not session.frames() @@ -843,5 +887,106 @@ async def test_ready_session_keeps_tokens_out_of_logs( order: WsFrame (order,) = session.frames('addOrder') assert order['token'] == token + assert ( + broker.__name__, + logging.INFO, + "Sending 'addOrder' for 'XBT/USD', reqid=1", + ) in caplog.record_tuples assert FIRST_TOKEN not in caplog.text assert NEXT_TOKEN not in caplog.text + + +async def test_private_subscription_diagnostics( + client: api.Client, + caplog: pytest.LogCaptureFixture, +) -> None: + ''' + Report connection status and rejected private subscriptions. + + - The online greeting triggered an unknown-event warning. An + error could copy the whole private reply into a log and an + exception. Send both messages through ``broker.subscribe()``. + - Send an unexpected list and a multiline rejection. Check that + the warning names the frame type and quotes the exchange text + without exposing a token or splitting the reason across lines. + + ''' + ws: mock.AsyncMock = mock.AsyncMock(spec=NoBsWs) + errmsg: str = 'EGeneral:Permission denied\nretry later' + ws.recv_msg.side_effect = [ + [FIRST_TOKEN], + { + 'event': 'systemStatus', + 'status': 'online', + }, + { + 'event': 'subscriptionStatus', + 'status': 'error', + 'subscription': { + 'name': 'openOrders', + 'token': FIRST_TOKEN, + }, + 'errorMessage': errmsg, + }, + ] + exc: pytest.ExceptionInfo[RuntimeError] + with ( + caplog.at_level(logging.INFO, logger=broker.__name__), + pytest.raises(RuntimeError) as exc, + ): + async with broker.subscribe(ws, client, FIRST_TOKEN): + pytest.fail('Kraken admitted a rejected subscription') + + reason: str = str(exc.value) + assert reason == ( + "Kraken rejected subscription 'openOrders': " + f'{errmsg!r}' + ) + assert ( + broker.__name__, + logging.WARNING, + "Expected a Kraken subscription event, received 'list'", + ) in caplog.record_tuples + assert (broker.__name__, logging.WARNING, reason) in ( + caplog.record_tuples + ) + assert ( + broker.__name__, + logging.INFO, + 'Kraken private WebSocket is online', + ) in caplog.record_tuples + assert FIRST_TOKEN not in reason + assert FIRST_TOKEN not in caplog.text + + +async def test_rejected_order_diagnostics( + client: api.Client, + caplog: pytest.LogCaptureFixture, +) -> None: + ''' + Identify the exchange action and its error in the console. + + - A rejected edit printed its wire action as ordinary prose. + Deliver an ``editOrderStatus`` with a multiline error through + ``broker.handle_order_updates()``. + - Require the quoted action, numeric request ID and escaped + error in the log. EMS receives the original rejection text. + + ''' + session: OrderSession = OrderSession(client) + session.ids['A'] = 17 + errmsg: str = 'EOrder:Invalid price\ncheck tick size' + await session.update({ + 'event': 'editOrderStatus', + 'status': 'error', + 'reqid': 17, + 'errorMessage': errmsg, + }) + assert ( + broker.__name__, + logging.ERROR, + f"Failed to 'edit' order 17:\n{errmsg!r}", + ) in caplog.record_tuples + session.ems.send.assert_awaited_once() + error: BrokerdError = session.ems.send.await_args.args[0] + assert error.reason == f'Failed edit:\n{errmsg}'