Files
Jyotisha/tests/test_vedastro_rest_bridge.py
ClaudeandClaude Opus 5.5 044b6bd82b fix(vedastro): every path sends the key, bodies follow the official SDK, and a Pass for the API's sample chart is a failure (BUG-2172, #327)
Live probes on 2026-11-22 showed every request shape answered Status Pass with
the API's own sample chart (14:30 25/10/1992 Mumbai, Ayanamsa 3). The new
scripts/vedastro_echo_guard package sends the key (x-api-key / SetAPIKey) and
only accepts a Pass whose echoed time, place and ayanamsa match the request;
otherwise input_echo_mismatch, not cached, never an official chart. Request
bodies are aligned with SDK 1.23.25 (planetName as a string, lowercase
SearchEvents/DasaAtRange fields, no Ayanamsa/NodeMode/CalculationPreferences).

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

168 lines
6.2 KiB
Python

import argparse
import http.client
import urllib.error
from io import BytesIO
import pytest
from tests.test_consultation_contract_golden import FORBIDDEN_PRIVACY_MARKERS
from scripts.vedastro_rest_bridge import (
SMOKE_DEFAULT,
_date_to_vedastro_std,
build_dasa_payload,
build_horoscope_payload,
build_parser,
call,
match_not_implemented,
probe_calculate_health,
reset_rate_limiter,
)
def _args(**overrides):
values = {
"birth": SMOKE_DEFAULT["birth"],
"name": SMOKE_DEFAULT["name"],
"lat": SMOKE_DEFAULT["lat"],
"lon": SMOKE_DEFAULT["lon"],
"ayanamsa": SMOKE_DEFAULT["ayanamsa"],
"start": "2026-01-01 00:00 +08:00",
"end": "2026-03-31 00:00 +08:00",
}
values.update(overrides)
return argparse.Namespace(**values)
SMOKE_TIME = {
"StdTime": "12:00 01/01/1990 +08:00",
"Location": {"Name": "Beijing, China", "Longitude": 116.4074, "Latitude": 39.9042},
}
# What the API answered on 2026-11-22 for every request: its own sample chart.
SAMPLE_ECHO = (
b'{"Status": "Pass", "Input": {"CalculatorName": "HoroscopePredictions", "Ayanamsa": 3, "Parameters": '
b'[{"Name": "birthTime", "Type": "Time", "Value": {"StdTime": "14:30 25/10/1992 +05:30", '
b'"Location": {"Name": "Mumbai", "Longitude": 72.8777, "Latitude": 19.076}}}]}, "Payload": []}'
)
MATCHING_ECHO = (
b'{"Status": "Pass", "Input": {"CalculatorName": "HoroscopePredictions", "Ayanamsa": 3, "Parameters": '
b'[{"Name": "birthTime", "Type": "Time", "Value": {"StdTime": "12:00 01/01/1990 +08:00", '
b'"Location": {"Name": "Beijing, China", "Longitude": 116.4074, "Latitude": 39.9042}}}]}, '
b'"Payload": {"source": "recorded_smoke"}}'
)
# BUG-2172 原值:{"Ayanamsa": "LAHIRI", "BirthTime": …, "SortByWeight": False};新值:官方 SDK 1.23.25 的
# {"birthTime", "filterTags", "sortByWeight"};原因:对齐官方接口,岁差接口不收,不再发送。
def test_default_horoscope_payload_uses_fictional_smoke_without_network():
payload = build_horoscope_payload(_args())
assert payload == {"birthTime": SMOKE_TIME, "filterTags": None, "sortByWeight": False}
assert "1993" not in payload["birthTime"]["StdTime"]
assert all(marker not in payload["birthTime"]["StdTime"] for marker in FORBIDDEN_PRIVACY_MARKERS)
def test_dasa_payload_formats_vedastro_range_times_without_network():
payload = build_dasa_payload(_args())
# BUG-2172 原值:大写字段 + Ayanamsa;新值:SDK 的 DasaAtRange 字段名,不发岁差。
assert "Ayanamsa" not in payload
assert payload["birthTime"] == SMOKE_TIME
assert payload["startTime"]["StdTime"] == "00:00 01/01/2026 +08:00"
assert payload["endTime"]["StdTime"] == "00:00 31/03/2026 +08:00"
assert payload["levels"] == 3
assert payload["precisionHours"] == 100
def test_date_parser_rejects_ambiguous_times():
with pytest.raises(ValueError):
_date_to_vedastro_std("2026-01-01")
def test_parser_match_is_registered_as_official_blocked():
parser = build_parser()
args = parser.parse_args(["match"])
assert args.cmd == "match"
blocked = match_not_implemented()
assert blocked["official_closure_state"] == "official_blocked"
assert blocked["official_closure_reason"] == "match_subcommand_not_implemented"
class _Handle(BytesIO):
def __enter__(self):
return self
def __exit__(self, *args):
return False
def test_recorded_horoscope_status_pass_does_not_hit_network():
reset_rate_limiter()
def fake_opener(_req, timeout=90):
return _Handle(MATCHING_ECHO)
result = call("HoroscopePredictions", build_horoscope_payload(_args()), opener=fake_opener)
assert result["Status"] == "Pass"
assert result["Payload"] == {"source": "recorded_smoke"}
def test_probe_maps_recorded_pass_and_rate_limit_without_network():
reset_rate_limiter()
# BUG-2172 原值:{"Status": "Pass"} 即判可用;新值:回显的时间地点要和发出的一致。
health = probe_calculate_health(opener=lambda _req, timeout=8: _Handle(MATCHING_ECHO))
assert health["status"] == "official_verified"
assert health["transport"] == "rest"
def limited(_req, timeout=8):
raise urllib.error.HTTPError(
"https://api.vedastro.org/api/Calculate/HoroscopePredictions",
429,
"rate",
hdrs=http.client.HTTPMessage(),
fp=BytesIO(b""),
)
reset_rate_limiter()
blocked = probe_calculate_health(opener=limited)
assert blocked["status"] == "official_blocked"
assert blocked["reason"] == "rate_limited"
def test_pass_computed_for_the_api_sample_chart_is_a_failure():
reset_rate_limiter()
result = call("HoroscopePredictions", build_horoscope_payload(_args()), opener=lambda _req, timeout=90: _Handle(SAMPLE_ECHO))
assert result["Status"] == "Fail"
assert result["echo_check"]["status"] == "input_echo_mismatch"
reset_rate_limiter()
health = probe_calculate_health(opener=lambda _req, timeout=8: _Handle(SAMPLE_ECHO))
assert health == {"status": "official_blocked", "reason": "input_echo_mismatch", "endpoint": health["endpoint"], "transport": "rest"}
def test_pass_without_an_echo_is_not_trusted():
reset_rate_limiter()
health = probe_calculate_health(opener=lambda _req, timeout=8: _Handle(b'{"Status": "Pass"}'))
assert health["status"] == "official_blocked"
assert health["reason"] == "input_echo_mismatch"
def test_the_key_goes_in_the_header_only_when_configured(monkeypatch):
seen = {}
def capture(req, timeout=90):
seen["headers"] = {key.lower(): value for key, value in req.header_items()}
seen["body"] = req.data.decode()
return _Handle(MATCHING_ECHO)
monkeypatch.setenv("VEDASTRO_API_KEY", "test-key-not-real")
reset_rate_limiter()
call("HoroscopePredictions", build_horoscope_payload(_args()), opener=capture)
assert seen["headers"]["x-api-key"] == "test-key-not-real"
assert "test-key-not-real" not in seen["body"]
monkeypatch.delenv("VEDASTRO_API_KEY")
reset_rate_limiter()
call("HoroscopePredictions", build_horoscope_payload(_args()), opener=capture)
assert "x-api-key" not in seen["headers"]