Files
Jyotisha/tests/test_shadbala_service_api.py
T
ClaudeandClaude Opus 5.5 5d64f71b81 fix: astrologer round-5 rulings 2/3/4/5/10/13 (BUG-1746..1752)
- Functional default = PVR Table 30 (functional_profile=pvr_table_30); the former
  product table is bphs_exception_profile, scored only when named (rectification
  names it, scores unchanged). profile_divergence shows both roles side by side;
  movable-lagna Moon by the table's paksha note; dual-lordship note; prior rulings
  BUG-1570/1590/#166 Q4 checked against Table 30.
- Shadbala: six open items labelled parameter_sensitive; every option combination
  computed; only planets whose pass/fail flips get minimum_check=parameter_sensitive.
- Vimshottari AD/PD rows carry parent_period_start / visible_period_start; the
  consult card cuts the balance MD from its full parent and clips at birth.
- KP DBA: full first parent, clipped at birth (no balance rescale).
- Mudda: balance fields + balance_method (angle default, time comparison apart),
  nominal_year_days, her crossing wording; Harsha combined blocked reason lists items.
- D30 _meta describes the unequal parts (as her r40).
- Golden recaptured with TTL=0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXoyn7Hj3LCW3BUs5bZ8
2026-11-08 11:57:22 +08:00

