Part 2 of #144. - The varga-segments scan gains opt-in stability_items: lagna degree, Sripati cusp signs, Moon sign / nakshatra / pada / house per minute, plus a historical-timezone check. The precheck requests D1/D9/D10 with it. - Chart page shows nine computed items (一致 / 有变化) only for a range the user gave, the verbatim comparison sentence, a verify-first block for the conditions stored data can show, and the verbatim Dasha boundary sentence. - Precheck sends the chart's ayanamsa and node mode and drops replies with other settings; the endpoint honours node_mode. candidate_time_sensitivity_scan and flexible_birth_time_profile take no defaults (BUG-1515). - 只记得时辰 third question, stored in birth_time_clue; no migration. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DbBXoyeZrYn6ryNcSe5Y2Y
150 lines
8.3 KiB
Python
150 lines
8.3 KiB
Python
"""Real chart parity, civil midnight and bounded/cache endpoint contracts."""
|
|
from datetime import timedelta
|
|
|
|
import pytest
|
|
|
|
from scripts import domain_calculation_service
|
|
from scripts.rectification_varga_segments_api import scan_varga_segments
|
|
from scripts.research import varga_resolution_lib as vr
|
|
|
|
|
|
@pytest.mark.parametrize("radius", [10, 30, 60])
|
|
def test_scan_matches_research_every_minute(radius, tmp_path):
|
|
case = vr.load_cases()[0] # Public AA calibration fixture, never a user profile.
|
|
origin = vr.birth_datetime(case)
|
|
body = {"start_at": (origin - timedelta(minutes=radius)).strftime("%Y-%m-%dT%H:%M"),
|
|
"end_at": (origin + timedelta(minutes=radius)).strftime("%Y-%m-%dT%H:%M"),
|
|
"latitude": case["birth"]["latitude"], "longitude": case["birth"]["longitude"],
|
|
"timezone_offset": case["birth"]["timezone_offset"], "target_charts": ["D1", "D9", "D10"]}
|
|
actual = scan_varga_segments(body, cache_dir=tmp_path)
|
|
signs = vr.signs_per_minute(case, radius, vargas=("D1", "D9", "D10"))
|
|
assert actual["window_minutes"] == 2 * radius + 1
|
|
assert [minute["signs"] for minute in actual["minutes"]] == [signs[offset] for offset in range(-radius, radius + 1)]
|
|
for chart in body["target_charts"]:
|
|
expected = vr.segments_for(signs, (chart,))
|
|
assert [(row["start"] - radius, row["end"] - radius, row["sign"]) for row in actual["segments"][chart]] == [(row["start"], row["end"], row["key"][0]) for row in expected]
|
|
assert scan_varga_segments(body, cache_dir=tmp_path) == actual
|
|
assert len(list(tmp_path.glob("*.json"))) == 1
|
|
|
|
|
|
def test_midnight_keeps_dates_and_offsets(tmp_path):
|
|
body = {"start_at": "2000-01-01T23:55", "end_at": "2000-01-02T00:05",
|
|
"latitude": 0, "longitude": 0, "timezone_offset": 0, "target_charts": ["D1"]}
|
|
result = scan_varga_segments(body, cache_dir=tmp_path)
|
|
assert result["minutes"][0]["date"] == "2000-01-01"
|
|
assert result["minutes"][-1]["date"] == "2000-01-02"
|
|
assert result["minutes"][-1]["offset"] == 10
|
|
assert all(result["full_window_unique"].values())
|
|
|
|
|
|
@pytest.mark.parametrize("patch", [
|
|
{"target_charts": ["D12"]}, {"target_charts": ["D1", {}]},
|
|
{"target_charts": [["D1"]]}, {"target_charts": [None]},
|
|
{"target_charts": ["D1", "D1"]}, {"target_charts": "D1"},
|
|
{"end_at": "2000-01-03T00:00"}, {"latitude": float("nan")}, {"timezone_offset": True},
|
|
])
|
|
def test_invalid_scan_rejected(patch, tmp_path):
|
|
body = {"start_at": "2000-01-01T00:00", "end_at": "2000-01-01T00:10",
|
|
"latitude": 0, "longitude": 0, "timezone_offset": 0, **patch}
|
|
with pytest.raises(ValueError):
|
|
scan_varga_segments(body, cache_dir=tmp_path)
|
|
|
|
|
|
@pytest.mark.parametrize("damaged", ["[]", "null", "42", "{broken"])
|
|
def test_nonobject_or_broken_cache_recomputed(damaged, tmp_path):
|
|
body = {"start_at": "2000-01-01T00:00", "end_at": "2000-01-01T00:02",
|
|
"latitude": 0, "longitude": 0, "timezone_offset": 0, "target_charts": ["D1"]}
|
|
expected = scan_varga_segments(body, cache_dir=tmp_path)
|
|
path = next(tmp_path.glob("*.json"))
|
|
path.write_text(damaged, encoding="utf-8")
|
|
assert scan_varga_segments(body, cache_dir=tmp_path) == expected
|
|
|
|
|
|
# Issue #165: per-item stability. Fictional coordinates and dates only.
|
|
_FICTIONAL = {"latitude": 31.2, "longitude": 121.5, "timezone_offset": 9, "ayanamsa": "raman", "node_mode": "mean"}
|
|
|
|
|
|
def _independent_minute(moment, *, ayanamsa="raman", node_mode="mean"):
|
|
"""Recompute one minute without the endpoint, for parity."""
|
|
import swisseph as swe
|
|
|
|
from scripts.ayanamsa_utils import temporary_ayanamsa
|
|
from scripts.bhava_chalit import BhavaChalitCalculator
|
|
|
|
chart = domain_calculation_service.compute_chart({
|
|
"lat": 31.2, "lon": 121.5, "tz": 9, "ayanamsa": ayanamsa, "node_mode": node_mode,
|
|
"year": moment.year, "month": moment.month, "day": moment.day, "hour": moment.hour, "minute": moment.minute,
|
|
})
|
|
asc = float(chart["ascendant"]["lon"])
|
|
jd = swe.julday(moment.year, moment.month, moment.day, moment.hour + moment.minute / 60 - 9)
|
|
with temporary_ayanamsa(ayanamsa, swe):
|
|
_, ascmc = swe.houses_ex(jd, 31.2, 121.5, b"R", swe.FLG_SWIEPH | swe.FLG_SIDEREAL)
|
|
cusps = BhavaChalitCalculator().calculate_cusps(asc, float(ascmc[1]) % 360, "sripati")
|
|
moon = chart["planets"]["Moon"]
|
|
return {
|
|
"lagna_arcmin": int((asc * 60 + 1e-9) // 1) % 21600,
|
|
"cusp_signs": [int(c // 30) % 12 for c in cusps],
|
|
"moon_sign": int(float(moon["lon"]) // 30) % 12,
|
|
"moon_nakshatra": moon["nakshatra"],
|
|
"moon_pada": moon["nakshatra_pada"],
|
|
"moon_house": moon["house"],
|
|
}
|
|
|
|
|
|
def test_stability_items_match_an_independent_minute_by_minute_recompute(tmp_path):
|
|
from datetime import datetime
|
|
|
|
body = {"start_at": "1990-06-15T11:00", "end_at": "1990-06-15T12:59", "target_charts": ["D1", "D9", "D10"],
|
|
"stability_items": True, **_FICTIONAL}
|
|
result = scan_varga_segments(body, cache_dir=tmp_path)
|
|
stability = result["stability"]
|
|
start = datetime(1990, 6, 15, 11, 0)
|
|
rows = [_independent_minute(start + timedelta(minutes=offset)) for offset in range(120)]
|
|
assert stability["minutes_compared"] == 120
|
|
lagna = [row["lagna_arcmin"] for row in rows]
|
|
assert stability["lagna_degree"] == {"changes": len(set(lagna)) > 1, "first_arcmin": lagna[0], "last_arcmin": lagna[-1],
|
|
"min_arcmin": min(lagna), "max_arcmin": max(lagna)}
|
|
changed = [house + 1 for house in range(12) if len({row["cusp_signs"][house] for row in rows}) > 1]
|
|
assert stability["house_cusps"]["changed_houses"] == changed
|
|
assert stability["house_cusps"]["changes"] is bool(changed)
|
|
for name in ("moon_sign", "moon_nakshatra", "moon_pada", "moon_house"):
|
|
values = [row[name] for row in rows]
|
|
distinct_runs = [value for index, value in enumerate(values) if index == 0 or values[index - 1] != value]
|
|
assert [segment["value"] for segment in stability[name]["segments"]] == distinct_runs, name
|
|
assert stability[name]["changes"] is (len(distinct_runs) > 1)
|
|
assert sum(segment["length"] for segment in stability[name]["segments"]) == 120
|
|
# Items are independent: whatever the D1 ascendant does, each Moon item reports its own runs.
|
|
assert result["full_window_unique"]["D1"] is (len(result["segments"]["D1"]) == 1)
|
|
|
|
|
|
def test_stability_is_opt_in_and_leaves_every_earlier_cache_key_alone(tmp_path):
|
|
body = {"start_at": "1990-06-15T11:58", "end_at": "1990-06-15T12:02", "target_charts": ["D1"], **_FICTIONAL}
|
|
plain = scan_varga_segments(body, cache_dir=tmp_path)
|
|
assert "stability" not in plain
|
|
with_items = scan_varga_segments({**body, "stability_items": True}, cache_dir=tmp_path)
|
|
assert with_items["window_key"] != plain["window_key"]
|
|
assert with_items["segments"] == plain["segments"]
|
|
assert scan_varga_segments(body, cache_dir=tmp_path) == plain
|
|
for bad in ({"stability_items": "yes"}, {"timezone_id": "Asia/Shanghai"}, {"stability_items": True, "timezone_id": 8}):
|
|
with pytest.raises(ValueError):
|
|
scan_varga_segments({**body, **bad}, cache_dir=tmp_path)
|
|
|
|
|
|
@pytest.mark.parametrize(("zone", "start_at", "end_at", "offset", "status"), [
|
|
(None, "1990-06-15T11:58", "1990-06-15T12:02", 9, "unchecked"),
|
|
("Asia/Shanghai", "1990-06-15T11:58", "1990-06-15T12:02", 9, "consistent"),
|
|
# The stored offset is not what the zone's historical rules give on that date.
|
|
("Asia/Shanghai", "1990-06-15T11:58", "1990-06-15T12:02", 8, "offset_differs"),
|
|
# Clocks went back: 01:30 happened twice.
|
|
("America/New_York", "2000-10-29T01:20", "2000-10-29T01:40", -5, "ambiguous"),
|
|
# Clocks went forward: 02:30 never happened.
|
|
("America/New_York", "2000-04-02T02:20", "2000-04-02T02:40", -5, "nonexistent"),
|
|
# The range spans the change itself.
|
|
("America/New_York", "2000-04-02T01:50", "2000-04-02T01:59", -5, "consistent"),
|
|
("America/New_York", "2000-04-02T03:00", "2000-04-02T03:10", -5, "offset_differs"),
|
|
])
|
|
def test_zone_check_reads_the_historical_offset_at_every_minute(zone, start_at, end_at, offset, status, tmp_path):
|
|
body = {"start_at": start_at, "end_at": end_at, "target_charts": ["D1"], "stability_items": True,
|
|
**_FICTIONAL, "timezone_offset": offset, **({"timezone_id": zone} if zone else {})}
|
|
assert scan_varga_segments(body, cache_dir=tmp_path)["stability"]["timezone_check"]["status"] == status
|