tradingSystem/scripts/test_proposal_trader_view.py

172 lines
12 KiB
Python
Raw Normal View History

"""交易员面板:当前依据一致、数据库读数可保存、旧确认与执行条件隔离(21例)。"""
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 json
import unittest
from contextlib import nullcontext
from decimal import Decimal
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_research_detail_preserves_watch_context_without_review(self):
from app.web import main
from app.services import logic_state_service,plan_feed
row={'ts_code':CODE,'user_candidate':{'id':'watch','expires_on':'2099-01-01'}}
blocks={'fund':{'stance':'无读数'},'tech':{'stance':'看多'},'timing':{'stance':'看多'},'consensus':{'route':'放行'}}
with patch.object(logic_state_service,'state_map',return_value={}),patch.object(logic_state_service,'company_view',return_value=None),patch.object(plan_feed,'get_plan',return_value={'main':[row]}),patch.object(cs,'nightly_map',return_value={}),patch.object(tech,'research_feed',return_value={'tech':blocks['tech']}),patch.object(cs,'assemble',return_value=blocks) as assemble:
out=main.api_research(CODE)
self.assertTrue(out['ok']);self.assertEqual(assemble.call_args.args[0]['user_candidate'],row['user_candidate'])
def test_changed_proposal_explains_actual_trade_restriction(self):
a=hard();a['consensus'].update(route='观察',route_reason='等待新的有效合成择时')
self.assertEqual(pa.recheck_message(a),'有效择时证据不足,暂不建仓')
a['consensus'].update(direction='看空',route_reason='方向看空')
self.assertEqual(pa.recheck_message(a),'综合分析看空,当前不建议建仓')
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])
def decimal_reading(self):
row={'data_date':20261111,'sar_side':'long','sar_flip_days':2,
'quality':'OK','reanchored':1,'boll_squeeze':0,
**{k:Decimal('23.125') for k in ('boll_upper','boll_mid','boll_lower',
'boll_bw_pct','boll_pos','bbi','bbi_pos','bbi_dist_pct','sar_value','sar_dist_pct')}}
with patch.object(tech_repo,'history_multi',return_value={CODE:[row]}):
result=tech.read_states_for([CODE])[CODE]
self.assertIsInstance(row['sar_value'],Decimal)
return result
def test_database_numeric_reading_can_be_saved_in_new_proposal(self):
h=hard();h['tech']=self.decimal_reading()
c={'ts_code':CODE,'action':'OPEN','qty':100,'reason':'等待人工确认','hard_numbers':h}
with patch.object(ps.param_store,'get_int',return_value=60),\
patch.object(ps.param_store,'get_bool',return_value=False),\
patch.object(pms_repo,'get_proposal',return_value=None),\
patch.object(pms_repo,'execute',return_value=1) as execute:
ps._make_proposal(c,23.125,{'verdict':'UNAVAILABLE','confidence':0})
saved=json.loads(execute.call_args.args[1]['hn'])
self.assertEqual(saved['tech']['latest']['sar']['value'],23.125)
self.assertEqual(saved['tech']['stance'],h['tech']['stance'])
self.assertEqual(execute.call_args.args[1]['qty'],100)
def test_database_numeric_reading_can_be_saved_in_daily_confirmation(self):
from app.services import daily_buy_review as daily
h=hard();h['tech']=self.decimal_reading()
c={'ts_code':CODE,'action':'OPEN','qty':100,'hard_numbers':h,'confirm_why':'等待人工确认'}
ins={'instruction_id':'existing','ts_code':CODE,'action':'OPEN','progress':{}}
with patch.object(daily,'transaction',return_value=nullcontext()),\
patch.object(daily,'_save',return_value=True),\
patch.object(pms_repo,'get_proposal',return_value=None),\
patch.object(pms_repo,'execute',return_value=1) as execute:
self.assertTrue(daily._queue(ins,{'candidate':c,'verdict':{'verdict':'UNAVAILABLE'}},NOW))
saved=json.loads(execute.call_args.args[1]['hn'])
self.assertEqual(saved['tech']['latest']['boll']['upper'],23.125)
self.assertEqual(saved['daily_parent'],'existing')
self.assertEqual(execute.call_args.args[1]['qty'],100)
if __name__=='__main__':unittest.main()