Files
Jyotisha/tests/test_handoff_2e5485f5_sync.py

282 lines
16 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Astrologer handoff branch 2e5485f5 (2026-11-07) regression witnesses, ported.
Source: yinduzhanxing handoff/product-parity-20261107 commits 9e971559, 9e62698e,
263092b3 and 2e5485f5 (tests/test_r37_followup_repairs.py,
tests/test_report_current_pd_activation.py, tests/test_yoga_card_promotion_gate.py),
plus rulings.md A1-A4, B10 and B11. Adapted tests carry 原值 / 新值 / 原因.
原因(全部):产品 2026-11-07 同步占星师交接分支 2e5485f5
"""
import json
from pathlib import Path
from types import SimpleNamespace
import pytest
from scripts import jyotish_engine as engine
from scripts import narayana_dasha as nd
# 原值(她的导入):from scripts.ashtakavarga import calc_sodhita_av
# 新值:从 scripts.ashtakavarga_shodhana 导入
# 原因:scripts/ashtakavarga.py 是冻结文件(tests/test_upstream_engine_sync_bug1699.py)
from scripts.ashtakavarga import SIGNS, calc_ashtakavarga, calc_yoga_pinda
from scripts.ashtakavarga_shodhana import calc_sodhita_av
from scripts.bhava_bala import RELATIVE_POINTS_PROFILE, reference_relative_points
from scripts.yoga_engine import YogaEngine, detect_yogas_with_status
ROOT = Path(__file__).resolve().parents[1]
RULES = ROOT / 'references/yoga_rules.json'
SEVEN = ('Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn')
# ---- A1 (her test_r37_followup_repairs.py, verbatim) ----
def test_sodhita_uses_classical_per_planet_reductions_without_threshold_labels():
planets = {p: {'sign': SIGNS[i]} for i, p in enumerate(SEVEN)}
bav = calc_ashtakavarga(planets, 0)['bav']
expected = calc_yoga_pinda(bav, planets, 0)
actual = calc_sodhita_av(bav, planets, 0)
assert actual['sodhita_bav'] == {p: expected['sodhita_rows'][p] for p in planets}
assert actual['prediction_scoring_allowed'] is False
assert all(row['level'] == 'not_calibrated' for row in actual['sodhita_sav']['assessment'])
assert actual['sodhita_sav']['total'] == sum(map(sum, actual['sodhita_bav'].values()))
def test_sodhita_without_seven_grahas_is_blocked_and_product_chain_is_labelled():
planets = {p: {'sign': SIGNS[i]} for i, p in enumerate(SEVEN)}
bav = calc_ashtakavarga(planets, 0)['bav']
partial = {p: row for p, row in bav.items() if p != 'Saturn'}
blocked = calc_sodhita_av(partial, planets, 0)
assert blocked['status'] == 'blocked' and blocked['sodhita_sav'] == {}
from scripts.ashtakavarga_shodhana import sodhita_chain
chain = sodhita_chain(bav, planets)
assert chain['prediction_scoring_allowed'] is False
assert all(row['level'] == 'not_calibrated' for row in chain['sodhita_sav']['assessment'])
assert chain['sodhita_bav'] == calc_sodhita_av(bav, planets, 0)['sodhita_bav']
# ---- A2 ----
def test_source_aware_narayana_uses_same_strength_for_seed_and_children(monkeypatch):
original = nd.select_narayana_seed_sign
profiles = []
def observe(*args, **kwargs):
profiles.append(kwargs.get('strength_profile', 'jaimini_lagna_seventh_strength_v1'))
return original(*args, **kwargs)
monkeypatch.setattr(nd, 'select_narayana_seed_sign', observe)
nd.narayana_report_with_variants(0, {
'Sun': 10., 'Moon': 45., 'Mars': 80., 'Mercury': 110.,
'Jupiter': 140., 'Venus': 170., 'Saturn': 200., 'Rahu': 230., 'Ketu': 50.})
assert profiles and set(profiles) == {'rath_empty_sign_lord_strength_v1'}
UPSTREAM_NARAYANA = ROOT.parent / 'up-run-h2/scripts/narayana_dasha.py'
@pytest.mark.skipif(not UPSTREAM_NARAYANA.exists(), reason='clean upstream export not on this machine')
def test_seed_selection_matches_her_function_on_random_charts():
import importlib.util
import random
spec = importlib.util.spec_from_file_location('upstream_nd_2e5485f5', UPSTREAM_NARAYANA)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
rng = random.Random(7)
names = ['Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn', 'Rahu']
reached = set()
for index in range(3000):
lons = {p: rng.uniform(0, 360) for p in names}
lons['Ketu'] = (lons['Rahu'] + 180) % 360
if index % 3 == 0: # empty Lagna / seventh more often
for p in ('Sun', 'Moon', 'Mercury', 'Venus'):
lons[p] = rng.choice([15, 75, 135, 195, 255, 315]) + rng.random()
lagna = rng.randrange(12)
for profile in ('jaimini_lagna_seventh_strength_v1', 'rath_empty_sign_lord_strength_v1'):
ours = nd.select_narayana_seed_sign(lagna, lons, strength_profile=profile)
theirs = module.select_narayana_seed_sign(lagna, lons, strength_profile=profile)
assert (ours['status'], ours.get('selected_sign_idx'), ours.get('selection_levels')) == \
(theirs['status'], theirs.get('selected_sign_idx'), theirs.get('selection_levels'))
reached.update(ours.get('selection_levels') or [])
assert {'empty_sign_modality', 'primary_lord_in_sign_degree'} <= reached
def test_empty_sign_tie_goes_to_modality_occupied_tie_stays_blocked():
# Gemini (dual) vs Sagittarius (dual), both empty, one role each → modality ties →
# lord degree: Mercury 20 deg in Leo vs Jupiter 5 deg in Leo → Gemini.
lons = {'Mercury': 140., 'Jupiter': 125., 'Sun': 5., 'Moon': 35., 'Mars': 95.,
'Venus': 185., 'Saturn': 215., 'Rahu': 275., 'Ketu': 95.}
new = nd.select_narayana_seed_sign(2, lons, strength_profile='rath_empty_sign_lord_strength_v1')
assert new['selection_levels'][2:] == ['empty_sign_modality', 'primary_lord_in_sign_degree']
assert new['status'] == 'selected' and new['selected_sign'] == 'Gemini'
assert nd.select_narayana_seed_sign(2, lons)['status'] == 'blocked' # default stops at two levels
occupied = dict(lons, Sun=65., Moon=245.) # one occupant each, roles unchanged
tied = nd.select_narayana_seed_sign(2, occupied, strength_profile='rath_empty_sign_lord_strength_v1')
assert tied['status'] == 'blocked' and 'empty_sign_modality' not in tied['selection_levels']
def test_role_profile_counts_jupiter_as_planet_and_lord_twice():
# Pisces: Jupiter in Pisces (conjunction) is both the Jupiter and the lord role.
lons = {'Jupiter': 345., 'Mercury': 100., 'Sun': 100., 'Moon': 160., 'Mars': 220.,
'Venus': 40., 'Saturn': 250., 'Rahu': 70., 'Ketu': 250.}
result = nd.select_narayana_seed_sign(5, lons, strength_profile='rath_empty_sign_lord_strength_v1')
roles = [f['role'] for f in result['candidates'][11]['role_factors']]
assert roles.count('jupiter') == 1 and roles.count('sign_lord') == 1
# Default profile is unchanged: one planet, aspect only.
assert 'role_factors' not in nd.select_narayana_seed_sign(5, lons)['candidates'][11]
def test_unsupported_strength_profile_is_rejected():
with pytest.raises(ValueError):
nd.select_narayana_seed_sign(0, {'Sun': 1.}, strength_profile='pvr_classical_lord_sign_strength_v1')
# ---- A3 (her test_r37_followup_repairs.py; adapted) ----
@pytest.mark.parametrize('operator', ['and', 'or', 'not'])
def test_unsupported_condition_cannot_be_hidden_by_boolean_short_circuit(operator):
# 原值(她的断言):detect 返回 1 行 formation_status=not_implemented
# 新值:本仓 detect 不把未实现规则放进 Yoga 列表,单列在 last_unimplemented /
# detect_yogas_with_status()['unimplemented_rules']
# 原因:本仓 2026-11-07 第三轮审查起未实现与求值失败都与成立列表分开
known = {'type': 'planet_in_house', 'planet': 'Sun', 'house': 1}
unknown = {'type': 'unimplemented_test_condition'}
logic = ({'type': 'not', 'condition': unknown} if operator == 'not' else
{'type': operator, 'conditions': [known, unknown]})
engine_ = YogaEngine(str(RULES))
engine_.rules = [{'id': 'test', 'name': 'Test', 'name_cn': '测试',
'logic': logic, 'effects': ['must not escape']}]
for house in (1, 2):
rows = engine_.detect({'Sun': {'sign': SIGNS[house - 1], 'house': house}}, 'Aries')
# 原值:assert all(row.get('rule_id') != 'test' for row in rows)
# 新值:她的断言——detect 返回 1 行 blocked 行(formation_status=not_implemented,无作用);
# 产品入口 detect_yogas / detect_yogas_with_status 照旧把它拿出 Yoga 列表
# 原因:BUG-2299/BUG-2301 照上游 58f37ee5b 的 detect 状态层
test_rows = [row for row in rows if row.get('rule_id') == 'test']
assert len(test_rows) == 1 and test_rows[0]['formation_status'] == 'not_implemented'
assert test_rows[0]['display_status'] == 'blocked' and test_rows[0]['effects'] == []
assert [r['rule_id'] for r in engine_.last_unimplemented] == ['test']
row = engine_.last_unimplemented[0]
assert row['formation_status'] == 'not_implemented'
assert row['unsupported_conditions'] == ['unimplemented_test_condition']
assert row['effects'] == [] and row['card_eligible'] is False
assert engine_.last_evaluation_failures == []
# BUG-2222 (upstream b6754475): Gaja, Parijatha, BVR Saraswathi, Rajju, Musala and
# Nala now have evaluators, so 71 - 6 = 65 rules remain not implemented.
NOW_IMPLEMENTED_2222 = {'bvr_gaja_yoga', 'bvr_parijatha_yoga', 'bvr_saraswathi_yoga',
'bvr_rajju_yoga', 'bvr_musala_yoga', 'bvr_nala_yoga'}
def test_her_71_rules_are_not_implemented():
hers = ROOT.parent / 'up-run-h2/handoff/2026-11-07/yoga_rules.json'
engine_ = YogaEngine(str(RULES))
ours = {row['rule_id'] for row in engine_.unimplemented_rules}
# 原值:65 条,含 bvr_apakeerthi_yoga
# 新值:1 条(bvr_anapathya_yoga)
# 原因:BUG-2301 接上占星师 58f37ee5b 的来源评估器(含 jada_apakeerti_raman)和她改过的规则;
# BUG-2302 取她的 bvr_maalavya_yoga 定义(PVR,可求值;本站仍 reference_only,由主检测器出结果)
assert ours == {'bvr_anapathya_yoga'}
assert not ours & NOW_IMPLEMENTED_2222
if hers.exists():
payload = json.loads(hers.read_text())
theirs = {r['rule_id'] for r in payload['rules']
if r['results']['jobs']['status'] == 'not_implemented'}
# 原值:ours == theirs - NOW_IMPLEMENTED_2222;新值:ours 是其子集(BUG-2301 又接上了她后来的评估器)
assert ours <= theirs - NOW_IMPLEMENTED_2222
def test_yoga_command_reports_not_implemented_count():
result = engine.cmd_yoga(SimpleNamespace(ascendant='Aries', planets='Sun:Aries:1:10'))
# 原值:65
# 新值:1(bvr_anapathya_yoga 仍含未实现条件类型)
# 原因:BUG-2301 接上占星师 58f37ee5b 的 35 个来源评估器和她改过的规则;BUG-2302 取她的 bvr_maalavya_yoga 定义
assert result['not_implemented_count'] == len(result['yoga_evaluation']['unimplemented_rules']) == 1
assert not {r['rule_id'] for r in result['yogas']} & {
r['rule_id'] for r in result['yoga_evaluation']['unimplemented_rules']}
def test_status_merges_runtime_unimplemented():
planets = {name: {'sign': SIGNS[i], 'house': i + 1, 'degree': 10.0} for i, name in enumerate(SEVEN)}
status = detect_yogas_with_status(planets, 'Aries')
# 原值:evaluation_status == 'unimplemented_rules_present'(没有求值失败的规则)
# 新值:'evaluation_failed_present';失败的只有 bvr_bandhubhisthyaktha_precise(Shashtiamsa 性质),状态是条件资料不全
# 原因:BUG-2298 照上游 58f37ee5b,D60 星座吉凶不再当作具名 Shashtiamsa 性质,Vaiseshikamsa 不再用自造的 0–20 分;缺来源定义时抛 MissingYogaInput
assert status['evaluation_status'] == 'evaluation_failed_present'
# BUG-2301:接上她的来源评估器后,缺度数 / 分盘 / Maandi 的规则也记为条件资料不全
assert ('bvr_bandhubhisthyaktha_precise', 'incomplete_conditions') in {
(row['rule_id'], row['condition_status']) for row in status['evaluation_failures']}
assert all(row['condition_status'] == 'incomplete_conditions' and row['missing_inputs']
for row in status['evaluation_failures'])
# 原值:65;新值:1;原因:BUG-2301 / BUG-2302(同上)
assert len(status['unimplemented_rules']) == 1
# ---- A4 (her test_r37_followup_repairs.py, verbatim) ----
def test_cancellation_label_does_not_claim_raja_yoga():
payload = json.loads(RULES.read_text())
rules = payload['rules'] if isinstance(payload, dict) else payload
rule = next(r for r in rules if r['id'] == 'neechabhanga_kendra')
# BUG-2303 原值(她的断言):'Neechabhanga Cancellation Candidate (Light on Life)'
# 新值:'Neecha Bhanga Cancellation (Kendra/Trikona Placement)'(她 formation contract 里的同一名称)
# 原因:这条规则现在对读者显示,BUG-2129 负责人裁定读者文字不出现书名
assert rule['name'] == 'Neecha Bhanga Cancellation (Kendra/Trikona Placement)'
assert rule['name_cn'] == '落陷化解(角宫/三方宫位置)' # BUG-2303:同上,读者文字不出现书名
assert 'Raja' not in rule['name']
assert '王' not in rule['name_cn']
assert rule['category'] == 'nicha_bhanga'
from scripts.yoga_engine import yoga_formation_contract
assert yoga_formation_contract('neechabhanga_kendra')['name'] == \
'Neecha Bhanga Cancellation (Kendra/Trikona Placement)'
# ---- 9e971559 native PD activation (her test_report_current_pd_activation.py) ----
def test_pratyantar_occupancy_is_visible_without_counting_a_new_system():
# 原值(她的断言):result['domain_evaluations']['wealth_family']
# 新值:本仓返回键为 domain_activations
# 原因:本仓 _calc_dasa_convergence 没有 domain_evaluations 别名
result = engine._calc_dasa_convergence(
{'current_dasha': {'mahadasha': {'lord': 'Jupiter'},
'antardasha': {'lord': 'Venus'},
'pratyantardasha': {'lord': 'Mercury'}}},
{}, {}, {'Jupiter': 32., 'Venus': 62., 'Mercury': 35.}, 0)
wealth = result['domain_activations']['wealth_family']
assert any(a['level'] == 'pratyantar' and a['planet'] == 'Mercury'
for a in wealth['activations'])
assert wealth['system_count'] == 1
def test_current_pd_is_read_from_native_nested_antardasha_timeline():
data = {'current_dasha': {'lord': 'Saturn', 'antardasha': {
'lord': 'Venus', 'pratyantar_dasha_timeline': [
{'lord': 'Mars', 'is_current': False},
{'lord': 'Jupiter', 'is_current': True}]}}}
result = engine._calc_dasa_convergence(data, {}, {}, {'Jupiter': 155.}, 4)
assert result['systems_summary']['vimshottari']['pratyantar'] == 'Jupiter'
assert any(a['level'] == 'pratyantar' for a in result['domain_activations']['wealth_family']['activations'])
def test_native_antardasha_record_now_counts_its_lord():
# 原值:原生 current_dasha 的 antardasha 是整条记录,只认字符串 → AD 静默不计
# 新值:取记录的 lord;summary 里的 antar 仍是原记录(orchestrator 读其日期)
data = {'current_dasha': {'mahadasha': 'Saturn', 'antardasha': {'lord': 'Venus', 'start': '2020-01-01'}}}
result = engine._calc_dasa_convergence(data, {}, {}, {'Venus': 35., 'Saturn': 200.}, 0)
assert result['systems_summary']['vimshottari']['antar']['start'] == '2020-01-01'
assert any(a['level'] == 'antar' and a['planet'] == 'Venus'
for a in result['domain_activations']['wealth_family']['activations'])
# ---- B11 ----
def test_relative_points_are_labelled_product_profile_and_kept_apart():
planets = {'Sun': {'sign': 'Leo', 'house': 1}, 'Jupiter': {'sign': 'Sagittarius', 'house': 5},
'Saturn': {'sign': 'Aquarius', 'house': 7}}
result = reference_relative_points(planets, 'Leo')
assert result['profile'] == RELATIVE_POINTS_PROFILE == 'product_relative_points_not_traditional'
assert result['traditional_standard'] is False and result['use_for_judgment'] is False
assert result['_meta']['score_unit'] == 'relative_points'
assert len(result['houses']) == 12
assert all(row['profile'] == RELATIVE_POINTS_PROFILE for row in result['houses'])
assert all('strength' not in row for row in result['houses'])
assert 'strongest_house' not in result and 'weakest_house' not in result