183 lines
8.9 KiB
Python
Raw 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.
"""BUG-1463: `/api/shadbala` with the birth moment returned 500 (`NameError: swe`).
The endpoint now lives in scripts/shadbala_service/api.py and the handler only
forwards the body. These tests go through the real HTTP handler on a local
port, so the regression is caught at the same surface the caller saw.
Birth data is the fictional golden profile shared with the frontend tests
(1990-06-15 12:00 Beijing, raman).
"""
from __future__ import annotations
import json
import socket
import subprocess
import sys
import threading
import urllib.error
import urllib.request
from http.server import ThreadingHTTPServer
from pathlib import Path
from typing import Any
import pytest
import swisseph as swe
ROOT = Path(__file__).resolve().parents[1]
SCRIPTS = ROOT / "scripts"
for path in (ROOT, SCRIPTS):
if str(path) not in sys.path:
sys.path.insert(0, str(path))
from scripts.api_heavy_compute_gate import reset_heavy_compute_gate # noqa: E402
from scripts.shadbala import build_shadbala_context, calc_dig_bala_precise # noqa: E402
GOLDEN = json.loads((ROOT / "frontend" / "tests" / "fixtures" / "chart-insight-golden.json").read_text(encoding="utf-8"))
PLANETS = GOLDEN["chart"]["planets"]
ASCENDANT = GOLDEN["chart"]["ascendant"]
BIRTH = {
"year": 1990, "month": 6, "day": 15, "hour": 12, "minute": 0, "second": 0,
"lat": 39.9042, "lon": 116.4074, "tz": 8, "ayanamsa": "raman",
}
SEVEN = ("Sun", "Moon", "Mars", "Mercury", "Jupiter", "Venus", "Saturn")
@pytest.fixture(scope="module")
def api_base():
import os
from scripts.jyotish_api_server import DEFAULT_ALLOWED_HOSTS, DEFAULT_ALLOWED_ORIGINS, JyotishAPIHandler
previous = os.environ.get("JYOTISH_API_RATE_LIMIT_PER_MINUTE")
os.environ["JYOTISH_API_RATE_LIMIT_PER_MINUTE"] = "0"
reset_heavy_compute_gate()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
sock.close()
server = ThreadingHTTPServer(("127.0.0.1", port), JyotishAPIHandler)
server.daemon_threads = True
base = f"http://127.0.0.1:{port}"
server.allowed_origins = set(DEFAULT_ALLOWED_ORIGINS) | {base}
server.allowed_hosts = set(DEFAULT_ALLOWED_HOSTS)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
yield base
finally:
server.shutdown()
server.server_close()
reset_heavy_compute_gate()
if previous is None:
os.environ.pop("JYOTISH_API_RATE_LIMIT_PER_MINUTE", None)
else:
os.environ["JYOTISH_API_RATE_LIMIT_PER_MINUTE"] = previous
def _post(base: str, body: dict[str, Any]) -> tuple[int, dict[str, Any]]:
request = urllib.request.Request(
f"{base}/api/shadbala",
data=json.dumps(body).encode("utf-8"),
method="POST",
headers={"Content-Type": "application/json", "Origin": base, "Host": base.split("://", 1)[1]},
)
try:
with urllib.request.urlopen(request, timeout=120) as response:
return response.status, json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as error:
return error.code, json.loads(error.read().decode("utf-8") or "{}")
def test_birth_data_request_returns_precise_shadbala(api_base) -> None:
status, payload = _post(api_base, {**BIRTH, "planets": PLANETS, "ascendant": ASCENDANT})
assert status == 200, payload
assert payload["success"] is True
result = payload["result"]
# The birth moment switches Kala and Chesta to the Swiss Ephemeris context.
# 原值: method_variants 只有 kala、chesta
# 新值: 加 moon_paksha(具名口径)
# 原因: BUG-1557 月亮 Paksha 口径绑定 BPHS-Santhanam 27.10–11 + 27.18
# 原值: method_variants 全等比较;新值: 只比较具名口径,BUG-1699 新增的 Chesta 候选键单独断言
# 原因: BUG-1699 从上游补 chesta_profile_candidates / _selection 等键(默认值不变)
chesta_keys = {
"chesta_profile_candidates", "chesta_profile_selection", "chesta_target_diagnostic",
"chesta_target_preview", "chesta_shadow_profile_result", "chesta_profile_result",
}
assert chesta_keys <= set(result["method_variants"])
assert result["method_variants"]["chesta_profile_selection"]["effective_profile"] == "bphs_bounded_surya_mean_motion_seeghrochcha"
# 原值:method_variants 只有下列具名口径。新值:另有 parameter_sensitive_items(六个未定项及其问题),单独核对。
# 原因:占星师 2026-11-08 第五轮裁定 4
assert set(result["method_variants"]["parameter_sensitive_items"]) == {
"saptavargaja_moolatrikona", "ayana_sun", "chesta_moon", "drik_angle", "drik_special_aspects", "drik_mercury_jupiter"}
assert {k: v for k, v in result["method_variants"].items() if k not in chesta_keys | {"parameter_sensitive_items"}} == {
"kala": "bphs_local_solar_events_ahargana_declination",
"chesta": "bphs_bounded_surya_mean_motion_seeghrochcha",
# 原值: moon_paksha bphs_santhanam_27_10_11_chesta_27_18,无下列五项
# 新值: 口径 C 与 #166 其余具名口径;原因: BUG-1581~1587(占星师 2026-11-04)
"moon_paksha": "bphs_sanskrit_27_11_indu_listed_chesta_27_18",
"sun_ayana": "bphs_27_15_17_base_ayana_chesta_27_18",
"saptavargaja": "bphs_27_saptavargaja_20_15_10_4_2_d1_compound",
# 原值: 无 saptavargaja_moolatrikona、drik_mercury_jupiter;mercury_nature "bphs_3_11_any_malefic_same_sign_no_nodes"
# 新值: 补两项待核标签;mercury_nature 改名写明排除交点是实现选择(数值不变)
# 原因: BUG-1622 / BUG-1623,#166 占星师 2026-11-05 答复(第 17 / 19、23、25 条)
"saptavargaja_moolatrikona": "d1_degree_band_only_provisional",
"drik_special_aspects": "bphs_26_9_12_piecewise",
"drik_mercury_jupiter": "quarter_only_raman_pending",
"mercury_nature": "same_sign_any_natural_malefic_waning_moon_included_nodes_excluded_implementation_choice",
"kendradi": "whole_sign_from_lagna",
# 原值: 无;新值: 写明日出与时主口径;原因: BUG-1595,#166 第 12、13 条(只记录,不改值)
"sunrise": "hindu_disc_centre_no_refraction",
"hora": "fixed_60_minutes_from_sunrise_approximation",
}
assert sorted(result["ranking"]) == sorted(SEVEN)
for planet in SEVEN:
row = result["planets"][planet]
assert row["total_rupas"] > 0
assert row["total_virupas"] == pytest.approx(row["total_rupas"] * 60, abs=0.05)
# Dig Bala is read from the Placidus bhava midpoints of the same instant (UT = 12:00 - 8h).
context = build_shadbala_context(swe.julday(1990, 6, 15, 4.0), 39.9042, 116.4074, "raman", 8.0)
for planet in SEVEN:
expected = calc_dig_bala_precise(planet, float(PLANETS[planet]["lon"]), context["house_midpoints"])
assert result["planets"][planet]["dig_bala"] == expected
assert payload["rule_variants"]["selected"] == ["core_sixfold", "advanced_evidence"]
assert payload["advanced_layer"]["source"] == "scripts/shadbala_advanced.py"
assert set(payload["advanced_layer"]["kala_vmdh"]) == set(SEVEN)
def test_birth_data_changes_the_strength_versus_planets_only(api_base) -> None:
status, payload = _post(api_base, {"planets": PLANETS, "ascendant": ASCENDANT, "hour": 12, "minute": 0})
assert status == 200, payload
legacy = payload["result"]
assert legacy["method_variants"]["kala"] == "legacy_approximation"
# Without the birth moment the answer is the chart page's `modules.shadbala` golden.
golden = GOLDEN["chart_modules_shadbala"]["planets"]
for planet in SEVEN:
assert legacy["planets"][planet]["total_rupas"] == pytest.approx(golden[planet]["total_rupas"], abs=1e-4)
_, precise = _post(api_base, {**BIRTH, "planets": PLANETS, "ascendant": ASCENDANT})
assert any(
precise["result"]["planets"][planet]["dig_bala"] != legacy["planets"][planet]["dig_bala"]
for planet in SEVEN
)
def test_bad_inputs_are_400_not_500(api_base) -> None:
status, _ = _post(api_base, {**BIRTH, "planets": PLANETS, "ascendant": ASCENDANT, "ayanamsa": "not-an-ayanamsa"})
assert status == 400
status, _ = _post(api_base, {**BIRTH, "planets": {"Mars": PLANETS["Mars"]}, "ascendant": ASCENDANT})
assert status == 400
def test_shadbala_service_and_api_server_have_no_undefined_names() -> None:
"""BUG-1463 was a module name used where it was never imported; ruff F821 sees that statically."""
ruff = pytest.importorskip("ruff")
targets = ["scripts/jyotish_api_server.py", "scripts/offline_compute_mixins.py", "scripts/shadbala_service"]
completed = subprocess.run(
[ruff.find_ruff_bin(), "check", "--isolated", "--no-cache", "--select", "F821", *targets],
cwd=ROOT, capture_output=True, text=True, check=False,
)
assert completed.returncode == 0, completed.stdout + completed.stderr