akg-factor-bridge/test_plan_rank_switch.py

141 lines
6.4 KiB
Python
Raw Permalink Normal View History

"""排序切换的发布边界和研究池同源回归。全部来源使用替身。"""
import copy
import datetime as dt
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
import config
import plan
import plan_inputs as pi
import plan_versions as pv
import plan_rank_switch as rs
import pool
DAY = '2026-10-23'
NOW = dt.datetime.fromisoformat('2026-10-26T14:00:00+08:00')
class RankSwitchTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = self.tmp.name
p = patch.object(config, 'PLAN_SNAPSHOT_DIR', self.root)
p.start()
self.addCleanup(p.stop)
rows = [{'code': 'SH600001', 'name': '甲', 'score': 240, 'tier': '强传导',
'rank': 1, 'quality_band': 0, 'rank_axis': 'transmission', 'verdict': '关注'},
{'code': 'SH600002', 'name': '乙', 'score': 220, 'tier': '弱传导',
'rank': 2, 'quality_band': 3, 'rank_axis': 'transmission', 'verdict': '候选'}]
with pv.writer(self.root):
self.old = pv.publish(self.root, {'date': DAY, 'plan_version': 'test', 'main': rows,
'observe': [], 'candidates': [], 'watch': []}, {'records': {}, 'market': {}, 'regime': None},
{'PLAN_RANK_AXIS': 'transmission', 'CARD_SORT_BY_QUALITY': False},
cutoff_at='2026-10-26T07:10:00+08:00', reason='晨版')
p = patch.object(plan, 'collect', side_effect=self.collect)
self.collect_mock = p.start()
self.addCleanup(p.stop)
p = patch.object(plan, 'write_published_md')
p.start()
self.addCleanup(p.stop)
def collect(self, day, **kw):
rows = copy.deepcopy(self.old['main'])
axis = plan.config.PLAN_RANK_AXIS
if axis == 'quality':
rows.sort(key=lambda r: -r['quality_band'])
for i, row in enumerate(rows, 1):
row.update(rank=i, rank_axis=axis)
return {'date': day, 'plan_version': 'test', 'rank_axis': axis, 'main': rows,
'observe': [], 'candidates': [], 'watch': [], '_full': {'main': rows, 'observe': []}}
def switch(self, **kw):
return rs.switch(now=NOW, **kw)
def apply(self, **kw):
with patch.object(config, 'PLAN_RANK_AXIS', 'quality'), patch.object(config, 'CARD_SORT_BY_QUALITY', True):
return self.switch(apply=True, expected_decision_id=pv.load(self.root)['decision']['id'], **kw)
def files(self):
return {str(p): p.read_bytes() for p in Path(self.root).rglob('*.json')}
def test_preview_does_not_change_published_bytes(self):
before = self.files()
result = self.switch()
self.assertEqual(result['status'], 'preview')
self.assertEqual(result['first20'][0]['code'], 'SH600002')
self.assertEqual(before, self.files())
def test_apply_preserves_history_and_inputs_and_is_idempotent(self):
original = self.files()
result = self.apply()
self.assertEqual(result['status'], 'published')
self.assertEqual(result['decision']['parent_id'], self.old['decision']['id'])
self.assertEqual(result['input_hash'], self.old['decision']['input_hash'])
self.assertEqual(pv.load(self.root, decision_id=self.old['decision']['id']), self.old)
self.assertEqual(pv.load(self.root, DAY, morning=True), self.old)
for path, value in original.items():
if Path(path).name.startswith(DAY + '_') or Path(path).name == 'morning.json':
self.assertEqual(Path(path).read_bytes(), value)
self.assertEqual(self.apply()['status'], 'unchanged')
def test_missing_or_changed_expected_version_refuses_write(self):
before = self.files()
for expected in (None, 'another'):
with self.assertRaisesRegex(ValueError, '版本已变化'):
self.switch(apply=True, expected_decision_id=expected)
self.assertEqual(before, self.files())
def test_wrong_runtime_configuration_refuses_write(self):
with patch.object(config, 'PLAN_RANK_AXIS', 'transmission'), self.assertRaisesRegex(ValueError, '运行配置'):
self.switch(apply=True, expected_decision_id=self.old['decision']['id'])
def test_previous_decision_day_refuses_rewrite(self):
with self.assertRaisesRegex(ValueError, '历史计划只读'):
rs.switch(now=NOW + dt.timedelta(days=1))
def test_pending_research_refuses_switch(self):
pv.health(self.root, DAY, pending_codes=['SH600001'], error=None)
with self.assertRaisesRegex(ValueError, '修订尚未完成'):
self.switch()
def test_qualification_drift_refuses_publication(self):
def changed(*a, **kw):
data = self.collect(*a, **kw)
data['_full']['main'][0]['verdict'] = '仅展示'
return data
self.collect_mock.side_effect = changed
with self.assertRaisesRegex(ValueError, '改变资格或研究'):
self.apply()
self.assertEqual(pv.load(self.root)['decision']['id'], self.old['decision']['id'])
def test_swallowed_missing_frozen_input_still_fails(self):
def missing(*a, **kw):
try:
pi.read('missing.source', lambda: self.fail('不得回源'))
except RuntimeError:
pass
return self.collect(*a, **kw)
self.collect_mock.side_effect = missing
with self.assertRaisesRegex(RuntimeError, '冻结输入缺失'):
self.apply()
def test_pool_reads_published_plan_without_live_assembly(self):
data = dict(self.old, main=[dict(self.old['main'][1], pointed=True)], refresh_status={})
with patch.object(plan, 'from_snapshot', return_value=data) as reader, \
patch.object(plan, 'collect', side_effect=AssertionError('不得现场重装配')), \
patch.object(pool, '_read_holdings', return_value=set()), \
patch.object(pool, '_read_bad_signals', return_value=(set(), None)), \
patch.object(pool, 'config_mongo_ready', return_value=False), \
patch.object(config, 'POOL_SOURCE', 'rank'), patch.object(config, 'POOL_WATCH_SLICE', 0):
result = pool.push(dry_run=True)
self.assertEqual(set(result['pool']), {'SH600002'})
reader.assert_called_once()
if __name__ == '__main__':
unittest.main()