"""交易员面板:当前依据一致、缺失不等于中性、旧确认与执行条件隔离(17例)。""" import unit_test_guard import os import sys sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import copy import unittest from unittest.mock import patch from datetime import datetime from app.core import proposal_analysis as pa, plan_revision from app.services import tech_service as tech, consensus_service as cs, proposal_service as ps from app.services import plan_recheck as rc, execution_basis as eb, timing_fusion, timing_state from app.repo import tech_repo, pms_repo CODE='002920.SZ' NOW=datetime(2026,11,12,11,10) def hard(stance='看多'): return {'fund_stance':{'stance':'看多'}, 'tech':{'stance':stance,'phase':'开口向上','data_date':20261111}, 'timing':{'stance':'无读数'}, 'consensus':{'direction':'看多','route':'交人','strength':'弱'}, 'preparation':{'status':'ready'},'consumption_id':'saved','proposal_revision':'shown'} def proposal(): return {'ts_code':CODE,'action':'OPEN','status':'WAIT_USER','proposal_id':'p','qty':100,'hard_numbers':hard()} class TraderViewTests(unittest.TestCase): def test_neutral_remains_neutral(self): self.assertEqual(pa.timing_view({'stance':'中性'})['label'],'中性') def test_missing_does_not_claim_neutral_or_fault(self): self.assertEqual(pa.timing_view({})['label'],'买入依据不足') self.assertNotIn('故障',pa.timing_view({})['reason']) def test_valid_conflict_explains_buy_restriction(self): t={'event':{'action':'WAIT','groups':{'a':{'state':'VALID','direction':1},'b':{'state':'VALID','direction':-1}}}} self.assertEqual(pa.timing_view(t)['label'],'多空分歧') t['event']['groups']['b']['state']='EXPIRED' self.assertEqual(pa.timing_view(t)['label'],'买入依据不足') def test_missing_tech_becomes_available_changes_confirmation(self): a,b=hard('无读数'),hard('看多') self.assertTrue(pa.changed(a,b)) self.assertNotEqual(plan_revision.confirmation_revision(100,a,{}),plan_revision.confirmation_revision(100,b,{})) def test_transport_time_and_evidence_key_alone_do_not_change_confirmation(self): a=hard();b=copy.deepcopy(a) b['timing'].update(event={'key':'refreshed','verified_at':'new'},fresh=True) b['tech']['latest']={'close':23.4} b['consensus']['route_reason']='说明内的实时价格刷新' self.assertFalse(pa.changed(a,b)) self.assertEqual(plan_revision.confirmation_revision(100,a,{}),plan_revision.confirmation_revision(100,b,{})) def test_readonly_current_analysis_disables_stale_confirmation_preserves_history(self): p=proposal();p['hard_numbers']['tech']['stance']='无读数';original=copy.deepcopy(p['hard_numbers']) def attach(rows,**kw): rows[0]['consensus_hard']=hard() with patch.object(ps,'_attach_consensus',side_effect=attach),patch.object(pms_repo,'record_proposal_check',side_effect=AssertionError('只读不得写')): cs.decorate_proposals([p],now=NOW) self.assertFalse(p['accept_ready']);self.assertEqual(p['analysis']['tech']['stance'],'看多') self.assertEqual(p['hard_numbers'],original) def test_read_failure_cannot_fall_back_to_unreviewed_open(self): rows=[{'ts_code':CODE}] with patch.object(cs,'nightly_map',return_value={}),patch.object(tech,'read_states_for',side_effect=RuntimeError('read failed')): ps._attach_consensus(rows,now=NOW) self.assertEqual(rows[0]['consensus']['route'],'观察') self.assertNotIn('consensus_hard',rows[0]) def test_accepted_plan_is_not_recreated_or_relabelled(self): p=proposal();p['status']='ACCEPTED';original=copy.deepcopy(p) with patch.object(ps,'_attach_consensus',side_effect=AssertionError('已采纳不重评')): cs.decorate_proposals([p],now=NOW) self.assertEqual(p,original) def test_analysis_failure_blocks_confirmation(self): p=proposal() with patch.object(ps,'_attach_consensus',return_value=None):cs.decorate_proposals([p],now=NOW) self.assertFalse(p['accept_ready']);self.assertIn('分析暂不可用',p['prepare_reason']) def test_before_accept_rechecks_analysis_without_model_or_order(self): p=proposal() with patch.object(ps,'is_expired',return_value=False),patch.object(rc,'current_basis',return_value={'view':{'held':[]},'analysis_changed':True}),patch.object(pms_repo,'record_proposal_check',return_value=1),patch.object(rc,'fast_checks',side_effect=AssertionError('不可确认旧分析')): out=rc.before_accept(p,'shown') self.assertFalse(out['ok']);self.assertTrue(out['pending']);self.assertIn('分析已变化',out['error']) def test_refresh_rechecks_changed_analysis_instead_of_ready_shortcut(self): p=proposal() check={'ok':False,'view':{},'analysis_changed':True} # 明确给出有效非空 view,变化须进入既有重扫流程。 check.update(view={'held':[]},params={},stock={}) with patch.object(rc,'current_basis',return_value=check),patch.object(pms_repo,'record_proposal_check',return_value=1),patch.object(ps,'_scan_open',return_value=[]) as scan,patch.object(rc,'_failed_recheck',return_value={'ok':False}): rc.refresh_one(p,now=NOW) scan.assert_called_once() def test_absent_timing_and_version_refresh_have_different_reasons(self): with patch.object(timing_fusion,'enabled',return_value=True),patch.object(timing_state,'latest',return_value=None): reason=eb.cache_reason({'execution_basis_cache':{'basis':{}}},NOW) self.assertIn('证据不足',reason);self.assertNotIn('版本',reason) with patch.object(timing_fusion,'enabled',return_value=True),patch.object(timing_state,'latest',return_value={'action':'BUY','key':'new'}): reason=eb.cache_reason({'execution_basis_cache':{'basis':{'timing_version':'old'}}},NOW) self.assertIn('择时已转多',reason);self.assertIn('不下单',reason) def test_sell_keeps_buy_block(self): with patch.object(timing_fusion,'enabled',return_value=True),patch.object(timing_state,'latest',return_value={'action':'SELL'}): self.assertEqual(eb.cache_reason({},NOW),'当前择时看空,暂停买入') class TechnicalCoverageTests(unittest.TestCase): def setUp(self): self.ps=[] for obj,name,kw in [(tech,'enabled',{'return_value':True}),(tech,'_params',{'return_value':{'stale_tdays':2,'rules':{}}}), (tech,'_tdays_elapsed',{'return_value':1}),(tech_repo,'latest_date',{'return_value':20261111}), (tech.tradedays,'prev_trade_day',{'return_value':20261020}),(tech.tradedays,'ymd',{'side_effect':lambda *a:20261020 if a else 20261112}), (tech.tech_rules,'synthesize',{'return_value':{'stance':'看多','phase':'开口向上','data_date':20261111}})]: p=patch.object(obj,name,**kw);p.start();self.addCleanup(p.stop) def test_candidate_and_detail_share_same_valid_data(self): with patch.object(tech_repo,'history_multi',return_value={CODE:[{'data_date':20261111}]}): self.assertEqual(tech.read_states_for([CODE])[CODE],tech.research_feed(CODE)['tech']) def test_stale_detail_cannot_fall_back_to_old_bullish_map(self): with patch.object(tech,'_tdays_elapsed',return_value=3),patch.object(tech_repo,'history_multi',side_effect=AssertionError('过期不取历史')): self.assertEqual(tech.read_states_for([CODE]),{});self.assertIsNone(tech.research_feed(CODE)['tech']) def test_missing_latest_day_is_not_replaced_with_previous_day(self): with patch.object(tech_repo,'history_multi',return_value={CODE:[{'data_date':20261110}]}): self.assertEqual(tech.read_states_for([CODE]),{}) def test_non_mainland_excluded_before_reading(self): with patch.object(tech_repo,'history_multi',return_value={}) as read: tech.read_states_for([CODE,'920000.BJ']) self.assertEqual(read.call_args.args[0],[CODE]) if __name__=='__main__':unittest.main()