"""人工止损命令、行情边界、SQLite清仓收尾;全部隔离,不连接运行账户。""" import unit_test_guard import copy import datetime as dt import json import unittest from unittest.mock import patch import test_risk_exit as base from app.core import risk_exit as core, strategy_book as books from app.repo import pms_repo, qmt_repo from app.services import risk_exit as service, market, executor, logic_state_service CODE, NOW = base.CODE, base.NOW def command(price=10, cid='STOP1', issued=None): return dict(command_id=cid, cmd_type='SET_STOP_PRICE', ts_code=CODE, status='EFFECTIVE', issued_at=issued or NOW-dt.timedelta(minutes=2), params={'price':price}) def quote(price=10, at=NOW): return dict(kind='minute', source='isolated-test', last=price, as_of=at.isoformat()) class CoreTests(unittest.TestCase): def test_equal_and_below_trigger_above_does_not(self): for price, trigger in [(9.99,True),(10,True),(10.01,False)]: self.assertEqual(bool(core.user_stop_event(command(),quote(price),now=NOW)[0]),trigger) def test_missing_disabled_invalid_command_never_triggers(self): for value in [None,0,-1,float('nan'),float('inf'),'bad']: self.assertIsNone(core.user_stop_event(command(value),quote(),now=NOW)[0]) for changes in [dict(command_id=None),dict(status='CANCELLED'),dict(ts_code='920001.BJ'), dict(issued_at=None),dict(issued_at=NOW+dt.timedelta(seconds=1))]: self.assertIsNone(core.user_stop_event({**command(),**changes},quote(),now=NOW)[0]) def test_quote_time_source_and_finite_price_required(self): changes=[dict(as_of=None),dict(as_of='2026-11-05T10:00:00'),dict(source=''), dict(kind='unknown'),dict(last=float('nan')),dict(last=float('inf')), dict(last=0),dict(as_of=(NOW-dt.timedelta(days=1)).isoformat()), dict(as_of=(NOW+dt.timedelta(seconds=1)).isoformat()), dict(as_of=(NOW-dt.timedelta(seconds=91)).isoformat())] for value in changes: with self.subTest(value=value): self.assertIsNone(core.user_stop_event(command(),{**quote(),**value},now=NOW)[0]) self.assertIsNotNone(core.user_stop_event(command(),quote(at=NOW-dt.timedelta(seconds=90)),now=NOW)[0]) def test_quote_must_follow_effective_command(self): self.assertIsNone(core.user_stop_event(command(issued=NOW),quote(at=NOW-dt.timedelta(seconds=1)),now=NOW)[0]) class ServiceTests(base.ServiceTests): def put_stop(self, price=10, cid='STOP1'): c=command(price,cid) self.insert('pms_command',dict(book_id='original',command_id=cid,cmd_class='param',cmd_type=c['cmd_type'], ts_code=CODE,status='EFFECTIVE',issued_at=c['issued_at'].isoformat(),params_json=json.dumps(c['params']))) def trigger(self): result=service.observe_user_stop(CODE,quote(),now=NOW) service.drive(CODE,now=NOW) return result def test_scan_generates_one_exit_without_model_or_second_signal(self): self.put_stop() with patch.object(market,'execution_quote',return_value=quote()) as fetch, \ patch.object(logic_state_service,'state_map',side_effect=RuntimeError('offline')): first=service.scan(now=NOW);service.scan(now=NOW) self.assertTrue(first['user_stops'][CODE]['triggered']) self.assertEqual(self.state()['count'],0) ins=self.instructions();self.assertEqual(len(ins),1);self.assertEqual(ins[0]['qty'],1600) self.assertTrue(ins[0]['progress']['is_command']);self.assertTrue(ins[0]['progress']['urgent']) self.assertFalse(ins[0]['progress']['from_signal']) self.assertEqual(ins[0]['progress']['risk_exit']['user_stop']['command_id'],'STOP1') self.assertEqual(fetch.call_args.kwargs['limits'],{}) def test_all_execution_halt_retains_intent_but_buy_halt_allows_exit(self): self.put_stop();self.params['PMS_GLOBAL_EXEC_HALT']=True self.trigger();self.assertEqual(self.instructions(),[]);self.assertEqual(self.state()['phase'],'EXIT_PENDING') self.params['PMS_GLOBAL_EXEC_HALT']=False;self.params['PMS_GLOBAL_BUY_HALT']=True service.drive(CODE,now=NOW);self.assertEqual(len(self.instructions()),1) def test_command_is_not_disabled_by_model_risk_switch(self): self.params['PMS_RISK_EXIT_ENABLED']=False;self.put_stop();self.trigger() self.assertEqual(len(self.instructions()),1);self.assertTrue(service.buy_blocker(CODE)) def existing_model_exit(self,pending): self.params['PMS_GLOBAL_EXEC_HALT']=pending self.fire();self.fire(2) self.params['PMS_GLOBAL_EXEC_HALT']=False self.params['PMS_RISK_EXIT_ENABLED']=False self.put_stop();self.trigger() self.assertEqual(len(self.instructions()),1) self.assertIn('user_stop',self.state()) service.drive(CODE,now=NOW);self.assertEqual(len(self.instructions()),1) def test_existing_model_pending_exit_continues_under_user_stop(self): self.existing_model_exit(True) def test_existing_model_exit_is_not_duplicated_by_user_stop(self): self.existing_model_exit(False) def test_latest_zero_price_disables_trigger_and_new_price_replaces_old(self): self.put_stop(11);self.put_stop(0,'STOP2') self.assertFalse(self.trigger()['triggered']);self.assertEqual(self.instructions(),[]) self.put_stop(10,'STOP3');self.assertTrue(self.trigger()['triggered']) self.assertEqual(self.state()['user_stop']['command_id'],'STOP3') def test_stale_quote_and_system_reference_do_not_trigger(self): self.put_stop(9) self.assertFalse(service.observe_user_stop(CODE,quote(),now=NOW)['triggered']) self.put_stop(11,'STOP2') self.assertFalse(service.observe_user_stop(CODE,quote(at=NOW-dt.timedelta(days=1)),now=NOW)['triggered']) self.assertEqual(self.instructions(),[]) def test_old_buy_cancel_and_pending_report_finish_before_full_exit(self): self.put_stop();self.cancel_pending=True pms_repo.insert_instruction(instruction_id='BUY',origin_type='proposal',origin_id=None, ts_code=CODE,action='ADD',side='buy',qty=100,status='DISPATCHED') self.insert('pms_qmt_order',dict(instruction_id='CHILD',parent_id='BUY',ts_code=CODE,side='buy',status='ACCEPTED')) self.trigger();self.assertEqual(len(self.instructions()),1) self.cancel_pending=False;self.change("UPDATE pms_qmt_order SET status='CANCELLED'") self.pending=1;service.drive(CODE,now=NOW);self.assertEqual(len(self.instructions()),1) self.pending=0;service.drive(CODE,now=NOW) self.assertEqual(self.instructions()[0]['action'],'EXIT');self.assertEqual(self.instructions()[0]['qty'],1600) def test_cancel_failure_keeps_intent_and_no_exit_then_retries(self): self.put_stop() pms_repo.insert_instruction(instruction_id='BUY',origin_type='proposal',origin_id=None, ts_code=CODE,action='ADD',side='buy',qty=100,status='PROPOSED') with patch.object(executor,'cancel_instruction',return_value={'ok':False}): with self.assertRaises(RuntimeError):self.trigger() self.assertEqual(self.state()['phase'],'EXIT_PENDING');self.assertEqual(len(self.instructions()),1) service.drive(CODE,now=NOW);self.assertEqual(self.instructions()[0]['action'],'EXIT') def test_old_grid_sell_and_strategy_are_cancelled_before_exit(self): self.put_stop() self.insert('pms_strategy',dict(book_id='original',strategy_id='GRID',ts_code=CODE,type='GRID',status='ACTIVE',params_json='{}',state_json='{}')) pms_repo.insert_instruction(instruction_id='SELL',origin_type='strategy',origin_id='GRID', ts_code=CODE,action='TRIM',side='sell',qty=100,status='DISPATCHED') self.insert('pms_qmt_order',dict(instruction_id='CHILD',parent_id='SELL',ts_code=CODE,side='sell',status='ACCEPTED')) self.trigger();self.assertEqual(len(self.instructions()),1) self.assertEqual(pms_repo.get_instruction('SELL')['status'],'CANCELLED') self.assertEqual(pms_repo.list_strategies(ts_code=CODE,statuses=['ACTIVE'],limit=1),[]) self.change("UPDATE pms_qmt_order SET status='CANCELLED'") service.drive(CODE,now=NOW);self.assertEqual(self.instructions()[0]['qty'],1600) def test_user_sell_finishes_then_exit_covers_actual_remainder(self): self.put_stop() pms_repo.insert_instruction(instruction_id='SELL',origin_type='plan',origin_id=None, ts_code=CODE,action='TRIM',side='sell',qty=100,status='PROPOSED') self.trigger();self.assertEqual(len(self.instructions()),1) pms_repo.update_instruction('SELL',status='CONFIRMED',exec_qty=100) self.change('UPDATE pms_position SET total_qty=1500,avail_qty=1500');self.change('UPDATE pms_lot SET qty=1500') service.drive(CODE,now=NOW);self.assertEqual(self.instructions()[0]['qty'],1500) def test_t1_partial_fill_and_late_buy_keep_full_remaining_exit(self): self.params['PMS_RISK_EXIT_ENABLED']=False self.put_stop();self.change('UPDATE pms_position SET avail_qty=0');self.trigger() ins=self.instructions()[0];self.assertEqual(ins['qty'],1600) pms_repo.update_instruction(ins['instruction_id'],status='DISPATCHED',exec_qty=600) self.change('UPDATE pms_position SET total_qty=1000,avail_qty=0');self.change('UPDATE pms_lot SET qty=1000') service.drive(CODE,now=NOW+dt.timedelta(days=1));self.assertEqual(len(self.instructions()),1) pms_repo.update_instruction(ins['instruction_id'],status='CONFIRMED',exec_qty=1600) self.change('UPDATE pms_position SET total_qty=0,avail_qty=0');self.change("UPDATE pms_lot SET qty=0,status='CLOSED'") service.drive(CODE,now=NOW);self.assertEqual(self.state()['phase'],'CLOSED') self.insert('pms_lot',dict(id=2,book_id='original',ts_code=CODE,instruction_id='BASE',qty=100,status='OPEN')) self.change('UPDATE pms_position SET total_qty=100,avail_qty=0') with patch.object(market,'execution_quote',return_value=quote(11)): service.scan(now=NOW) self.assertEqual(self.instructions()[0]['qty'],100);self.assertEqual(len(self.instructions()),2) def test_clearing_price_does_not_undo_trigger_or_reopen_cancelled_exit(self): self.put_stop();self.trigger();iid=self.instructions()[0]['instruction_id'] self.put_stop(0,'STOP2');service.drive(CODE,now=NOW) self.assertEqual(self.state()['phase'],'EXITING') pms_repo.update_instruction(iid,status='CANCELLED');service.drive(CODE,now=NOW) self.assertEqual(self.state()['phase'],'MANUAL');self.put_stop(10,'STOP3');self.trigger() self.assertEqual(len(self.instructions()),1) def test_audit_or_instruction_failure_cannot_lose_intent(self): self.put_stop() with patch.object(pms_repo,'insert_ledger',return_value=0): with self.assertRaises(RuntimeError):service.observe_user_stop(CODE,quote(),now=NOW) self.assertEqual(self.state(),{}) with patch.object(pms_repo,'insert_instruction',return_value=0): with self.assertRaises(RuntimeError):self.trigger() self.assertEqual(self.state()['phase'],'EXIT_PENDING');self.assertEqual(self.instructions(),[]) service.drive(CODE,now=NOW);self.assertEqual(len(self.instructions()),1) def test_other_book_and_no_holding_do_not_create_orders(self): self.put_stop() with books.scope('micro30'): self.assertIsNone(service.observe_user_stop(CODE,quote(),now=NOW)) self.change('UPDATE pms_position SET total_qty=0,avail_qty=0');self.change("UPDATE pms_lot SET qty=0,status='CLOSED'") self.assertFalse(self.trigger()['triggered']);self.assertEqual(self.instructions(),[]) for name in base.ServiceTests.__dict__: if name.startswith('test_') and name not in ServiceTests.__dict__: setattr(ServiceTests,name,None) if __name__=='__main__':unittest.main()