227 lines
13 KiB
Python
227 lines
13 KiB
Python
"""当日限价有效期、撤单与成交交错,以及传输状态的真实SQL回归。"""
|
||
import unit_test_guard
|
||
import asyncio
|
||
import copy
|
||
import os
|
||
import sys
|
||
import tempfile
|
||
import unittest
|
||
from contextlib import nullcontext
|
||
from datetime import datetime
|
||
from unittest.mock import AsyncMock, patch
|
||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||
from sqlalchemy import create_engine, text
|
||
from app.db import session
|
||
from app.repo import qmt_repo, pms_repo, execution_repo
|
||
from app.services import executor, dispatcher
|
||
from app.ws.runner import WsRunner
|
||
|
||
|
||
class ChannelTest(unittest.TestCase):
|
||
def setUp(self):
|
||
self.loop = asyncio.new_event_loop(); asyncio.set_event_loop(self.loop)
|
||
self.addCleanup(self.loop.close)
|
||
self.runner = WsRunner()
|
||
self.row = {'instruction_id': 'P_D01', 'parent_id': 'P', 'qty': 400, 'cum_qty': 0,
|
||
'status': 'ACCEPTED', 'cancel_state': 'SENT', 'ts_code': '688100.SH'}
|
||
self.use(qmt_repo, 'get_order', side_effect=lambda _: copy.deepcopy(self.row))
|
||
self.use(qmt_repo, 'update_order', side_effect=self.update)
|
||
self.use(execution_repo, 'pending_corrections', return_value=0)
|
||
self.use(pms_repo, 'get_instruction', return_value={'instruction_id': 'P', 'progress': {}})
|
||
|
||
def use(self, obj, name, **kw):
|
||
p = patch.object(obj, name, **kw); m = p.start(); self.addCleanup(p.stop); return m
|
||
|
||
def update(self, _, **fields): self.row.update(fields); return 1
|
||
def reject(self, code='ALREADY_FINAL'):
|
||
self.loop.run_until_complete(self.runner._apply_side_effects('reject',
|
||
{'instruction_id': 'P_D01', 'code': code, 'reason': 'cancel denied'}, {}))
|
||
def state(self, status, done):
|
||
self.loop.run_until_complete(self.runner._on_order_update('P_D01',
|
||
{'status': status, 'cum_qty': done, 'final': status in qmt_repo.FINAL, 'leaves_qty': 0}))
|
||
|
||
def test_cancel_reject_keeps_order_and_reservation(self):
|
||
self.row.update(status='PARTIAL', cum_qty=100)
|
||
self.reject('INTERNAL')
|
||
self.assertEqual((self.row['status'], self.row['cum_qty']), ('PARTIAL', 100))
|
||
self.assertNotIn('final_at', self.row)
|
||
with patch.object(dispatcher, 'mode', return_value='ws'), patch.object(qmt_repo, 'orders_for_parent', return_value=[self.row]):
|
||
self.assertEqual(executor._parent_available({'instruction_id': 'P', 'qty': 400, 'exec_qty': 0}, []), 0)
|
||
|
||
def test_already_final_before_final_update_keeps_pending(self):
|
||
self.row['cancel_state'] = 'NONE'
|
||
self.reject(); self.assertEqual(self.row['status'], 'ACCEPTED')
|
||
self.state('FILLED', 400); self.assertEqual(self.row['status'], 'FILLED')
|
||
|
||
def test_reject_cannot_overwrite_filled(self):
|
||
self.row.update(status='FILLED', cum_qty=400)
|
||
self.reject(); self.assertEqual((self.row['status'], self.row['cum_qty']), ('FILLED', 400))
|
||
|
||
def test_genuine_place_rejection_still_finishes(self):
|
||
self.row.update(status='SENT', cancel_state='NONE')
|
||
self.reject('INVALID_PRICE'); self.assertEqual(self.row['status'], 'REJECTED')
|
||
|
||
def test_partial_cancel_preserves_fill_releases_only_remainder(self):
|
||
self.row['cum_qty'] = 100
|
||
self.state('CANCELLED', 100)
|
||
with patch.object(dispatcher, 'mode', return_value='ws'), patch.object(qmt_repo, 'orders_for_parent', return_value=[self.row]):
|
||
self.assertEqual(executor._parent_available({'instruction_id': 'P', 'qty': 400, 'exec_qty': 0}, []), 300)
|
||
|
||
def test_cancel_cannot_zero_previously_reported_fills(self):
|
||
self.row.update(status='PARTIAL', cum_qty=100)
|
||
self.state('CANCELLED', 0)
|
||
self.assertEqual((self.row['status'], self.row['cum_qty']), ('PARTIAL', 100))
|
||
self.assertEqual(self.runner._stat['order_update_conflicts'], 1)
|
||
|
||
def test_missing_or_invalid_cumulative_quantity_keeps_pending(self):
|
||
for quantity in (None, -1, 500):
|
||
self.state('CANCELLED', quantity)
|
||
self.assertEqual(self.row['status'], 'ACCEPTED')
|
||
self.state('FILLED', 0); self.assertEqual(self.row['status'], 'ACCEPTED')
|
||
|
||
def test_late_cancel_does_not_override_full_fill(self):
|
||
self.state('FILLED', 400); self.state('CANCELLED', 400)
|
||
self.assertEqual(self.row['status'], 'FILLED')
|
||
|
||
def test_restarted_queued_order_is_cancelled_at_qmt(self):
|
||
self.row.update(status='QUEUED', sent_at=datetime.now(), cancel_state='REQUESTED', cancel_id='C')
|
||
with patch.object(qmt_repo, 'next_cancel_requests', return_value=[self.row]), \
|
||
patch.object(qmt_repo, 'mark_cancel_sent'), patch.object(qmt_repo, 'abort_order') as abort, \
|
||
patch.object(self.runner, '_send', new_callable=AsyncMock) as send:
|
||
self.loop.run_until_complete(self.runner._drain_cancels('unused'))
|
||
abort.assert_not_called(); send.assert_awaited_once()
|
||
self.assertEqual(send.call_args.args[0], 'cancel_order')
|
||
|
||
def test_unsent_queue_can_be_aborted_locally(self):
|
||
self.row.update(status='QUEUED', sent_at=None, cancel_state='REQUESTED')
|
||
with patch.object(qmt_repo, 'next_cancel_requests', return_value=[self.row]), \
|
||
patch.object(qmt_repo, 'mark_cancel_sent'), patch.object(qmt_repo, 'abort_order') as abort, \
|
||
patch.object(self.runner, '_send', new_callable=AsyncMock) as send:
|
||
self.loop.run_until_complete(self.runner._drain_cancels('unused'))
|
||
abort.assert_called_once(); send.assert_not_called()
|
||
|
||
def test_expired_uncertain_send_needs_downstream_cancel(self):
|
||
self.row.update(status='QUEUED', sent_at=datetime.now(), cancel_state='NONE')
|
||
with patch.object(qmt_repo, 'request_order_cancel', return_value=1) as cancel, patch.object(qmt_repo, 'abort_order') as abort:
|
||
self.loop.run_until_complete(self.runner._stop_outbox_order('P_D01', 'expired'))
|
||
cancel.assert_called_once(); abort.assert_not_called()
|
||
|
||
def test_cancel_between_claim_and_send_prevents_transport(self):
|
||
from app.services import execution_conflicts
|
||
self.row.update(status='SENDING', cancel_state='NONE', side='buy', limit_price=23.3,
|
||
valid_until=9999999999999)
|
||
with patch.object(qmt_repo, 'next_queued', return_value=[self.row]), \
|
||
patch.object(qmt_repo, 'claim_order', return_value=True), \
|
||
patch.object(execution_conflicts, 'queued_buy_blocker', return_value=None), \
|
||
patch.object(qmt_repo, 'mark_send_attempt', return_value=False), \
|
||
patch.object(self.runner, '_send', new_callable=AsyncMock) as send:
|
||
self.loop.run_until_complete(self.runner._drain_outbox('unused'))
|
||
send.assert_not_called()
|
||
|
||
def test_send_error_after_attempt_keeps_uncertain_order_retryable(self):
|
||
from app.services import execution_conflicts
|
||
self.row.update(status='SENDING', cancel_state='NONE', side='buy', limit_price=23.3,
|
||
valid_until=9999999999999)
|
||
def attempted(_): self.row['sent_at'] = datetime.now(); return True
|
||
with patch.object(qmt_repo, 'next_queued', return_value=[self.row]), \
|
||
patch.object(qmt_repo, 'claim_order', return_value=True), \
|
||
patch.object(execution_conflicts, 'queued_buy_blocker', return_value=None), \
|
||
patch.object(qmt_repo, 'mark_send_attempt', side_effect=attempted), \
|
||
patch.object(qmt_repo, 'requeue_order') as requeue, \
|
||
patch.object(self.runner, '_send', new_callable=AsyncMock, side_effect=RuntimeError('uncertain send')):
|
||
with self.assertRaises(RuntimeError):
|
||
self.loop.run_until_complete(self.runner._drain_outbox('unused'))
|
||
self.assertTrue(self.row['sent_at'])
|
||
self.assertFalse(requeue.call_args.args[-1])
|
||
|
||
|
||
class DeadlineTest(unittest.TestCase):
|
||
def test_qmt_day_order_always_ends_at_close(self):
|
||
with patch.object(executor.param_store, 'get_bool', return_value=True):
|
||
for hour, minute in [(9, 31), (11, 25), (14, 58)]:
|
||
self.assertEqual(executor.order_deadline(datetime(2026, 10, 30, hour, minute),
|
||
{'qmt_price_monitor': True}, ttl_min=10), 900)
|
||
|
||
def test_old_mode_keeps_ten_minute_lifetime(self):
|
||
now = datetime(2026, 10, 30, 10, 22)
|
||
with patch.object(executor.param_store, 'get_bool', return_value=False):
|
||
self.assertEqual(executor.order_deadline(now, {'qmt_price_monitor': True}, ttl_min=10), 632)
|
||
with patch.object(executor.param_store, 'get_bool', return_value=True):
|
||
self.assertEqual(executor.order_deadline(now, {}, ttl_min=10), 632)
|
||
|
||
def test_repeated_cancel_request_reports_pending(self):
|
||
with patch.object(dispatcher, 'mode', return_value='ws'), \
|
||
patch.object(qmt_repo, 'request_cancel', return_value=0), \
|
||
patch.object(qmt_repo, 'orders_for_parent', return_value=[{'status': 'PARTIAL', 'cancel_state': 'SENT'}]):
|
||
result = dispatcher.cancel(instruction_id='P')
|
||
self.assertTrue(result['ok']); self.assertTrue(result['cancel_pending'])
|
||
|
||
def test_cancel_intent_survives_status_read_failure(self):
|
||
with patch.object(dispatcher, 'mode', return_value='ws'), \
|
||
patch.object(qmt_repo, 'request_cancel', return_value=0), \
|
||
patch.object(qmt_repo, 'orders_for_parent', side_effect=RuntimeError('temporarily unavailable')):
|
||
result = dispatcher.cancel(instruction_id='P')
|
||
self.assertTrue(result['ok']); self.assertTrue(result['cancel_pending'])
|
||
|
||
|
||
class SqlTest(unittest.TestCase):
|
||
def setUp(self):
|
||
self.tmp = tempfile.TemporaryDirectory(); self.addCleanup(self.tmp.cleanup)
|
||
self.engine = create_engine('sqlite:///' + self.tmp.name + '/orders.sqlite'); self.addCleanup(self.engine.dispose)
|
||
for obj, name, kwargs in [(session, 'get_engine', {'return_value': self.engine}), (session, '_check_cooldown', {})]:
|
||
p = patch.object(obj, name, **kwargs); p.start(); self.addCleanup(p.stop)
|
||
with self.engine.begin() as c:
|
||
c.execute(text('CREATE TABLE pms_qmt_order(instruction_id TEXT PRIMARY KEY,status TEXT,sent_at TEXT,updated_at TEXT,send_attempts INTEGER,cancel_state TEXT,reject_code TEXT,reject_reason TEXT,final_at TEXT)'))
|
||
c.execute(text("INSERT INTO pms_qmt_order(instruction_id,status,send_attempts,cancel_state) VALUES('I','SENDING',0,'NONE')"))
|
||
def row(self): return session.fetch_one("SELECT * FROM pms_qmt_order WHERE instruction_id='I'")
|
||
|
||
def test_send_marker_persists_before_transport(self):
|
||
self.assertTrue(qmt_repo.mark_send_attempt('I')); self.assertTrue(self.row()['sent_at'])
|
||
self.assertEqual(qmt_repo.abort_order('I', 'cancel'), 0)
|
||
self.assertEqual(self.row()['status'], 'SENDING')
|
||
|
||
def test_cancel_wins_before_transport(self):
|
||
qmt_repo.update_order('I', cancel_state='REQUESTED')
|
||
self.assertFalse(qmt_repo.mark_send_attempt('I'))
|
||
self.assertEqual(qmt_repo.abort_order('I', 'cancel'), 1)
|
||
self.assertEqual(self.row()['status'], 'ABORTED')
|
||
|
||
def test_fast_ack_or_fill_never_regresses_to_sent(self):
|
||
for status in ('ACCEPTED', 'PARTIAL', 'FILLED', 'CANCELLED'):
|
||
qmt_repo.update_order('I', status=status)
|
||
qmt_repo.mark_sent('I'); self.assertEqual(self.row()['status'], status)
|
||
qmt_repo.requeue_order('I', 'error'); self.assertEqual(self.row()['status'], status)
|
||
|
||
def test_restart_retains_send_uncertainty(self):
|
||
qmt_repo.mark_send_attempt('I'); qmt_repo.reset_stuck_sending()
|
||
self.assertEqual(self.row()['status'], 'QUEUED'); self.assertTrue(self.row()['sent_at'])
|
||
self.assertEqual(qmt_repo.abort_order('I', 'expired'), 0)
|
||
|
||
|
||
class ZBookTest(unittest.TestCase):
|
||
def test_late_trade_after_parent_cancel_books_once_in_own_strategy(self):
|
||
from test_wiring import install_fakes
|
||
from app.services import rotation_execution as re, rotation_accounting as ra, trade_lineage
|
||
from app.repo import rotation_repo
|
||
fake = install_fakes(prices={'688100.SH': 23.3})
|
||
fake.insert_instruction(instruction_id='P', origin_type='proposal', origin_id='X',
|
||
ts_code='688100.SH', action='OPEN', side='buy', qty=400, status='CANCELLED')
|
||
fake.instructions['P']['book_id'] = 'original'
|
||
fake.qmt.put_trade(seq=1, instruction_id='P_D01', ts_code='688100.SH', side='buy', qty=100, price=23.3)
|
||
act = {'instruction_id': 'P', 'kind': 'BUY', 'ts_code': '688100.SH', 'qty': 100, 'price': 23.3, 'lot_type': 'BASE', 'order_id': 'T1'}
|
||
with patch.object(re.db, 'transaction', side_effect=nullcontext), \
|
||
patch.object(trade_lineage, 'record'), \
|
||
patch.object(rotation_repo, 'account_guard', side_effect=nullcontext), \
|
||
patch.object(re.db, 'fetch_one', side_effect=lambda *a, **kw: {'processed': fake.qmt.inbox[1]['processed']}), \
|
||
patch.object(pms_repo, 'get_instruction', side_effect=lambda iid: copy.deepcopy(fake.instructions.get(iid))), \
|
||
patch.object(ra, 'record_fill') as cash:
|
||
self.assertTrue(re.book_trade(act, [], 1))
|
||
self.assertFalse(re.book_trade(act, [], 1))
|
||
self.assertEqual(fake.positions['688100.SH']['total_qty'], 100)
|
||
self.assertEqual(fake.instructions['P']['exec_qty'], 100)
|
||
self.assertEqual(fake.instructions['P']['status'], 'CANCELLED')
|
||
cash.assert_called_once_with('original', 'buy', 2330., 0, '1')
|
||
|
||
|
||
if __name__ == '__main__': unittest.main()
|