Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DbBXp2U3BH1SxwAGyhhbe1
238 lines
13 KiB
Python
238 lines
13 KiB
Python
"""Astrologer handoff branch 99076dad (2026-11-07) regression witnesses, ported.
|
||
|
||
Source: yinduzhanxing handoff/product-parity-20261107 commits 28823446 and
|
||
99076dad, tests/test_product_handoff_repairs.py and
|
||
tests/test_deterministic_chain_repairs.py. Tests kept verbatim where our API
|
||
matches hers; adapted ones carry 原值 / 新值 / 原因 comments.
|
||
原因(全部):产品 2026-11-07 同步占星师交接分支 99076dad
|
||
"""
|
||
import os
|
||
import subprocess
|
||
import sys
|
||
from datetime import datetime, timedelta
|
||
from pathlib import Path
|
||
from types import SimpleNamespace
|
||
|
||
import pytest
|
||
|
||
from scripts import bhava_bala
|
||
from scripts import jyotish_engine as engine
|
||
from scripts.ashtottari_dasha import calculate_ashtottari_dasha
|
||
from scripts.bhava_bala import bhava_bala_from_chart, calc_bhava_bala
|
||
from scripts.jaimini import _jaimini_stronger_planet
|
||
from scripts.narayana_dasha import get_current_narayana_dasha
|
||
from scripts.shadbala import calc_shadbala
|
||
from scripts.tajika import calc_tajika_strength_layers
|
||
from scripts.yoga_engine import YogaEngine, detect_yogas_with_status
|
||
|
||
ROOT = Path(__file__).resolve().parents[1]
|
||
RULES = ROOT / 'references/yoga_rules.json'
|
||
PLANETS7 = ('Sun', 'Moon', 'Mars', 'Mercury', 'Jupiter', 'Venus', 'Saturn')
|
||
|
||
|
||
# ---- verbatim from her test_product_handoff_repairs.py ----
|
||
|
||
@pytest.mark.parametrize('mode', ['legacy', 'mean', 'apparent'])
|
||
def test_bhava_midheaven_uses_the_natal_position_frame(mode):
|
||
# 原值:MC 由 houses_ex(flags | FLG_SIDEREAL) 直接取,与上升(热带减所选岁差)不同框架
|
||
# 新值:同一热带 flags、同一岁差偏移
|
||
engine._apply_ayanamsa('raman')
|
||
jd = engine.swe.julday(2026, 11, 7, 12.)
|
||
_, flags, offset = engine._sidereal_calculation_profile(jd, mode)
|
||
_, angles = engine.swe.houses_ex(jd, 28., 77., b'R', flags)
|
||
assert engine._bhava_midheaven_in_natal_frame(jd, 28., 77., mode) == pytest.approx((angles[1] - offset) % 360)
|
||
|
||
|
||
def test_chara_compares_dignity_at_actual_planet_locations():
|
||
# Already true here since BUG-1566 (each co-lord judged where it stands).
|
||
assert _jaimini_stronger_planet({'Saturn': 195., 'Mars': 105.}, 'Saturn', 'Mars', 9) == 'Saturn'
|
||
|
||
|
||
def test_drik_rounding_does_not_change_with_hash_seed():
|
||
# Already true here since BUG-1576 (sorted order, integer hundredths).
|
||
code = """from scripts.shadbala import calc_drik_bala_precise
|
||
p={n:{'degree':v} for n,v in zip(['Sun','Moon','Mars','Mercury','Jupiter','Venus','Saturn'],[184.942,172.24,239.539,29.653,104.63,30.78,354.355])}
|
||
print(calc_drik_bala_precise('Jupiter',p))"""
|
||
values = [subprocess.check_output([sys.executable, '-c', code], text=True, cwd=ROOT,
|
||
env={**os.environ, 'PYTHONHASHSEED': str(seed)}).strip() for seed in (1, 2, 3, 42)]
|
||
assert len(set(values)) == 1
|
||
|
||
|
||
def test_transit_restores_available_ephemeris_instead_of_resetting_it(monkeypatch):
|
||
paths = []
|
||
original = engine.swe.set_ephe_path
|
||
|
||
def record(path):
|
||
paths.append(path)
|
||
return original(path)
|
||
monkeypatch.setattr(engine.swe, 'set_ephe_path', record)
|
||
result = engine.cmd_transit(SimpleNamespace(year=2026, month=11, day=7, tz=8,
|
||
planet='Sun', node_mode='mean', position_mode='mean', ayanamsa='raman'))
|
||
assert not result.get('error')
|
||
assert paths and '' not in paths
|
||
|
||
|
||
def test_shadbala_requirement_ratio_is_explicitly_not_ishta_phala():
|
||
# 原值:只有 ishta_bala_pct(总 Rupa ÷ 最低要求 × 100)
|
||
# 新值:另给 required_strength_pct(同值),ishta_bala_pct 标为旧名别名
|
||
# 与她的不同:她改在 calc_shadbala 里;本仓 shadbala.py 冻结(BUG-1699),由
|
||
# shadbala_display.attach_required_strength_alias 在 cmd_shadbala / 全读 / API 上补。
|
||
from scripts.shadbala_display import attach_required_strength_alias
|
||
planets = {p: {'sign': 'Aries', 'house': 1, 'degree': i * 3.0} for i, p in enumerate(PLANETS7)}
|
||
result = attach_required_strength_alias(calc_shadbala(planets, 'Aries', 12., 0., 3.))
|
||
for row in result['planets'].values():
|
||
assert row['required_strength_pct'] == row['ishta_bala_pct']
|
||
assert row['ishta_bala_pct_semantics'] == 'deprecated_alias_of_required_strength_pct_not_ishta_phala'
|
||
assert 'ishta_phala' in row
|
||
|
||
|
||
# ---- from her test_deterministic_chain_repairs.py ----
|
||
|
||
@pytest.mark.parametrize('expr', ['missing_helper()', 'if True:\n missing_helper()', 'if :'])
|
||
def test_yoga_evaluation_failure_is_visible_not_a_negative_match(expr):
|
||
# 原值(她的断言):detect() 行内 formation_status == 'evaluation_error'
|
||
# 新值:本仓 BUG-1571 把失败单列在 evaluation_failures(condition_status = evaluation_failed),
|
||
# 不进入 yogas,所以既不算成立也不算不成立
|
||
engine_ = YogaEngine(str(RULES))
|
||
engine_.rules = [{'id': 'broken', 'name': 'Broken', 'name_cn': '测试',
|
||
'effects': ['must not escape'], 'effects_en': ['must not escape'],
|
||
'logic': {'type': 'custom', 'expr': expr}}]
|
||
# 原值:engine_.detect(...) == []
|
||
# 新值:detect 照她的写法只留一行 blocked 行(formation_status=evaluation_error,无作用);产品入口照旧不列它
|
||
# 原因:BUG-2299 同步她的 detect 状态层
|
||
[row] = engine_.detect({}, 'Aries')
|
||
assert row['formation_status'] == 'evaluation_error' and row['display_status'] == 'blocked'
|
||
assert row['effects'] == [] and row['planets'] == []
|
||
[failure] = engine_.last_evaluation_failures
|
||
assert failure['rule_id'] == 'broken'
|
||
assert failure['condition_status'] == 'evaluation_failed'
|
||
assert 'effects' not in failure
|
||
|
||
|
||
def test_amala_renamed_helper_reaches_real_match():
|
||
# 原值(她的断言):rows[0]['formation_status'] == 'conditions_met'
|
||
# 新值:本仓成立的行不带 formation_status,断言规则出现在结果里
|
||
engine_ = YogaEngine(str(RULES))
|
||
engine_.rules = [r for r in engine_.rules if r['id'] == 'bvr_amala_precise']
|
||
rows = engine_.detect({'Jupiter': {'sign': 'Capricorn', 'house': 10}}, 'Aries')
|
||
assert [r['rule_id'] for r in rows] == ['bvr_amala_precise']
|
||
|
||
|
||
@pytest.mark.parametrize('ascendant', bhava_bala.SIGNS)
|
||
def test_enabled_yoga_library_has_no_runtime_errors_on_complete_synthetic_chart(ascendant):
|
||
planets = {name: {'sign': bhava_bala.SIGNS[i], 'house': (i - bhava_bala.SIGNS.index(ascendant)) % 12 + 1, 'degree': 10.0}
|
||
for i, name in enumerate(PLANETS7 + ('Rahu', 'Ketu'))}
|
||
status = detect_yogas_with_status(planets, ascendant)
|
||
# 原值:evaluation_failures == []
|
||
# 新值:没有运行异常;只允许条件资料不全(她的 Shashtiamsa / Vaiseshikamsa 不再用代用分数)
|
||
# 原因:BUG-2298 照上游 58f37ee5b
|
||
assert [row for row in status['evaluation_failures'] if row['condition_status'] != 'incomplete_conditions'] == []
|
||
|
||
|
||
def test_yoga_command_reports_evaluation_error_count(monkeypatch):
|
||
# 原值:cmd_yoga 只在 yoga_evaluation.evaluation_failures 里列失败
|
||
# 新值:另给她的同名计数 evaluation_error_count;失败不计入 yogas_detected
|
||
failure = {'rule_id': 'x', 'condition_status': 'evaluation_failed', 'error_class': 'NameError'}
|
||
monkeypatch.setattr(engine, 'detect_yogas_with_status', lambda *a, **kw: {
|
||
'yogas': [], 'rules_evaluated': 1, 'evaluation_failures': [failure],
|
||
'unimplemented_rules': [], 'evaluation_status': 'evaluation_failed_present'})
|
||
result = engine.cmd_yoga(SimpleNamespace(ascendant='Aries', planets='Sun:Aries:1:10'))
|
||
assert result['yogas_detected'] == 0
|
||
assert result['evaluation_error_count'] == 1
|
||
assert result['detected_yogas'] == []
|
||
|
||
|
||
ASHTOTTARI_INPUTS = {
|
||
'moon_nakshatra_index': 18, 'is_shukla_paksha': False, 'moon_longitude': 249.0,
|
||
'birth_is_daytime': True, 'rahu_sign_index': 5, 'lagna_lord_sign_index': 11,
|
||
'applicability_rule_family': 'rahu_from_lagna_lord_kendra_trikona_plus_paksha_daynight',
|
||
}
|
||
|
||
|
||
def test_ashtottari_birth_balance_controls_md_ad_and_current_dates():
|
||
# 原值:本仓结果没有 dasha_balance_at_birth / dasha_at_birth(报告读这两个字段,一直是空)
|
||
# 新值:与她同名输出;时间轴本来就按余额前移(BUG-1344 / BUG-1475)
|
||
birth = datetime(2000, 1, 1)
|
||
result = calculate_ashtottari_dasha({**ASHTOTTARI_INPUTS, 'birth_datetime': birth, 'as_of': birth})
|
||
assert result['timeline_basis'] == 'birth_balance_adjusted'
|
||
expected_end = birth + timedelta(days=result['dasha_balance_at_birth']['years'] * 365.25)
|
||
first = result['major'][0]
|
||
assert abs(datetime.fromisoformat(first['end_date']) - expected_end) < timedelta(seconds=1)
|
||
assert datetime.fromisoformat(first['start_date']) < birth
|
||
assert result['current']['end_date'] == first['end_date']
|
||
ads = [p for p in result['antardasha'] if datetime.fromisoformat(p['start_date']) <= birth < datetime.fromisoformat(p['end_date'])]
|
||
assert len(ads) == 1
|
||
assert ads[0]['planet'] == result['dasha_at_birth']['lords'][1]
|
||
pds = [p for p in result['pratyantardasha'] if datetime.fromisoformat(p['start_date']) <= birth < datetime.fromisoformat(p['end_date'])]
|
||
assert len(pds) == 1
|
||
assert pds[0]['planet'] == result['dasha_at_birth']['lords'][2]
|
||
|
||
|
||
def test_ashtottari_balance_adjusted_cycle_boundary_has_no_gap():
|
||
# 原值:周期序号按出生时刻算,第一轮结束到 108 岁生日之间 current = None
|
||
# 新值:按第一段大运起点算,边界前后首尾相接
|
||
birth = datetime(2000, 1, 1)
|
||
inputs = {**ASHTOTTARI_INPUTS, 'birth_datetime': birth, 'as_of': birth}
|
||
initial = calculate_ashtottari_dasha(inputs)
|
||
boundary = datetime.fromisoformat(initial['major'][-1]['end_date'])
|
||
before = calculate_ashtottari_dasha({**inputs, 'as_of': boundary - timedelta(seconds=1)})['current']
|
||
after = calculate_ashtottari_dasha({**inputs, 'as_of': boundary})['current']
|
||
assert before['cycle_number'] == 1
|
||
assert after['cycle_number'] == 2
|
||
assert before['end_date'] == after['start_date']
|
||
assert after['antardasha'][0]['start_date'] == after['start_date']
|
||
|
||
|
||
@pytest.mark.parametrize('age', [-1, 4 + 8, 200])
|
||
def test_narayana_does_not_replay_first_cycle_outside_coverage(age):
|
||
# 原值:((age − start) % 144) + start,出生前 / 两轮之后绕回第一轮
|
||
# 新值:时间轴外 md = None,status = outside_generated_timeline
|
||
# 与她的不同:本仓自己生成第二轮(BUG-1545,12 − 首轮年数),所以只有一行 4 年时
|
||
# 覆盖 0–12 岁(她的函数只看传入的行,覆盖 0–4 岁)。
|
||
rows = [{'sign': 'Aries', 'sign_idx': 0, 'lord': 'Mars', 'years': 4, 'start_age': 0, 'end_age': 4}]
|
||
result = get_current_narayana_dasha(rows, age)
|
||
assert result['md'] is None
|
||
assert result['status'] == 'outside_generated_timeline'
|
||
|
||
|
||
def test_narayana_second_cycle_is_selected_not_replayed():
|
||
rows = [{'sign': 'Aries', 'sign_idx': 0, 'lord': 'Mars', 'years': 4, 'start_age': 0, 'end_age': 4}]
|
||
result = get_current_narayana_dasha(rows, 9)
|
||
assert result['status'] == 'selected'
|
||
assert result['md']['cycle'] == 2 and result['md']['years'] == 8
|
||
|
||
|
||
def test_harsha_unknown_daynight_is_missing_not_zero():
|
||
# 原值(她的断言):status == 'incomplete_inputs'
|
||
# 新值:本仓状态名沿用 'incomplete'(第三轮审查已有测试),另给她的同名
|
||
# missing_inputs / score_range
|
||
result = calc_tajika_strength_layers({'Sun': 10.0}, 0.0, is_daytime=None)
|
||
row = result['harsha_bala']['Sun']
|
||
assert row['score'] is None
|
||
assert row['components']['fourth_bala'] is None
|
||
assert row['status'] == 'incomplete'
|
||
assert row['missing_inputs'] == ['is_daytime']
|
||
assert row['score_range'][1] - row['score_range'][0] == 5.0
|
||
assert row['max_score'] == 20.0
|
||
assert result['combined_strength']['Sun']['status'] == 'blocked'
|
||
|
||
|
||
def test_bhava_raw_totals_have_no_unvalidated_absolute_grade():
|
||
# 原值:level 按 20/30/40/50/60 分档(合计 300–650 Virupa 时每宫都是「极强」)
|
||
# 新值:level = not_assessed
|
||
result = calc_bhava_bala(['Aries'] * 12, [15.0] * 12, 'Aries', 15.0,
|
||
{'Sun': {'sign': 'Aries', 'degree': 10.0}}, {'Mars': 400.0})
|
||
assert all(row['level'] == 'not_assessed' for row in result['houses'])
|
||
assert all(row['total'] == round(row['adhipathi_bala'] + row['dig_bala'] + row['drik_bala'], 2) for row in result['houses'])
|
||
|
||
|
||
def test_bhava_primary_output_is_virupas():
|
||
# 原值:bhava_bala_from_chart 只有 score_unit / unit,没有 _meta
|
||
# 新值:她的 _meta.score_unit = 'Virupas';宫行不带等级
|
||
planets = {p: {'sign': bhava_bala.SIGNS[i], 'degree': 10.0} for i, p in enumerate(PLANETS7)}
|
||
shadbala_rows = {p: {'total_virupas': 400.0 + i} for i, p in enumerate(PLANETS7)}
|
||
result = bhava_bala_from_chart(planets, 'Aries', 15.0, shadbala_rows)
|
||
assert result['_meta']['score_unit'] == 'Virupas'
|
||
assert result['_meta']['house_count'] == 12
|
||
assert all('level' not in row and 'level_status' not in row for row in result['houses'])
|