211 lines
10 KiB
Python
211 lines
10 KiB
Python
|
|
"""本地:python3 -m unittest test_dividend_watch;纯标准库,无网络或数据库。"""
|
|||
|
|
import copy
|
|||
|
|
import datetime as dt
|
|||
|
|
import json
|
|||
|
|
from pathlib import Path
|
|||
|
|
import tempfile
|
|||
|
|
import unittest
|
|||
|
|
from unittest.mock import patch
|
|||
|
|
|
|||
|
|
import dividend_watch as d
|
|||
|
|
import dividend_sources as s
|
|||
|
|
|
|||
|
|
|
|||
|
|
def source():
|
|||
|
|
return {'captured_at': '2026-10-21T08:00:00+08:00', 'expected_date': '2026-10-20',
|
|||
|
|
'data_date': '2026-10-20', 'table': 'gp_stock_factor_pro_202610',
|
|||
|
|
'factors': [{'ts_code': '600001.SH', 'trade_date': '2026-10-20', 'dv_ttm': 5, 'dv_ratio': 9, 'close': 10}],
|
|||
|
|
'names': [{'gp_code_two': '600001.SH', 'gp_name': '示例公司', 'list_status': 'L'}],
|
|||
|
|
'reviews': [], 'fundamentals': {}}
|
|||
|
|
|
|||
|
|
|
|||
|
|
def reviewed(q='好'):
|
|||
|
|
x = source()
|
|||
|
|
x['reviews'] = [{'ts_code': '600001.SH', 'ran_at': '2026-10-20T09:00:00+08:00',
|
|||
|
|
'period_fi': '2026Q1', 'period_rf': '2026Q2', 'grades': {'buffett': '好', 'earnings_quality': '差'},
|
|||
|
|
'summary': {'overall': q, 'thesis': '盈利稳定', 'antithesis': '现金转化下降', 'unknown_n': 3}}]
|
|||
|
|
return x
|
|||
|
|
|
|||
|
|
|
|||
|
|
class ClassificationTest(unittest.TestCase):
|
|||
|
|
def test_risk_variants(self):
|
|||
|
|
for name in ['ST公司', '*ST公司', 'ST公司', 'S*ST公司', 'SST公司', 'XDst公司', 'XR* ST公司', '退市公司', '公司退']:
|
|||
|
|
with self.subTest(name=name): self.assertTrue(d.risk_name(name))
|
|||
|
|
self.assertFalse(d.risk_name('厦门国贸'))
|
|||
|
|
|
|||
|
|
def test_st_before_any_yield(self):
|
|||
|
|
x = source(); x['names'][0]['gp_name'] = '*ST公司'; x['factors'][0]['dv_ttm'] = None
|
|||
|
|
self.assertEqual(d.assemble(x)['rows'][0]['status'], 'excluded')
|
|||
|
|
self.assertEqual(d.candidates(x), [])
|
|||
|
|
|
|||
|
|
def test_missing_name_never_passes(self):
|
|||
|
|
x = source(); x['names'][0]['gp_name'] = ''
|
|||
|
|
self.assertEqual(d.assemble(x)['rows'][0]['status'], 'identity_unknown')
|
|||
|
|
self.assertEqual(d.candidates(x), [])
|
|||
|
|
|
|||
|
|
def test_listing_status_unknown_and_delisted(self):
|
|||
|
|
for v, expected in [(None, 'identity_unknown'), ('D', 'excluded')]:
|
|||
|
|
x = source(); x['names'][0]['list_status'] = v
|
|||
|
|
self.assertEqual(d.assemble(x)['rows'][0]['status'], expected)
|
|||
|
|
|
|||
|
|
def test_boundary_and_missing_not_previous_year(self):
|
|||
|
|
for value, expected in [(5, 'missing_review'), (4.9999, 'below'), (None, 'yield_unknown'), ('NaN', 'yield_unknown')]:
|
|||
|
|
x = source(); x['factors'][0]['dv_ttm'] = value
|
|||
|
|
self.assertEqual(d.assemble(x)['rows'][0]['status'], expected)
|
|||
|
|
|
|||
|
|
def test_good_not_sustainability_approval(self):
|
|||
|
|
r = d.assemble(reviewed())['rows'][0]
|
|||
|
|
self.assertEqual(r['status'], 'priority'); self.assertFalse(r['investment_approved'])
|
|||
|
|
self.assertEqual(r['sustainability'], '待核验')
|
|||
|
|
|
|||
|
|
def test_bad_and_divided(self):
|
|||
|
|
self.assertEqual(d.assemble(reviewed('差'))['rows'][0]['status'], 'risk')
|
|||
|
|
self.assertEqual(d.assemble(reviewed('中'))['rows'][0]['status'], 'mixed')
|
|||
|
|
|
|||
|
|
def test_opposing_view_and_material_age_preserved(self):
|
|||
|
|
r = d.assemble(reviewed())['rows'][0]
|
|||
|
|
self.assertEqual(r['antithesis'], '现金转化下降')
|
|||
|
|
self.assertEqual(r['perspectives']['earnings_quality'], '差')
|
|||
|
|
self.assertTrue(any('2026Q2' in n for n in r['needs']))
|
|||
|
|
|
|||
|
|
def test_quarter_review_due(self):
|
|||
|
|
x = reviewed(); x['reviews'][0]['ran_at'] = '2026-09-30T09:00:00+08:00'
|
|||
|
|
self.assertIn('本季度尚无完整评析更新', d.assemble(x)['rows'][0]['needs'])
|
|||
|
|
|
|||
|
|
def test_future_review_rejected(self):
|
|||
|
|
x = reviewed(); x['reviews'][0]['ran_at'] = '2026-10-21T09:00:00+08:00'
|
|||
|
|
with self.assertRaises(ValueError): d.assemble(x)
|
|||
|
|
|
|||
|
|
def test_duplicate_source_rejected(self):
|
|||
|
|
for key in ('factors', 'names'):
|
|||
|
|
x = source(); x[key].append(copy.deepcopy(x[key][0]))
|
|||
|
|
with self.assertRaises(ValueError): d.assemble(x)
|
|||
|
|
|
|||
|
|
def test_stale_mixed_dates_and_month_table(self):
|
|||
|
|
for change in ({'expected_date': '2026-10-21'}, {'table': 'gp_stock_factor_pro_202609'}, {'data_date': '2026-10-21'}):
|
|||
|
|
x = source(); x.update(change)
|
|||
|
|
with self.assertRaises(ValueError): d.assemble(x)
|
|||
|
|
|
|||
|
|
def test_timezone_required(self):
|
|||
|
|
x = source(); x['captured_at'] = '2026-10-21T08:00:00'
|
|||
|
|
with self.assertRaises(ValueError): d.assemble(x)
|
|||
|
|
|
|||
|
|
def test_november_uses_october_data_table(self):
|
|||
|
|
x = source(); x.update(captured_at='2026-11-02T08:00:00+08:00', expected_date='2026-10-30',data_date='2026-10-30')
|
|||
|
|
x['factors'][0]['trade_date'] = '2026-10-30'
|
|||
|
|
self.assertEqual(d.assemble(x)['source_table'], 'gp_stock_factor_pro_202610')
|
|||
|
|
|
|||
|
|
def test_deterministic_rows(self):
|
|||
|
|
x = source(); second = dict(x['factors'][0], ts_code='600002.SH'); x['factors'].append(second)
|
|||
|
|
a = d.assemble(x); x['factors'].reverse()
|
|||
|
|
self.assertEqual(a, d.assemble(x))
|
|||
|
|
|
|||
|
|
def test_report_escapes_untrusted_prose(self):
|
|||
|
|
x = reviewed(); x['reviews'][0]['summary']['thesis'] = '<img src=x onerror=alert(1)>'
|
|||
|
|
text = d.report(d.assemble(x))
|
|||
|
|
self.assertNotIn('<img', text); self.assertIn('<img', text)
|
|||
|
|
|
|||
|
|
|
|||
|
|
class CadenceTest(unittest.TestCase):
|
|||
|
|
def test_monthly_cache_reuse(self):
|
|||
|
|
old = {'fundamentals': {'600001.SH': {'checked_at': '2026-10-01T08:00:00+08:00'}}}
|
|||
|
|
self.assertEqual(d.refresh_codes(source(), old), [])
|
|||
|
|
|
|||
|
|
def test_new_month_and_new_candidate_due(self):
|
|||
|
|
self.assertEqual(d.refresh_codes(source(), None), ['600001.SH'])
|
|||
|
|
old = {'fundamentals': {'600001.SH': {'checked_at': '2026-09-30T08:00:00+08:00'}}}
|
|||
|
|
self.assertEqual(d.refresh_codes(source(), old), ['600001.SH'])
|
|||
|
|
|
|||
|
|
def test_announcement_cutoff_and_missing(self):
|
|||
|
|
rows = [{'ann_date': 20261021}, {'ann_date': 20261022}, {'ann_date': None}, {'ann_date': 20261020, 'f_ann_date': 20261022}]
|
|||
|
|
r = s.public_rows(rows, dt.date(2026,10,21))
|
|||
|
|
self.assertEqual(len(r['records']), 1); self.assertEqual(len(r['quarantined']), 3)
|
|||
|
|
self.assertFalse(r['completeness_verified'])
|
|||
|
|
|
|||
|
|
def test_financial_source_order_stable(self):
|
|||
|
|
rows = [{'ann_date': 20260101, 'x': 1}, {'ann_date': 20260101, 'x': 2}]
|
|||
|
|
self.assertEqual(s.public_rows(rows, dt.date(2026,10,21)), s.public_rows(rows[::-1], dt.date(2026,10,21)))
|
|||
|
|
|
|||
|
|
def test_report_cache_no_network(self):
|
|||
|
|
v = reviewed()['reviews'][0]
|
|||
|
|
identity = d.digest({k: v.get(k) for k in ('ran_at','summary','grades')})
|
|||
|
|
old = {'report_capture': {'identity': identity, 'status': 'ok', 'markdown': '原文'}}
|
|||
|
|
with patch('urllib.request.urlopen', side_effect=AssertionError('no network')):
|
|||
|
|
self.assertEqual(s.report_read('600001.SH', v, old, 'http://unused'), old['report_capture'])
|
|||
|
|
|
|||
|
|
def test_unavailable_report_not_claimed_full(self):
|
|||
|
|
with patch('urllib.request.urlopen', side_effect=OSError('down')):
|
|||
|
|
r = s.report_read('600001.SH', reviewed()['reviews'][0], None, 'http://unused')
|
|||
|
|
self.assertEqual(r['traceability'], 'summary_only')
|
|||
|
|
self.assertNotIn('markdown', r)
|
|||
|
|
|
|||
|
|
|
|||
|
|
class PublishTest(unittest.TestCase):
|
|||
|
|
def setUp(self):
|
|||
|
|
self.tmp = tempfile.TemporaryDirectory(); self.root = Path(self.tmp.name)
|
|||
|
|
def tearDown(self): self.tmp.cleanup()
|
|||
|
|
|
|||
|
|
def test_repeated_input_idempotent(self):
|
|||
|
|
x = source(); a, changed = d.publish(self.root, x); self.assertTrue(changed)
|
|||
|
|
x['captured_at'] = '2026-10-21T09:00:00+08:00'
|
|||
|
|
b, changed = d.publish(self.root, x); self.assertFalse(changed); self.assertEqual(a, b)
|
|||
|
|
|
|||
|
|
def test_changed_view_keeps_old_archive(self):
|
|||
|
|
a, _ = d.publish(self.root, reviewed()); old = (self.root/'versions'/a['id']/'bundle.json').read_bytes()
|
|||
|
|
b, _ = d.publish(self.root, reviewed('差'))
|
|||
|
|
self.assertEqual(b['parent_id'], a['id'])
|
|||
|
|
self.assertEqual((self.root/'versions'/a['id']/'bundle.json').read_bytes(), old)
|
|||
|
|
|
|||
|
|
def test_bad_source_keeps_pointer(self):
|
|||
|
|
a, _ = d.publish(self.root, source()); x = source(); x['factors'] = []
|
|||
|
|
with self.assertRaises(ValueError): d.publish(self.root, x)
|
|||
|
|
self.assertEqual(d.read_latest(self.root)['id'], a['id'])
|
|||
|
|
|
|||
|
|
def test_interrupted_publish_and_recovery(self):
|
|||
|
|
a, _ = d.publish(self.root, source()); write = d.atomic
|
|||
|
|
def fail_pointer(path, data):
|
|||
|
|
if Path(path).name == 'latest.json': raise OSError('interrupted')
|
|||
|
|
return write(path, data)
|
|||
|
|
with patch.object(d, 'atomic', side_effect=fail_pointer):
|
|||
|
|
with self.assertRaises(OSError): d.publish(self.root, reviewed())
|
|||
|
|
self.assertEqual(d.read_latest(self.root)['id'], a['id'])
|
|||
|
|
b, _ = d.publish(self.root, reviewed()); self.assertNotEqual(a['id'], b['id'])
|
|||
|
|
|
|||
|
|
def test_corruption_detected(self):
|
|||
|
|
a, _ = d.publish(self.root, source())
|
|||
|
|
(self.root/'versions'/a['id']/'bundle.json').write_text('{}')
|
|||
|
|
self.assertFalse(d.health(self.root, '2026-10-20')['ok'])
|
|||
|
|
|
|||
|
|
def test_health_requires_successful_check(self):
|
|||
|
|
bundle, _ = d.publish(self.root, source()); self.assertFalse(d.health(self.root, '2026-10-20')['ok'])
|
|||
|
|
d.atomic(self.root/'last_check.json', d.encode({'ok':True, 'id': bundle['id']}))
|
|||
|
|
self.assertTrue(d.health(self.root, '2026-10-20')['ok'])
|
|||
|
|
self.assertFalse(d.health(self.root, '2026-10-21')['ok'])
|
|||
|
|
d.atomic(self.root/'last_check.json', d.encode({'ok':False}))
|
|||
|
|
self.assertFalse(d.health(self.root, '2026-10-20')['ok'])
|
|||
|
|
|
|||
|
|
|
|||
|
|
class IntegrationContractTest(unittest.TestCase):
|
|||
|
|
def test_business_defaults_unchanged_and_explicit_entry(self):
|
|||
|
|
import ast
|
|||
|
|
tree = ast.parse(Path('xxl.py').read_text())
|
|||
|
|
values = {}
|
|||
|
|
for node in tree.body:
|
|||
|
|
if isinstance(node, ast.Assign):
|
|||
|
|
for target in node.targets:
|
|||
|
|
if isinstance(target, ast.Name) and target.id in ('DEFAULT_STEPS', 'STEP_ORDER', 'STEP_CMDS'):
|
|||
|
|
values[target.id] = ast.literal_eval(node.value)
|
|||
|
|
self.assertEqual(values['DEFAULT_STEPS'], ('build','plan','push-pool'))
|
|||
|
|
self.assertNotIn('dividend-watch', values['STEP_ORDER'])
|
|||
|
|
self.assertNotIn('dividend-watch', values['STEP_CMDS'])
|
|||
|
|
|
|||
|
|
def test_read_query_cannot_collect_or_publish(self):
|
|||
|
|
import ast
|
|||
|
|
tree = ast.parse(Path('api.py').read_text())
|
|||
|
|
fn = next(x for x in tree.body if isinstance(x, ast.FunctionDef) and x.name == 'dividend_research')
|
|||
|
|
calls = [n.func.attr for n in ast.walk(fn) if isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute)]
|
|||
|
|
self.assertNotIn('collect', calls); self.assertNotIn('publish', calls)
|
|||
|
|
|
|||
|
|
|
|||
|
|
if __name__ == '__main__': unittest.main()
|