"""用户候选沿用原评估链路,不创建命令、不修改资格结论。""" import unit_test_guard import unittest from unittest.mock import patch, Mock from datetime import datetime from test_wiring import install_fakes from app.services import plan_feed as pf, plan_candidates as pc, tech_service as tech from app.core import plan_revision, consensus from config.settings import settings CODE='600001.SH' def payload(expiry='2099-01-01'): return {'date':'2026-11-02','decision':{'id':'v1'},'main':[ {'code':'SH600001','name':'甲','rank':2,'research_rank':2,'score':240,'verdict':'候选', 'user_candidate':{'id':'a'*32,'reason':'需求变化','expires_on':expiry},'user_required':True}, {'code':'SH600002','name':'乙','rank':1,'research_rank':1,'score':250,'verdict':'候选'}], 'observe':[], 'rank_axis':'quality'} class UserCandidateTests(unittest.TestCase): def setUp(self): self.fake=install_fakes(params={'PMS_PLAN_API_BASE':'http://plan.test','PMS_PLAN_TIERS':'', 'PMS_PLAN_MIN_UPSIDE':0,'PMS_PLAN_MIN_SCORE':0,'PMS_PLAN_TOP_N':30}) def test_source_passes_through_without_priority_or_score_change(self): plan=pf.parse_plan(payload()) rows=pf.select_candidates(plan,rank_by_upstream=True,top_n=2)['items'] self.assertEqual([r['ts_code'] for r in rows],['600002.SH',CODE]) self.assertEqual(rows[1]['score'],240) self.assertTrue(rows[1]['user_required']) self.assertEqual(pf.select_candidates(plan,rank_by_upstream=True,top_n=1)['items'][0]['ts_code'],'600002.SH') def test_expired_source_not_used_but_system_source_survives(self): plan=pf.parse_plan(payload('2000-01-01')) self.assertNotIn(CODE,[r['ts_code'] for r in pf.select_candidates(plan)['items']]) plan['main'][0]['user_required']=False self.assertIn(CODE,[r['ts_code'] for r in pf.select_candidates(plan)['items']]) def test_blacklist_and_display_still_reject_user_candidate(self): plan=pf.parse_plan(payload()) self.assertNotIn(CODE,[r['ts_code'] for r in pf.select_candidates(plan,black=[CODE])['items']]) plan['main'][0]['verdict']='仅展示' self.assertNotIn(CODE,[r['ts_code'] for r in pf.select_candidates(plan,route_by_verdict=True)['items']]) self.assertEqual(consensus.decide('无读数','看多','看多',fund_required=True)['route'],'跳过') self.assertEqual(consensus.decide('中性','看多','看空')['route'],'观察') def test_user_metadata_changes_invalidate_basis(self): row=pf.parse_plan(payload())['main'][0] old=plan_revision.basis(row) row['user_candidate']=dict(row['user_candidate'],id='b'*32) row['decision']={'id':'v2'} self.assertEqual(plan_revision.compare(old,row,CODE),'material') def test_command_source_does_not_gain_user_only_candidates(self): plan=pf.parse_plan(payload()) with patch.object(pf,'get_plan',return_value=plan): rows=pf.candidates(record=False,allow_user=False)['items'] self.assertNotIn(CODE,[r['ts_code'] for r in rows]) self.assertEqual(len(plan['main']),2) def test_plan_request_explicitly_declares_user_source_support(self): import requests response=Mock();response.json.return_value=payload() with patch.object(requests,'get',return_value=response) as get: pf.fetch(base='http://plan.test',path='/plan',timeout=3) self.assertEqual(get.call_args.kwargs['params']['include_user_candidates'],1) def test_proxy_secret_actor_failure_and_redirect(self): import requests from app.services import param_store self.assertIn('PMS_PLAN_WRITE_KEY',param_store.SECRET_KEYS) response=Mock(status_code=200) response.json.return_value={'ok':True,'added':1} with patch.object(settings,'PMS_PLAN_WRITE_KEY','test-key'),patch.object(requests,'request',return_value=response) as send: self.assertTrue(pc.request('POST',payload={'codes':['600001'],'actor':'冒名'},actor='会话用户')['ok']) self.assertEqual(send.call_args.kwargs['json']['actor'],'会话用户') self.assertEqual(send.call_args.kwargs['headers'],{'X-Job-Key':'test-key'}) self.assertFalse(send.call_args.kwargs['allow_redirects']) response.status_code=302 with self.assertRaises(ValueError):pc.request('POST') with patch.object(settings,'PMS_PLAN_WRITE_KEY',''),patch.object(requests,'request') as send: with self.assertRaises(ValueError):pc.request('POST') send.assert_not_called() def test_on_demand_technical_read_rejects_stale_or_missing_today(self): from app.repo import tech_repo with patch.object(tech_repo,'latest_date',return_value=20261102),patch.object(tech,'_tdays_elapsed',return_value=9): self.assertEqual(tech.read_states_for([CODE]),{}) with patch.object(tech_repo,'latest_date',return_value=20261102),patch.object(tech,'_tdays_elapsed',return_value=1),\ patch.object(tech.tradedays,'prev_trade_day',return_value=20261001),\ patch.object(tech_repo,'history_multi',return_value={CODE:[{'data_date':20261030}]}) as read: self.assertEqual(tech.read_states_for([CODE]),{}) self.assertEqual(read.call_args.args[0],[CODE]) def test_trader_route_and_server_actor(self): from app.web import auth, main self.assertNotEqual(auth.authz_decision('POST','/api/plan/user-candidates'),'admin') request=Mock();request.state.user={'username':'交易员甲'} with patch.object(pc,'request',return_value={'ok':True,'added':1}) as send, \ patch.object(main.pms_repo,'insert_op_log',return_value=1) as log: result=main.api_add_user_candidates(request,{'codes':['600001'],'by':'冒名'}) self.assertTrue(result['ok']);self.assertEqual(send.call_args.kwargs['actor'],'交易员甲') self.assertEqual(log.call_args.kwargs['by'],'交易员甲') if __name__=='__main__':unittest.main()