"""微盘冻结后备池、持久补齐及真实在途防重。所有输入为内存数据。""" import unit_test_guard # noqa: F401 import copy from contextlib import contextmanager, ExitStack, nullcontext import datetime as dt import hashlib import json from pathlib import Path import sys import unittest from unittest.mock import patch sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from app.core import micro_rotation as m def snapshot(day='2026-11-03', size=100, rule=m.EXECUTION_RULE, low=True): rows = [{'code': f'{600000+i}.SH', 'rank': i+1, 'eligible': True, 'close': 10., 'total_mv_wan': i+1} for i in range(size)] value = {'rule_version': rule, 'rule_parameters': m.rule_parameters(rule), 'basket_size': 50, 'data_date': '2026-11-02', 'effective_date': day, 'signal_ready': True, 'basket_ready': True, 'signal': {'date': '2026-11-02', 'ready': True, 'low': low, 'high': False, 'growth_break': False}, 'members': rows[:50], 'source_hashes': {'stocks': 'fixed'}, 'errors': []} if rule == m.EXECUTION_RULE: value.update(candidates=rows, candidate_count=len(rows)) value['snapshot_version'] = hashlib.sha256(json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(',', ':')).encode()).hexdigest() value['frozen'] = True return value def state(snap=None): snap = snap or snapshot() return m.transition(m.initial_state(), snap, micro_qty=0, original_qty=0, budget=100000) class SnapshotTests(unittest.TestCase): def test_v2_remains_compatible_without_candidates(self): snap = snapshot(rule=m.RULE) self.assertNotIn('candidates', snap) self.assertEqual(m.snapshot_check(snap, '2026-11-03'), []) def test_v3_contract_and_frozen_hash(self): snap = snapshot() self.assertEqual(m.snapshot_check(snap, '2026-11-03', expected_rule=m.EXECUTION_RULE), []) snap['candidates'][70]['close'] = 20 self.assertIn('快照摘要不一致', m.snapshot_check(snap, '2026-11-03')) def test_candidate_order_and_mainland_required(self): for change in ('rank', 'code'): snap = snapshot() snap['candidates'][70][change] = 1 if change == 'rank' else '920001.BJ' self.assertIn('冻结候选池数量、资格或顺序不完整', m.snapshot_check(snap, '2026-11-03')) def test_rule_mismatch_cannot_be_silent(self): self.assertIn('策略规则版本不一致', m.snapshot_check(snapshot(), '2026-11-03', expected_rule=m.RULE)) old = state(snapshot(rule=m.RULE)) with self.assertRaises(ValueError): m.transition(old, snapshot(), micro_qty=100, original_qty=0, budget=100000) def test_short_pool_is_explicit_and_valid(self): snap = snapshot(size=51) self.assertEqual(m.snapshot_check(snap, '2026-11-03'), []) class TargetTests(unittest.TestCase): def test_halted_zero_fill_uses_next_rank(self): snap = snapshot(); s = state(snap) m.resolve_targets(s, snap, unavailable={'600000.SH': '停牌'}) self.assertNotIn('600000.SH', s['target']) self.assertIn('600050.SH', s['target']) self.assertEqual(len(s['target']), 50) self.assertEqual(s['substitutions'][0]['from'], '600000.SH') def test_partial_fill_keeps_seat(self): snap = snapshot(); s = state(snap) m.resolve_targets(s, snap, micro=[{'ts_code': '600000.SH', 'total_qty': 100}], unavailable={'600000.SH': '停牌'}) self.assertIn('600000.SH', s['target']) self.assertNotIn('600050.SH', s['target']) def test_cancel_pending_keeps_seat(self): snap = snapshot(); s = state(snap) m.resolve_targets(s, snap, pending=[{'ts_code': '600000.SH'}], unavailable={'600000.SH': '停牌'}) self.assertIn('600000.SH', s['target']) m.resolve_targets(s, snap, pending=[], unavailable={'600000.SH': '停牌'}) self.assertNotIn('600000.SH', s['target']) def test_recovery_and_restart_do_not_switch_back_same_day(self): snap = snapshot(); s = state(snap) m.resolve_targets(s, snap, unavailable={'600000.SH': '停牌'}) s = json.loads(json.dumps(s)) s = m.transition(s, snap, micro_qty=0, original_qty=0, budget=100000) m.resolve_targets(s, snap, unavailable={}) self.assertNotIn('600000.SH', s['target']) self.assertIn('600050.SH', s['target']) def test_next_day_returns_to_new_frozen_rank(self): snap = snapshot(); s = state(snap) m.resolve_targets(s, snap, unavailable={'600000.SH': '停牌'}) tomorrow = snapshot(day='2026-11-04') s = m.transition(s, tomorrow, micro_qty=100, original_qty=0, budget=100000) m.resolve_targets(s, tomorrow, unavailable={}) self.assertIn('600000.SH', s['target']) self.assertNotIn('600050.SH', s['target']) def test_price_lag_does_not_change_target(self): snap = snapshot(); s = state(snap) m.resolve_targets(s, snap, unavailable={}) self.assertEqual(s['target'], [r['code'] for r in snap['members']]) def test_pool_exhaustion_does_not_remove_good_members(self): snap = snapshot(size=51); s = state(snap) waits = m.resolve_targets(s, snap, unavailable={'600000.SH': '停牌', '600001.SH': '停牌'}) self.assertEqual(len(s['target']), 49) self.assertEqual(s['target_shortfall'], 1) self.assertTrue(waits) def test_incomplete_daily_member_is_still_topped_up(self): snap = snapshot(); s = state(snap); s['phase'] = 'micro' held = [{'ts_code': r['code'], 'total_qty': 100} for r in snap['members'][1:]] kwargs = dict(original=[], quotes={'600000.SH': {'price': 10}}, cash=5000, account_mv=0, cap_amount=100000) orders, _ = m.orders(s, snap, micro=held, **kwargs) wanted = orders[0]['qty'] held.append({'ts_code': '600000.SH', 'total_qty': 100}) s = json.loads(json.dumps(s)) orders, _ = m.orders(s, snap, micro=held, **kwargs) self.assertEqual(orders[0]['qty'], wanted-100) self.assertEqual(s['buy_targets']['600000.SH']['qty'], wanted) def test_daily_target_does_not_expand_after_price_fall(self): snap = snapshot(); s = state(snap); s['phase'] = 'micro' s['buy_targets'] = {'600000.SH': {'qty': 300, 'snapshot_version': 'old'}} held = [{'ts_code': r['code'], 'total_qty': 100} for r in snap['members']] orders, _ = m.orders(s, snap, original=[], micro=held, quotes={'600000.SH': {'price': 1}}, cash=10000, account_mv=0, cap_amount=100000) self.assertEqual(orders[0]['qty'], 200) def test_old_positions_do_not_create_cash(self): snap = snapshot(); s = state(snap) orders, _ = m.orders(s, snap, original=[{'ts_code': '000001.SZ', 'total_qty': 100}], micro=[], quotes={'000001.SZ': {'price': 10}, **{r['code']: {'price': 10} for r in snap['members']}}, cash=0, account_mv=1000, cap_amount=100000) self.assertTrue(orders) self.assertTrue(all(r['side'] == 'sell' for r in orders)) def test_high_exit_overrides_unfinished_entry(self): snap = snapshot(); s = state(snap); snap['signal']['high'] = True s = m.transition(s, snap, micro_qty=100, original_qty=0, budget=100000) self.assertEqual(s['phase'], 'returning_original') before = copy.deepcopy(s) m.resolve_targets(s, snap, unavailable={'600000.SH': '停牌'}) self.assertEqual(s, before) class ServiceBoundaries(unittest.TestCase): def prepare(self, snap, funds, scale, *, prepare_only=True, fail_limits=False, missing_position=False, refresh=None): from app.services import rotation_service as r, rotation_execution as execution, execution_orders, command_service stored = {'rotation': m.initial_state()} config = {'mode': 'auto', 'control': 'run', 'rule_version': snap['rule_version'], 'candidate_pool_size': 100, 'boards': {'MAIN','CHINEXT','STAR'}, 'costs': {}} @contextmanager def locked(*args): yield stored with ExitStack() as stack: for obj, name, value in ( (r, 'configuration', config), (r, 'documents_ready', True), (r, 'activation_errors', []), (r, 'pull', snap), (r, 'reconcile_books', {'ok': True, 'diffs': []}), (r, 'positions', [{'ts_code':'600000.SH','total_qty':100}] if missing_position else []), (r, '_quote', {} if missing_position else {'price': 10}), (r, '_limits', {}), (r.market, 'execution_quote', {}), (execution_orders, 'quote_order', {'action':'WAIT','reason':'没有当日限制价'}), (r.td, 'calendar_degraded', False), (r.td, 'is_trade_day', True), (r.portfolio, 'cash_view', {'source': 'ws', 'cash_avail': funds}), (r.store, 'get', (stored, 0)), (r.store, 'put_once', None), (r, 'cancel_control_orders', None), (execution, 'cancel_expired', None), (execution, 'suspended_rejections', {}), (r.pms_repo, 'active_strategies', []), (command_service, 'blacklist', []), (execution, 'pending_instructions', [])): stack.enter_context(patch.object(obj, name, return_value=value)) stack.enter_context(patch.object(execution, 'refresh_orders', side_effect=refresh or (lambda *a, **kw: ([], [])))) if fail_limits: stack.enter_context(patch.object(r, '_limits', side_effect=RuntimeError('in-memory query failure'))) stack.enter_context(patch.object(r.store, 'locked', side_effect=locked)) stage = stack.enter_context(patch.object(r.store, 'stage_locked')) stack.enter_context(patch.object(r.settings, 'INFRA_STRATEGY_BOOK_SCHEMA', True)) stack.enter_context(patch.object(r.param_store, 'get_bool', return_value=False)) stack.enter_context(patch.object(r.param_store, 'get_float', side_effect=lambda k,d=0: { 'PMS_TOTAL_SCALE': scale, 'PMS_PORTFOLIO_CAP': 1, 'PMS_CASH_RESERVE': 0}.get(k,d))) result = r._tick(dt.datetime(2026, 11, 3, 9, 31, tzinfo=r.TZ), prepare_only=prepare_only) return stored, result, stage.call_count def test_static_failure_prevents_committing_entry(self): stored, result, writes = self.prepare(snapshot(rule=m.RULE), 500, 500) self.assertEqual(stored['rotation']['phase'], 'original') self.assertIn('blocked', result) self.assertEqual(writes, 0) def test_v3_zero_budget_does_not_clear_old_strategy(self): stored, result, writes = self.prepare(snapshot(), 0, 100000) self.assertEqual(stored['rotation']['phase'], 'original') self.assertEqual(writes, 0) def test_no_today_limits_blocks_funding_sales(self): from app.services import rotation_execution as execution with patch.object(execution,'send_intent') as send: stored, result, writes = self.prepare(snapshot(),100000,100000,prepare_only=False) self.assertIn('blocked',result) self.assertTrue(any('不卖出原策略' in reason for reason in result['blocked'])) send.assert_not_called() def test_v3_single_expensive_member_does_not_block_other_members(self): snap = snapshot(); snap['members'][0]['close'] = 10000 body = {k:v for k,v in snap.items() if k not in ('snapshot_version','frozen')} snap['snapshot_version'] = hashlib.sha256(json.dumps(body, sort_keys=True, ensure_ascii=False, separators=(',', ':')).encode()).hexdigest() stored, result, writes = self.prepare(snap, 100000, 100000) self.assertEqual(stored['rotation']['phase'], 'entering_micro') self.assertNotIn('600000.SH', stored['rotation']['target']) self.assertIn('600050.SH', stored['rotation']['target']) self.assertEqual(writes, 1) def test_limit_query_failure_still_refreshes_existing_orders(self): calls=[] def refresh(*args): calls.append(args) return [], [] stored,result,_=self.prepare(snapshot(),100000,100000,prepare_only=False, fail_limits=True,refresh=refresh) self.assertEqual(len(calls),1) self.assertTrue(any('限制价查询失败' in reason for reason in result['blocked'])) self.assertEqual(stored['rotation'].get('skipped_candidates'),{}) def test_missing_holding_quote_cancels_during_prepare_phase(self): calls=[] def refresh(*args): calls.append(args) return [], [] _,result,writes=self.prepare(snapshot(),100000,100000,missing_position=True,refresh=refresh) self.assertIn('blocked',result) self.assertEqual(writes,0) self.assertEqual(len(calls),1) self.assertEqual(calls[0][1],{}) def test_unknown_quote_is_not_a_suspension(self): from app.services.rotation_service import _unavailable_candidates out = _unavailable_candidates(snapshot(), {'600000.SH': {}}, 100000, {'MAIN', 'CHINEXT', 'STAR'}, {}) self.assertEqual(out, {}) def test_explicit_halt_affects_only_one_member(self): from app.services.rotation_service import _unavailable_candidates out = _unavailable_candidates(snapshot(), {'600000.SH': {'halted': True}}, 100000, {'MAIN', 'CHINEXT', 'STAR'}, {}) self.assertEqual(set(out), {'600000.SH'}) def test_live_child_survives_terminal_parent_in_pending(self): from app.services import rotation_execution as r parent = {'instruction_id': 'old', 'book_id': 'micro30', 'ts_code': '600000.SH', 'status': 'CANCELLED'} with patch.object(r.pms_repo, 'list_instructions', return_value=[]), \ patch.object(r.pms_repo, 'get_instruction', return_value=parent), \ patch.object(r.qmt_repo, 'list_orders', return_value=[{'parent_id': 'old'}]): self.assertEqual(r.pending_instructions(), [parent]) def test_unknown_live_child_owner_blocks(self): from app.services import rotation_execution as r with patch.object(r.pms_repo, 'list_instructions', return_value=[]), \ patch.object(r.pms_repo, 'get_instruction', return_value=None), \ patch.object(r.qmt_repo, 'list_orders', return_value=[{'parent_id': 'unknown'}]): with self.assertRaises(ValueError): r.pending_instructions() def send_existing(self, settled, cancel=False): from app.services import rotation_execution as r, execution_orders as e, dispatcher parent = {'instruction_id':'p', 'book_id':'micro30', 'ts_code':'600000.SH', 'side':'buy', 'qty':300, 'exec_qty':100, 'status':'DISPATCHED', 'progress':{'children':[{'ref':'p_D01'}], **({'cancel_requested':True} if cancel else {})}} with patch.object(r.db, 'transaction', side_effect=nullcontext), \ patch.object(r.pms_repo, 'get_instruction', return_value=parent), \ patch.object(r.pms_repo, 'update_instruction', return_value=1), \ patch.object(e, 'code_settlement_blocker', return_value=''), \ patch.object(e, 'replacement_state', return_value=settled), \ patch.object(e, 'retry_reason', return_value=''), \ patch.object(e, 'next_child_id', return_value='p_D02'), \ patch.object(dispatcher, 'mode', return_value='ws'), \ patch.object(dispatcher, 'dispatch', return_value={'ok':True}) as send: result = r.send_intent({'id':'p','book_id':'micro30','ts_code':'600000.SH','side':'buy', 'qty':300,'reason':'补齐'},10,dt.datetime(2026,11,3,9,40),'snapshot') return result, send.call_args def test_replacement_waits_until_cancellation_and_booking_finish(self): result, sent = self.send_existing({'ready':False,'remaining':200}) self.assertTrue(result['pending']) self.assertIsNone(sent) def test_replacement_only_submits_unfilled_quantity(self): result, sent = self.send_existing({'ready':True,'remaining':200}) self.assertEqual(sent.kwargs['qty'],200) self.assertEqual(sent.kwargs['instruction_id'],'p_D02') def test_user_cancelled_parent_never_reopens(self): result, sent = self.send_existing({'ready':True,'remaining':200},cancel=True) self.assertIsNone(sent) def test_partial_fill_after_cancel_still_keeps_seat(self): snap=snapshot(); s=state(snap) m.resolve_targets(s,snap,pending=[{'ts_code':'600000.SH'}],unavailable={'600000.SH':'停牌'}) m.resolve_targets(s,snap,micro=[{'ts_code':'600000.SH','total_qty':100}],unavailable={'600000.SH':'停牌'}) self.assertIn('600000.SH',s['target']) self.assertEqual(len(s['target']),50) def test_missing_quote_cancels_live_child_without_substituting(self): from app.services import rotation_execution as r, execution_orders as e, executor parent={'instruction_id':'p','book_id':'micro30','ts_code':'600000.SH','side':'buy','qty':100, 'progress':{'execution_profile':'rotation','rule_version':m.EXECUTION_RULE,'deadline':'2026-11-03'}} with patch.object(r.qmt_repo,'orders_for_parent',return_value=[{'status':'ACCEPTED'}]), \ patch.object(e,'quote_order',return_value={'action':'WAIT','reason':'行情缺失'}), \ patch.object(e,'request_replace',return_value={'pending':True}) as replace, \ patch.object(executor,'cancel_instruction') as cancel, \ patch.object(r.db,'savepoint',side_effect=nullcontext): result,waits=r.refresh_orders([parent],{},dt.datetime(2026,11,3,9,40),'v',{'600000.SH'},{}) replace.assert_called_once() cancel.assert_not_called() self.assertEqual(result,[]) self.assertTrue(waits) def test_missing_quote_without_live_child_only_waits(self): from app.services import rotation_execution as r, execution_orders as e parent={'instruction_id':'p','book_id':'micro30','ts_code':'600000.SH','side':'buy','qty':100, 'progress':{'execution_profile':'rotation','rule_version':m.EXECUTION_RULE,'deadline':'2026-11-03'}} with patch.object(r.qmt_repo,'orders_for_parent',return_value=[]), \ patch.object(e,'quote_order',return_value={'action':'WAIT','reason':'行情缺失'}), \ patch.object(e,'request_replace') as replace: r.refresh_orders([parent],{},dt.datetime(2026,11,3,9,40),'v',{'600000.SH'},{}) replace.assert_not_called() class ReservationTests(unittest.TestCase): def setUp(self): from app.repo import execution_repo stub = patch.object(execution_repo, 'pending_corrections', return_value=0) stub.start() self.addCleanup(stub.stop) def release(self, *, filled=0, fresh=True, booked=True): from app.services import rotation_execution as r, execution_orders as e now=dt.datetime(2026,11,3,9,40) account={'available':10010.,'orders':{'a':1005.,'b':9005.}} orders={'a':{'instruction_id':'a','parent_id':'pa','status':'CANCELLED', 'qty':1000,'cum_qty':filled,'limit_price':1.,'final_at':now}, 'b':{'instruction_id':'b','parent_id':'pb','status':'ACCEPTED', 'qty':9000,'cum_qty':0,'limit_price':1.,'final_at':None}} funds={'received_at':now+dt.timedelta(seconds=1 if fresh else -1)} state={'pending_trades':0 if booked else 1,'booked':filled if booked else 0, 'confirmed_filled':filled,'missing_orders':[]} with patch.object(r.qmt_repo,'get_order',side_effect=orders.get), \ patch.object(e,'replacement_state',return_value=state): r.release_settled_reservations(account,funds) r.release_settled_reservations(account,funds) return account def test_cancelled_one_releases_budget_while_others_live(self): account=self.release() self.assertEqual(account['orders'],{'a':0.,'b':9005.}) self.assertEqual(account['available']-sum(account['orders'].values()),1005.) def test_partial_cancel_keeps_filled_principal_and_original_fee(self): account=self.release(filled=100) self.assertEqual(account['orders'],{'a':105.,'b':9005.}) self.assertEqual(account['original_reservations']['a'],1005.) def test_old_funds_snapshot_cannot_release(self): self.assertEqual(self.release(fresh=False)['orders']['a'],1005.) def test_unbooked_trade_cannot_release(self): self.assertEqual(self.release(filled=100,booked=False)['orders']['a'],1005.) class SuspensionEvidenceTests(unittest.TestCase): def evidence(self, code='SUSPENDED', filled=0, ready=True, deadline='2026-11-03'): from app.services import rotation_execution as r, execution_orders as e order={'instruction_id':'p_D01','parent_id':'p','ts_code':'600000.SH','status':'REJECTED', 'reject_code':code,'cum_qty':filled} parent={'instruction_id':'p','book_id':'micro30','exec_qty':filled, 'progress':{'execution_profile':'rotation','rule_version':m.EXECUTION_RULE,'deadline':deadline}} with patch.object(r.db,'fetch_all',return_value=[order]), \ patch.object(r.pms_repo,'get_instruction',return_value=parent), \ patch.object(e,'replacement_state',return_value={'ready':ready,'confirmed_filled':filled}): return r.suspended_rejections(dt.datetime(2026,11,3,9,40)) def test_exact_suspended_zero_fill_can_substitute(self): result=self.evidence() self.assertIn('600000.SH',result) self.assertIn('p_D01',result['600000.SH']) def test_generic_errors_and_price_errors_never_substitute(self): for code in ('BROKER_ERROR','BAD_PARAM','UNKNOWN_CODE','LIMIT_UP','INTERNAL','INSUFFICIENT_CASH'): self.assertEqual(self.evidence(code=code),{}) def test_partial_or_pending_never_substitutes(self): self.assertEqual(self.evidence(filled=100),{}) self.assertEqual(self.evidence(ready=False),{}) def test_previous_day_rejection_does_not_carry_forward(self): self.assertEqual(self.evidence(deadline='2026-11-02'),{}) if __name__ == '__main__': unittest.main()