"""策略账本隔离、轮换优先级、纸面现金及重复成交回归。""" import unit_test_guard # noqa: F401 import copy 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 strategy_book as b, micro_rotation as m def snapshot(day='2026-10-27', low=False, high=False, growth=False, ready=True): members = [{'code': f'{600000+i}.SH', 'rank': i+1, 'eligible': True, 'close': 10., 'total_mv_wan': i+1} for i in range(30)] value = {'rule_version': m.RULE, 'basket_size': 30, 'data_date': '2026-10-26', 'effective_date': day, 'signal_ready': ready, 'basket_ready': ready, 'signal': {'date': '2026-10-26', 'ready': ready, 'low': low, 'high': high, 'growth_break': growth}, 'members': members, 'source_hashes': {'source': 'fixed'}, 'errors': []} value['snapshot_version'] = hashlib.sha256(json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(',', ':')).encode()).hexdigest() value['frozen'] = True return value class RotationTests(unittest.TestCase): def test_default_scope(self): self.assertEqual(b.CURRENT.get(), 'original') with b.scope('micro30'): self.assertIn("book_id = 'micro30'", b.scoped_sql('SELECT * FROM pms_position')) self.assertEqual(b.CURRENT.get(), 'original') def test_where_or_is_wrapped(self): sql = b.scoped_sql('SELECT * FROM pms_lot WHERE qty>0 OR closed_qty>0 ORDER BY id LIMIT 5') self.assertIn("WHERE book_id = 'original' AND (qty>0 OR closed_qty>0) ORDER BY", sql) def test_literals_and_nested_functions(self): sql = "SELECT * FROM pms_command WHERE note='ORDER BY x' AND id IN (:x,:y) ORDER BY id" self.assertIn("AND (note='ORDER BY x' AND id IN (:x,:y)) ORDER BY", b.scoped_sql(sql)) def test_insert_owns_book(self): self.assertEqual(b.scoped_sql('INSERT INTO pms_lot (ts_code,qty) VALUES (:c,:q)', 'micro30'), "INSERT INTO pms_lot (book_id, ts_code,qty) VALUES ('micro30', :c,:q)") def test_all_read_only(self): self.assertEqual(b.scoped_sql('SELECT * FROM pms_position', 'all'), 'SELECT * FROM pms_position') with self.assertRaises(ValueError): b.scoped_sql('UPDATE pms_position SET total_qty=0', 'all') def test_nonbook_untouched(self): sql = 'SELECT * FROM pms_qmt_order ORDER BY id' self.assertEqual(b.scoped_sql(sql, 'micro30'), sql) def test_unknown_scope_rejected(self): with self.assertRaises(ValueError): with b.scope('anything'): pass def test_snapshot_valid(self): self.assertEqual(m.snapshot_check(snapshot(), '2026-10-27'), []) def test_snapshot_tamper(self): s = snapshot();s['signal']['low'] = True self.assertIn('快照摘要不一致', m.snapshot_check(s, '2026-10-27')) def test_snapshot_date_and_freeze(self): s = snapshot();s['frozen'] = False self.assertGreaterEqual(len(m.snapshot_check(s, '2026-10-28')), 2) def test_growth_or_low_enters(self): for s in [snapshot(low=True), snapshot(growth=True)]: r = m.transition(m.initial_state(), s, micro_qty=0, original_qty=300, budget=100000) self.assertEqual((r['phase'], r['cycle'], len(r['target'])), ('entering_micro', 1, 30)) def test_high_vetoes_entry(self): r = m.transition(m.initial_state(), snapshot(low=True, high=True, growth=True), micro_qty=0, original_qty=0, budget=100) self.assertEqual(r['phase'], 'original') def test_exit_during_entry(self): s = m.initial_state();s['phase'] = 'entering_micro' r = m.transition(s, snapshot(high=True), micro_qty=100, original_qty=100, budget=100) self.assertEqual(r['phase'], 'returning_original') r = m.transition(s, snapshot(high=True), micro_qty=0, original_qty=100, budget=100, micro_pending=True) self.assertEqual(r['phase'], 'returning_original') r = m.transition(r, None, micro_qty=0, original_qty=100, budget=100, micro_pending=True) self.assertEqual(r['phase'], 'returning_original') r = m.transition(r, None, micro_qty=0, original_qty=100, budget=100) self.assertEqual(r['phase'], 'original') def test_missing_signal_does_not_exit(self): s = m.initial_state();s['phase'] = 'micro' r = m.transition(s, None, micro_qty=100, original_qty=0, budget=100) self.assertEqual(r['phase'], 'micro') def test_residual_prevents_new_cycle(self): s = m.initial_state();s['phase'] = 'returning_original' r = m.transition(s, snapshot(low=True), micro_qty=100, original_qty=0, budget=100) self.assertEqual(r['phase'], 'returning_original') def test_finish_no_same_tick_reentry(self): s = m.initial_state();s['phase'] = 'returning_original' r = m.transition(s, snapshot(low=True), micro_qty=0, original_qty=0, budget=100) self.assertEqual(r['phase'], 'original') def test_pause_and_exit_disable(self): s = m.initial_state();s['phase'] = 'micro' self.assertEqual(m.transition(s, snapshot(high=True), micro_qty=100, original_qty=0, budget=100, control='pause_all'), s) r = m.transition(s, snapshot(), micro_qty=100, original_qty=0, budget=100, control='exit_disable') self.assertTrue(r['disabled']);self.assertEqual(r['phase'], 'returning_original') def test_lot_minimum_fee(self): self.assertEqual(m.buy_qty('600000.SH', 10, 1000, {}), 0) self.assertEqual(m.buy_qty('600000.SH', 10, 1006, {}), 100) self.assertEqual(m.buy_qty('688001.SH', 10, 1006, {}), 0) def test_permissions_not_silent_subset(self): members = snapshot()['members'];members[0]['code'] = '688001.SH' self.assertTrue(any('权限' in s for s in m.preflight(members, 100000, {'MAIN'}, {}))) def test_unfilled_sells_do_not_fund_buys(self): snap = snapshot(low=True) state = m.transition(m.initial_state(), snap, micro_qty=0, original_qty=100, budget=100000) quotes = {r['code']: {'price': 10.} for r in snap['members']};quotes['000001.SZ'] = {'price': 10.} orders, _ = m.orders(state, snap, original=[{'ts_code':'000001.SZ','total_qty':100,'base_qty':100}], micro=[], quotes=quotes, cash=0, account_mv=1000, cap_amount=100000) self.assertTrue(orders);self.assertTrue(all(o['side'] == 'sell' for o in orders)) def test_same_ticker_and_inflight_block(self): snap = snapshot(low=True);state = m.transition(m.initial_state(), snap, micro_qty=0, original_qty=100, budget=100000) quotes = {r['code']: {'price': 10.} for r in snap['members']} orders, _ = m.orders(state, snap, original=[{'ts_code':'600000.SH','total_qty':100}], micro=[], quotes=quotes, cash=100000, account_mv=1000, cap_amount=100000, pending=[{'ts_code':'600001.SH'}]) self.assertFalse(any(o['side']=='buy' and o['ts_code'] in ('600000.SH','600001.SH') for o in orders)) def test_no_reweight_retained(self): snap=snapshot();s=m.initial_state();s.update(phase='micro', target=[r['code'] for r in snap['members']]) micro=[{'ts_code':c,'total_qty':100} for c in s['target']] orders,_=m.orders(s,snap,original=[],micro=micro,quotes={c:{'price':10} for c in s['target']},cash=100000,account_mv=30000,cap_amount=200000) self.assertEqual(orders,[]) def test_paper_idempotency_t1_and_cash(self): a={'cash':10000.,'books':{'original':{},'micro30':{}},'fills':{},'realized':{'original':0.,'micro30':0.},'fees':{'original':0.,'micro30':0.}} buy={'id':'1','book_id':'micro30','ts_code':'600000.SH','side':'buy','qty':100} self.assertTrue(m.apply_paper_fill(a,buy,10,'2026-10-26',{})) before=copy.deepcopy(a) self.assertFalse(m.apply_paper_fill(a,buy,10,'2026-10-26',{}));self.assertEqual(a,before) sell={**buy,'id':'2','side':'sell'} with self.assertRaises(ValueError):m.apply_paper_fill(a,sell,11,'2026-10-26',{}) self.assertTrue(m.apply_paper_fill(a,sell,11,'2026-10-27',{})) self.assertAlmostEqual(a['cash']-10000,a['realized']['micro30']) self.assertEqual(a['books']['original'],{}) class ActivationTests(unittest.TestCase): def test_simulation_direct_does_not_require_history(self): from app.services import rotation_service as s with patch.object(s.settings, 'PMS_TABLE_PREFIX', ''), patch.object(s.settings, 'INFRA_STRATEGY_BOOK_SCHEMA', True), \ patch.object(s.param_store, 'get_bool', return_value=True), patch.object(s.param_store, 'get', return_value='ws'), \ patch.object(s, 'configuration', return_value={'boards': {'MAIN', 'STAR', 'CHINEXT'}, 'costs': {'rate': .0002, 'minimum': 5.}}), \ patch.object(s.store, 'get', return_value=({'cash': {'original': 2000000., 'micro30': 0.}, 'source_funds_seq': 100}, 1)), \ patch.object(s.store, 'recent', side_effect=AssertionError('直接模拟不读取观察或纸面日')): self.assertEqual(s.activation_errors(), []) with patch.object(s.store, 'get', return_value=(None, 0)): self.assertIn('分策略现金尚未按实际账户初始化', s.activation_errors()) with patch.object(s.param_store, 'get', return_value='shadow'): self.assertIn('自动执行需要启用唯一QMT直连通道', s.activation_errors()) def test_direct_cannot_bypass_instance_or_migration(self): from app.services import rotation_service as s with patch.object(s.param_store, 'get_bool', return_value=True), patch.object(s.settings, 'PMS_TABLE_PREFIX', 'real_'): self.assertEqual(s.activation_errors(), ['本次策略只开放155模拟实例']) with patch.object(s.settings, 'PMS_TABLE_PREFIX', ''), patch.object(s.settings, 'INFRA_STRATEGY_BOOK_SCHEMA', False): self.assertEqual(s.activation_errors(), ['策略账本迁移尚未启用']) def test_default_keeps_validated_policy(self): from app.services import rotation_service as s with patch.object(s.settings, 'PMS_TABLE_PREFIX', ''), patch.object(s.settings, 'INFRA_STRATEGY_BOOK_SCHEMA', True), \ patch.object(s.param_store, 'get_bool', return_value=False), patch.object(s.store, 'get', return_value=(None, 0)), \ patch.object(s.store, 'recent', return_value=[]): errors = s.activation_errors() self.assertIn('有效观察不足3个交易日', errors) self.assertIn('观察完成后的健康纸面运行不足10个交易日', errors) class BoundaryTests(unittest.TestCase): def test_pause_cancels_only_rotation_orders(self): from app.services import rotation_service as s, executor rows = [{'instruction_id': 'micro_buy', 'book_id': 'micro30', 'side': 'buy', 'progress': {'execution_profile': 'rotation'}}, {'instruction_id': 'fund_sell', 'book_id': 'original', 'side': 'sell', 'progress': {'execution_profile': 'rotation'}}, {'instruction_id': 'user_buy', 'book_id': 'original', 'side': 'buy', 'progress': {}}] with patch.object(s.pms_repo, 'list_instructions', return_value=rows), patch.object(executor, 'cancel_instruction', return_value={'ok': True}) as cancel: s.cancel_control_orders('pause_new') self.assertEqual([c.args[0] for c in cancel.call_args_list], ['micro_buy']) cancel.reset_mock() s.cancel_control_orders('pause_all') self.assertEqual([c.args[0] for c in cancel.call_args_list], ['micro_buy', 'fund_sell']) def test_failed_cancel_does_not_allow_continue(self): from app.services import rotation_service as s, executor rows = [{'instruction_id': 'micro_buy', 'book_id': 'micro30', 'side': 'buy', 'progress': {'execution_profile': 'rotation'}}] with patch.object(s.pms_repo, 'list_instructions', return_value=rows), patch.object(executor, 'cancel_instruction', return_value={'ok': False}): with self.assertRaises(RuntimeError): s.cancel_control_orders('pause_all') self.assertEqual(b.CURRENT.get(), 'original') def test_publish_nav_reads_whole_account_after_migration(self): from app.services import publish_export as p from config.settings import settings with patch.object(settings, 'INFRA_STRATEGY_BOOK_SCHEMA', True), patch.object(p, '_compute_snapshot', side_effect=lambda: {'scope': b.CURRENT.get()}): self.assertEqual(p.compute_snapshot()['scope'], 'all') self.assertEqual(b.CURRENT.get(), 'original') def test_restart_does_not_reconsume_entry(self): snap=snapshot(low=True) a=m.transition(m.initial_state(),snap,micro_qty=0,original_qty=0,budget=100000) a.update(phase='returning_original',exit_date=snap['effective_date']) a=m.transition(a,snap,micro_qty=0,original_qty=0,budget=100000) a=json.loads(json.dumps(a)) self.assertEqual(m.transition(a,snap,micro_qty=0,original_qty=0,budget=100000)['phase'],'original') def test_confirmed_exit_survives_bad_monitor(self): a=m.initial_state();a.update(phase='returning_original',target=['600000.SH']) orders,_=m.orders(a,None,original=[],micro=[{'ts_code':'600000.SH','total_qty':100}],quotes={},cash=0,account_mv=1000,cap_amount=100000) self.assertEqual([(r['side'],r['qty']) for r in orders],[('sell',100)]) def test_partial_entry_does_not_reweight_after_price_fall(self): snap=snapshot(low=True);a=m.transition(m.initial_state(),snap,micro_qty=0,original_qty=0,budget=30000) a['entry_quantities']={'600000.SH':100} orders,_=m.orders(a,snap,original=[],micro=[{'ts_code':'600000.SH','total_qty':100}],quotes={'600000.SH':{'price':1}},cash=100000,account_mv=100,cap_amount=200000) self.assertFalse(any(r['ts_code']=='600000.SH' and r['side']=='buy' for r in orders)) def test_partial_fill_only_buys_remaining_quantity(self): snap=snapshot(low=True);a=m.transition(m.initial_state(),snap,micro_qty=0,original_qty=0,budget=30000) a['entry_quantities']={'600000.SH':300} orders,_=m.orders(a,snap,original=[],micro=[{'ts_code':'600000.SH','total_qty':100}],quotes={'600000.SH':{'price':10}},cash=100000,account_mv=1000,cap_amount=200000) self.assertEqual(orders[0]['qty'],200) def test_target30_can_have31_actual_positions(self): snap=snapshot();a=m.initial_state();a.update(phase='micro',target=[r['code'] for r in snap['members']]) held=[{'ts_code':c,'total_qty':100} for c in a['target']]+[{'ts_code':'000001.SZ','total_qty':100}] orders,_=m.orders(a,snap,original=[],micro=held,quotes={},cash=0,account_mv=31000,cap_amount=40000,pending=[{'ts_code':'000001.SZ'}]) self.assertEqual(orders,[]) def test_transfer_does_not_create_profit_or_change_nav(self): from app.core import rotation_account as a cash=a.seed(10000,{'original':10000,'micro30':0}) a.transfer(cash,'original','micro30',5000,{'original':12000,'micro30':0},'1') view=a.metrics(cash,{'original':12000,'micro30':0}) self.assertAlmostEqual(view['original']['profit'],2000) self.assertEqual(view['micro30']['profit'],0) self.assertAlmostEqual(view['original']['nav'],1.1) self.assertEqual(view['micro30']['nav'],1) self.assertEqual(view['account']['profit'],2000) def test_capital_duplicate_fill_and_cash_not_double_used(self): from app.core import rotation_account as a cash=a.seed(10000,{'original':0,'micro30':0}) a.transfer(cash,'original','micro30',5000,{},'1') self.assertFalse(a.transfer(cash,'original','micro30',5000,{},'1')) a.fill(cash,'micro30','buy',4000,5,'x') self.assertFalse(a.fill(cash,'micro30','buy',4000,5,'x')) with self.assertRaises(ValueError):a.fill(cash,'micro30','buy',1000,5,'y') self.assertEqual(sum(cash['cash'].values()),5995) def test_cannot_liquidate_unknown_old_micro_as_new_cycle(self): with self.assertRaises(ValueError):m.transition(m.initial_state(),snapshot(low=True),micro_qty=100,original_qty=0,budget=100) def test_pause_new_still_sells_dropped_member(self): a=m.initial_state();a.update(phase='micro',target=[]) orders,_=m.orders(a,snapshot(),original=[],micro=[{'ts_code':'000001.SZ','total_qty':100}],quotes={},cash=100000,account_mv=1000,cap_amount=100000,control='pause_new') self.assertEqual([r['side'] for r in orders],['sell']) def test_minimum_commission_for_small_budget(self): self.assertEqual(m.buy_qty('600000.SH',4.07,412.01,{'rate':.0002}),100) def test_risky_insert_rejected(self): with self.assertRaises(ValueError):b.scoped_sql('INSERT INTO pms_position (book_id,ts_code) VALUES (:b,:c)') def test_scope_restored_when_exception(self): with self.assertRaises(RuntimeError): with b.scope('micro30'):raise RuntimeError() self.assertEqual(b.CURRENT.get(),'original') class MarketReadingsTests(unittest.TestCase): def test_published_value_and_execution_date_are_not_confused(self): from app.services import macro_service as ms from app.repo import macro_repo row = {'id': 1, 'trade_date': '2026-10-27', 'hedge_index': '-17.8949', 'zone': 'neutral'} signal = {'trade_date': 20261028, 'value': -20.3242, 'zone': 'COLD', 'action': 'NONE', 'detail': {'zs_last': 20261027}} params = dict(enabled=True, autonomy='full', signals=['hedge_fx'], hot_th=25., cold_th=-20., exit_band=15., cooldown_tdays=3, trigger_hot='zone_exit', trigger_cold='zone_enter') with patch.object(ms, '_params', return_value=params), patch.object(ms, 'gate_state', return_value={}), patch.object(ms.td, 'ymd', return_value=20261028), patch.object(macro_repo, 'latest_published_hedge', return_value=row), patch.object(macro_repo, 'recent_signals', return_value=[signal]), patch.object(macro_repo, 'upsert_signal') as write, patch.object(ms.param_store, 'set_param') as set_param: result = ms.status()['signals'][0] self.assertEqual((result['value'], result['ymd'], result['data_ymd']), (-20.3242, 20261028, 20261027)) self.assertEqual(result['published']['value'], -17.8949) self.assertEqual(result['zone'], 'COLD') write.assert_not_called();set_param.assert_not_called() def test_invalid_published_data_is_not_zero_or_execution_fallback(self): from app.services import macro_service as ms from app.repo import macro_repo for value in (None, 'NaN', 'Infinity'): with patch.object(macro_repo, 'latest_published_hedge', return_value={'id':1, 'trade_date':'2026-10-27', 'hedge_index':value}), patch.object(ms.td, 'ymd', return_value=20261028): result = ms.published_reading() self.assertFalse(result['ready']) self.assertNotIn('value', result) with patch.object(macro_repo, 'latest_published_hedge', side_effect=RuntimeError('offline')): self.assertFalse(ms.published_reading()['ready']) def test_published_zero_valid_future_date_invalid(self): from app.services import macro_service as ms from app.repo import macro_repo for day, ready in (('2026-10-27', True), ('2026-10-29', False)): with patch.object(macro_repo, 'latest_published_hedge', return_value={'id':1, 'trade_date':day, 'hedge_index':0}), patch.object(ms.td, 'ymd', return_value=20261028): self.assertEqual(ms.published_reading()['ready'], ready) if __name__=='__main__': unittest.main()