//! End-to-end tests of the HTTP API against the real data directory. use std::path::PathBuf; use std::sync::{Arc, OnceLock}; use astro_engine::swiss::SwissEphemeris; use axum::body::Body; use axum::http::{Request, StatusCode}; use geo_tz::Atlas; use http_body_util::BodyExt; use serde_json::{Value, json}; use tower::ServiceExt; use crate::{AppState, routes}; fn state() -> Arc { static STATE: OnceLock> = OnceLock::new(); STATE .get_or_init(|| { let data = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../data"); Arc::new(AppState { engine: Arc::new(SwissEphemeris::new(data.join("ephe")).expect("ephemeris")), atlas: Atlas::load(&data).expect("atlas"), }) }) .clone() } async fn call(method: &str, uri: &str, body: Option) -> (StatusCode, Value) { let mut req = Request::builder().method(method).uri(uri); let body = match body { Some(v) => { req = req.header("content-type", "application/json"); Body::from(v.to_string()) } None => Body::empty(), }; let resp = routes::router(state()).oneshot(req.body(body).unwrap()).await.unwrap(); let status = resp.status(); let bytes = resp.into_body().collect().await.unwrap().to_bytes(); (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null)) } async fn natal(body: Value) -> (StatusCode, Value) { call("POST", "/v1/natal", Some(body)).await } #[tokio::test] async fn budapest_1985_full_chart() { let (status, d) = natal(json!({"date": "1985-07-14", "time": "14:30", "country": "HU", "place": "Budapest"})).await; assert_eq!(status, StatusCode::OK, "{d}"); assert_eq!(d["time"]["utc"], "1985-07-14T12:30:00Z"); assert_eq!(d["time"]["dst"], true); assert_eq!(d["time"]["abbreviation"], "CEST"); assert_eq!(d["points"][0]["id"], "sun"); assert_eq!(d["points"][0]["sign"], "cancer"); assert_eq!(d["angles"]["ascendant"]["sign"], "scorpio"); assert_eq!(d["houses"]["cusps"].as_array().unwrap().len(), 12); assert!(d["aspects"].as_array().unwrap().len() > 10); assert_eq!(d["summary"]["sect"], "day"); assert_eq!(d["warnings"], json!([])); assert_eq!(d["meta"]["data_sources"]["tzdb_version"], "2026f"); } #[tokio::test] async fn place_lmt_before_standard_time() { // Debrecen 1880: Hungary had no standard time; Debrecen's own mean time // (21.6273° E -> +01:26:31) applies, not Budapest's (+01:16:20). let (status, d) = natal(json!({"date": "1880-03-01", "time": "12:00", "country": "HU", "place": "Debrecen"})).await; assert_eq!(status, StatusCode::OK, "{d}"); let offset = d["time"]["utc_offset"].as_str().unwrap(); assert!(offset.starts_with("+01:26:"), "{offset}"); assert_eq!(d["time"]["abbreviation"], "LMT"); assert_eq!(d["time"]["zone"], "Europe/Budapest"); } #[tokio::test] async fn ambiguous_and_nonexistent_local_times() { let (status, d) = natal(json!({"date": "2023-10-29", "time": "02:30", "country": "HU", "place": "Szeged"})).await; assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY); assert_eq!(d["error"]["code"], "ambiguous_local_time"); let (status, d) = natal(json!({ "date": "2023-10-29", "time": "02:30", "country": "HU", "place": "Szeged", "ambiguous_time": "later" })) .await; assert_eq!(status, StatusCode::OK); assert_eq!(d["time"]["utc_offset"], "+01:00"); assert_eq!(d["time"]["transition"]["kind"], "fold"); let (status, d) = natal(json!({"date": "2023-03-26", "time": "02:30", "country": "HU", "place": "Szeged"})).await; assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY); assert_eq!(d["error"]["code"], "nonexistent_local_time"); } #[tokio::test] async fn coordinates_only_in_multi_zone_country() { let (status, d) = natal(json!({"date": "1990-01-15", "time": "08:00", "country": "US", "latitude": 39.74, "longitude": -104.99})) .await; assert_eq!(status, StatusCode::OK, "{d}"); assert_eq!(d["time"]["zone"], "America/Denver"); assert_eq!(d["time"]["zone_source"], "nearest_place"); assert_eq!(d["location"]["coordinates_source"], "coordinates"); assert!(d["location"]["nearest_place"]["name"].is_string()); } #[tokio::test] async fn unknown_time_and_julian_calendar() { let (status, d) = natal(json!({"date": "1950-03-01", "country": "HU", "place": "Iborfia"})).await; assert_eq!(status, StatusCode::OK, "{d}"); assert_eq!(d["time"]["time_known"], false); assert!(d["houses"].is_null() && d["angles"].is_null() && d["lots"].is_null()); let (status, d) = natal(json!({ "date": "1917-10-25", "time": "10:00", "calendar": "julian", "country": "RU", "place": "Moscow" })) .await; assert_eq!(status, StatusCode::OK, "{d}"); assert_eq!(d["time"]["date"], "1917-11-07"); } #[tokio::test] async fn validation_errors() { let cases = [ (json!({"date": "1985-07-14", "country": "HU"}), StatusCode::BAD_REQUEST, "bad_request"), (json!({"date": "1985-13-01", "country": "HU", "place": "Szeged"}), StatusCode::BAD_REQUEST, "bad_request"), (json!({"date": "1985-07-14", "country": "XX", "place": "Szeged"}), StatusCode::BAD_REQUEST, "unknown_country"), ( json!({"date": "1985-07-14", "country": "HU", "place": "Nincsilyenhely"}), StatusCode::NOT_FOUND, "place_not_found", ), ( json!({"date": "1985-07-14", "country": "HU", "latitude": 95.0, "longitude": 19.0}), StatusCode::BAD_REQUEST, "bad_request", ), ( json!({"date": "1985-07-14", "country": "HU", "place": "Szeged", "timezone": "Mars/Base"}), StatusCode::BAD_REQUEST, "unknown_time_zone", ), ( json!({"date": "1985-07-14", "country": "HU", "geonames_id": 683506}), StatusCode::BAD_REQUEST, "place_country_mismatch", ), ( json!({"date": "1985-07-14", "country": "HU", "place": "Szeged", "foo": 1}), StatusCode::BAD_REQUEST, "bad_request", ), ( json!({"date": "1985-07-14", "country": "HU", "place": "Szeged", "options": {"house_system": "nope"}}), StatusCode::BAD_REQUEST, "bad_request", ), ]; for (body, status, code) in cases { let (s, d) = natal(body.clone()).await; assert_eq!((s, d["error"]["code"].as_str().unwrap_or_default()), (status, code), "{body} -> {d}"); } } #[tokio::test] async fn lookup_endpoints() { let (status, d) = call("GET", "/v1/places?country=HU&q=szentgyorgy&limit=3", None).await; assert_eq!(status, StatusCode::OK); assert_eq!(d["places"].as_array().unwrap().len(), 3); let (status, d) = call("GET", "/v1/timezones?country=US", None).await; assert_eq!(status, StatusCode::OK); assert!(d["timezones"].as_array().unwrap().len() > 20); let (status, d) = call("GET", "/v1/info", None).await; assert_eq!(status, StatusCode::OK); assert_eq!(d["options"]["house_system"][0], "placidus"); let (status, _) = call("GET", "/healthz", None).await; assert_eq!(status, StatusCode::OK); let (status, d) = call("GET", "/v1/places?country=HU", None).await; assert_eq!(status, StatusCode::BAD_REQUEST, "{d}"); } #[tokio::test] async fn synastry_two_known_times() { let (status, d) = call( "POST", "/v1/synastry", Some(json!({ "person1": {"name": "A", "date": "1985-07-14", "time": "14:30", "country": "HU", "place": "Budapest"}, "person2": {"name": "B", "date": "1987-02-03", "time": "06:10", "country": "HU", "place": "Szeged"}, "options": {"aspect_set": "extended"} })), ) .await; assert_eq!(status, StatusCode::OK, "{d}"); assert_eq!(d["person1"]["input"]["name"], "A"); assert_eq!(d["person2"]["time"]["abbreviation"], "CET"); assert_eq!(d["person2"]["settings"]["aspect_set"], "extended"); let aspects = d["aspects"].as_array().unwrap(); assert!(aspects.len() > 10); assert!(aspects.windows(2).all(|w| w[0]["orb"].as_f64() <= w[1]["orb"].as_f64())); assert!(aspects.iter().any(|a| a["person1"] == "ascendant" || a["person2"] == "ascendant")); assert_eq!(d["summary"]["aspect_count"], aspects.len()); // Person 1's Sun (Cancer) in person 2's houses, and the reverse direction. let overlays = d["house_overlays"]["person1_in_person2"].as_array().unwrap(); let sun = overlays.iter().find(|o| o["point"] == "sun").unwrap(); assert_eq!(sun["sign"], "cancer"); assert!((1..=12).contains(&sun["house"].as_u64().unwrap())); assert!(d["house_overlays"]["person2_in_person1"].as_array().unwrap().len() >= 18); let comp = &d["composite"]; assert_eq!(comp["houses"]["cusps"].as_array().unwrap().len(), 12); assert_eq!(comp["angles"]["ascendant"]["longitude"], comp["houses"]["cusps"][0]["longitude"]); let sun1 = d["person1"]["points"][0]["longitude"].as_f64().unwrap(); let sun2 = d["person2"]["points"][0]["longitude"].as_f64().unwrap(); let mid = comp["points"][0]["longitude"].as_f64().unwrap(); assert!((astro_engine::synastry::midpoint(sun1, sun2) - mid).abs() < 1e-9); assert!(d["meta"]["data_sources"]["tzdb_version"].is_string()); assert!(d.get("warnings").is_none(), "{}", d["warnings"]); } #[tokio::test] async fn synastry_unknown_time_and_errors() { let (status, d) = call( "POST", "/v1/synastry", Some(json!({ "person1": {"date": "1985-07-14", "time": "14:30", "country": "HU", "place": "Budapest"}, "person2": {"date": "1990-03-01", "country": "HU", "place": "Pécs"} })), ) .await; assert_eq!(status, StatusCode::OK, "{d}"); assert!(d["house_overlays"]["person1_in_person2"].is_null()); assert!(d["house_overlays"]["person2_in_person1"].is_array()); assert!(d["composite"]["houses"].is_null() && d["composite"]["angles"].is_null()); assert!(d["aspects"].as_array().unwrap().iter().all(|a| a["person2"] != "ascendant")); assert!(d["warnings"][0].as_str().unwrap().contains("person2")); let (status, d) = call( "POST", "/v1/synastry", Some(json!({ "person1": {"date": "1985-07-14", "time": "14:30", "country": "HU", "place": "Budapest"}, "person2": {"date": "1990-03-01", "country": "HU", "place": "Nincsilyenhely"} })), ) .await; assert_eq!(status, StatusCode::NOT_FOUND); assert_eq!(d["error"]["code"], "place_not_found"); assert_eq!(d["error"]["person"], "person2"); assert!(d["error"]["message"].as_str().unwrap().starts_with("person2: ")); let (status, d) = call( "POST", "/v1/synastry", Some(json!({ "person1": {"date": "1985-07-14", "country": "HU", "place": "Budapest", "options": {"house_system": "koch"}}, "person2": {"date": "1990-03-01", "country": "HU", "place": "Pécs"} })), ) .await; assert_eq!(status, StatusCode::BAD_REQUEST); assert_eq!(d["error"]["person"], "person1"); let (status, _) = call("POST", "/v1/synastry", Some(json!({"person1": {"date": "1985-07-14"}}))).await; assert_eq!(status, StatusCode::BAD_REQUEST); } #[tokio::test] async fn forecast_year_with_solar_return() { let birth = json!({"date": "1985-07-14", "time": "14:30", "country": "HU", "place": "Budapest"}); let (status, d) = call("POST", "/v1/forecast", Some(json!({"birth": birth, "year": 2026}))).await; assert_eq!(status, StatusCode::OK, "{d}"); let sr = &d["solar_return"]; assert_eq!(sr["timezone"], "Europe/Budapest"); assert!(sr["local_time"].as_str().unwrap().starts_with("2026-07-14T"), "{sr}"); assert_eq!(sr["utc_offset"], "+02:00"); assert_eq!(sr["points"][0]["sign"], "cancer"); assert!(sr["natal_house_of_ascendant"].as_u64().is_some()); assert_eq!(sr["location"]["place"]["name"], "Budapest"); let f = &d["forecast"]; assert_eq!(f["start"], "2026-07-14"); assert_eq!(f["age"], 41); assert_eq!(f["profection"]["lord"], "mars"); assert!(!f["transits"].as_array().unwrap().is_empty()); // Elsewhere on the birthday: same moment, other houses. let (status, e) = call( "POST", "/v1/forecast", Some(json!({"birth": birth, "year": 2026, "location": {"country": "JP", "place": "Tokyo"}})), ) .await; assert_eq!(status, StatusCode::OK, "{e}"); assert_eq!(e["solar_return"]["moment_utc"], sr["moment_utc"]); assert_eq!(e["solar_return"]["timezone"], "Asia/Tokyo"); assert_ne!(e["solar_return"]["angles"]["ascendant"]["sign"], sr["angles"]["ascendant"]["sign"]); // Unknown birth time: no solar return chart, the rest is there. let (status, u) = call( "POST", "/v1/forecast", Some(json!({"birth": {"date": "1985-07-14", "country": "HU", "place": "Budapest"}, "year": 2026})), ) .await; assert_eq!(status, StatusCode::OK, "{u}"); assert!(u["solar_return"].is_null()); assert!(u["forecast"]["profection"].is_null()); let (status, _) = call("POST", "/v1/forecast", Some(json!({"birth": birth, "year": 1985}))).await; assert_eq!(status, StatusCode::BAD_REQUEST); }