use std::collections::BTreeSet;
use hafas::{
Arrival, ArrivalBoard, ArrivalList, BoardEvent, CoordLocation, Departure, DepartureBoard,
DepartureList, Direction, Journey, JourneyDetail, JourneyDetailRef, JourneyStatus, Leg,
LocationKind, LocationList, LocationName, LocationNote, Message, Name, NearbyStops, Note,
Occupancy, OriginDest, Place, Platform, PlatformKind, Product, PrognosisType, Recon, Request,
RtMode, ServiceDays, Stop, StopLocation, Trip, TripList, TripSearch, TripStatus,
};
use serde::Serialize;
use serde_json::Value;
const PRODUCTION: &str = include_str!("../schema/production.json");
const LATEST: &str = include_str!("../schema/latest.json");
enum Field {
Simple,
Complex(String),
}
struct Schemas(Vec<Value>);
impl Schemas {
fn load() -> Self {
Self(
[PRODUCTION, LATEST]
.iter()
.map(|text| serde_json::from_str(text).expect("the extract is JSON"))
.collect(),
)
}
fn types<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a Value> + 'a {
self.0
.iter()
.map(move |schema| &schema["types"][name])
.filter(|ty| ty.is_object())
}
fn is_complex(&self, name: &str) -> bool {
self.types(name).next().is_some()
}
fn field(&self, ty: &str, name: &str) -> Option<Field> {
for schema in &self.0 {
let mut current = Some(ty.to_owned());
while let Some(ty) = current {
let definition = &schema["types"][&ty];
if !definition.is_object() {
break;
}
if let Some(element) = definition["elements"].get(name) {
let element = element["type"].as_str().unwrap().to_owned();
return Some(if self.is_complex(&element) {
Field::Complex(element)
} else {
Field::Simple
});
}
if definition["attributes"].get(name).is_some()
|| (name == "value" && definition["text"] == true)
{
return Some(Field::Simple);
}
current = definition["base"].as_str().map(str::to_owned);
}
}
None
}
fn walk(&self, value: &Value, ty: &str, path: &str, unknown: &mut BTreeSet<String>) {
match value {
Value::Array(items) => {
for item in items {
self.walk(item, ty, &format!("{path}[]"), unknown);
}
}
Value::Object(fields) => {
for (key, child) in fields {
let path = format!("{path}.{key}");
if ty == "LocationList" && key == "stopLocationOrCoordLocation" {
self.walk(child, ty, &path, unknown);
continue;
}
match self.field(ty, key) {
None => {
unknown.insert(format!("{ty}: {path}"));
}
Some(Field::Complex(element)) => {
self.walk(child, &element, &path, unknown);
}
Some(Field::Simple) => {}
}
}
}
_ => {}
}
}
fn element(&self, ty: &str, name: &str) -> String {
match self.field(ty, name) {
Some(Field::Complex(element)) => element,
_ => panic!("{ty} has no complex element {name}"),
}
}
fn enum_values(&self, name: &str) -> BTreeSet<String> {
let mut values = BTreeSet::new();
for schema in &self.0 {
if let Some(list) = schema["enums"][name].as_array() {
values.extend(list.iter().map(|v| v.as_str().unwrap().to_owned()));
}
}
assert!(!values.is_empty(), "no enum {name}");
values
}
}
fn unknown_fields<T: Serialize>(schemas: &Schemas, value: &T, ty: &str) -> BTreeSet<String> {
let mut unknown = BTreeSet::new();
let value = serde_json::to_value(value).unwrap();
schemas.walk(&value, ty, "", &mut unknown);
unknown
}
#[test]
fn the_walk_finds_unknown_fields_at_any_depth() {
let schemas = Schemas::load();
let value = serde_json::json!({
"serverVersion": "2.39.1",
"bogus": 1,
"Trip": [{
"ctxRecon": "x",
"LegList": {"Leg": [{"Notes": {"Note": [{"value": "x", "nope": 1}]}}]},
}],
});
let mut unknown = BTreeSet::new();
schemas.walk(&value, "TripList", "", &mut unknown);
assert_eq!(
unknown,
BTreeSet::from([
"TripList: .bogus".to_owned(),
"Note: .Trip[].LegList.Leg[].Notes.Note[].nope".to_owned(),
])
);
let value = serde_json::json!({
"stopLocationOrCoordLocation": [
{"StopLocation": {"extId": "1", "nope": 1}},
{"Nowhere": {}},
],
});
let mut unknown = BTreeSet::new();
schemas.walk(&value, "LocationList", "", &mut unknown);
assert_eq!(
unknown,
BTreeSet::from([
"StopLocation: .stopLocationOrCoordLocation[].StopLocation.nope".to_owned(),
"LocationList: .stopLocationOrCoordLocation[].Nowhere".to_owned(),
])
);
}
fn check<T: Default + Serialize>(schemas: &Schemas, ty: &str) {
let unknown = unknown_fields(schemas, &T::default(), ty);
assert!(unknown.is_empty(), "fields the API lacks: {unknown:?}");
}
#[test]
fn every_field_of_the_responses_exists_in_the_schema() {
let schemas = Schemas::load();
check::<LocationList>(&schemas, "LocationList");
check::<DepartureList>(&schemas, "DepartureBoard");
check::<ArrivalList>(&schemas, "ArrivalBoard");
check::<Journey>(&schemas, "JourneyDetail");
check::<TripList>(&schemas, "TripList");
}
#[test]
fn every_field_of_the_parts_exists_in_the_schema() {
let schemas = Schemas::load();
let s = &schemas;
let stop_location = s.element("LocationList", "StopLocation");
check::<StopLocation>(s, &stop_location);
check::<CoordLocation>(s, &s.element("LocationList", "CoordLocation"));
let notes = s.element(&stop_location, "LocationNotes");
check::<LocationNote>(s, &s.element(¬es, "LocationNote"));
let departure = s.element("DepartureBoard", "Departure");
check::<Departure>(s, &departure);
check::<BoardEvent>(s, &departure);
let arrival = s.element("ArrivalBoard", "Arrival");
check::<Arrival>(s, &arrival);
check::<BoardEvent>(s, &arrival);
check::<JourneyDetailRef>(s, &s.element(&departure, "JourneyDetailRef"));
check::<Product>(s, &s.element(&departure, "Product"));
check::<Platform>(s, &s.element(&departure, "platform"));
check::<Occupancy>(s, &s.element(&departure, "Occupancy"));
let notes = s.element(&departure, "Notes");
check::<Note>(s, &s.element(¬es, "Note"));
let messages = s.element(&departure, "Messages");
check::<Message>(s, &s.element(&messages, "Message"));
let stops = s.element("JourneyDetail", "Stops");
check::<Stop>(s, &s.element(&stops, "Stop"));
let names = s.element("JourneyDetail", "Names");
check::<Name>(s, &s.element(&names, "Name"));
let directions = s.element("JourneyDetail", "Directions");
check::<Direction>(s, &s.element(&directions, "Direction"));
check::<ServiceDays>(s, &s.element("JourneyDetail", "ServiceDays"));
let trip = s.element("TripList", "Trip");
check::<Trip>(s, &trip);
check::<TripStatus>(s, &s.element(&trip, "TripStatus"));
let legs = s.element(&trip, "LegList");
let leg = s.element(&legs, "Leg");
check::<Leg>(s, &leg);
check::<OriginDest>(s, &s.element(&leg, "Origin"));
}
#[test]
fn every_field_of_the_decoded_fixtures_exists_in_the_schema() {
let schemas = Schemas::load();
let fixtures = concat!(env!("CARGO_MANIFEST_DIR"), "/../hafas-sim/fixtures");
let mut unknown = BTreeSet::new();
let mut count = 0;
for version in hafas::DIALECT_VERSIONS {
let dir = std::path::Path::new(fixtures).join(version);
for entry in std::fs::read_dir(&dir).unwrap() {
let path = entry.unwrap().path();
if path.extension().is_none_or(|extension| extension != "json") {
continue;
}
let name = path.file_name().unwrap().to_str().unwrap().to_owned();
let body = std::fs::read(&path).unwrap();
let decoded = |ty: &str| -> Value {
let value = match ty {
"LocationList" => {
serde_json::to_value(serde_json::from_slice::<LocationList>(&body).unwrap())
}
"DepartureBoard" => serde_json::to_value(
serde_json::from_slice::<DepartureList>(&body).unwrap(),
),
"ArrivalBoard" => {
serde_json::to_value(serde_json::from_slice::<ArrivalList>(&body).unwrap())
}
"JourneyDetail" => {
serde_json::to_value(serde_json::from_slice::<Journey>(&body).unwrap())
}
_ => serde_json::to_value(serde_json::from_slice::<TripList>(&body).unwrap()),
};
value.unwrap()
};
let ty = match name.split(['-', '.']).next().unwrap() {
"location" => "LocationList",
"departureBoard" => "DepartureBoard",
"arrivalBoard" => "ArrivalBoard",
"journeyDetail" => "JourneyDetail",
"trip" | "recon" => "TripList",
other => panic!("no type for the fixture {other}"),
};
schemas.walk(&decoded(ty), ty, &format!("{version}/{name}"), &mut unknown);
count += 1;
}
}
assert!(count >= 14, "only {count} fixtures");
assert!(unknown.is_empty(), "fields the API lacks: {unknown:#?}");
}
#[test]
fn every_response_type_matches_its_service() {
let schemas = Schemas::load();
let services = [
(LocationName::PATH, "LocationList"),
(NearbyStops::PATH, "LocationList"),
(DepartureBoard::PATH, "DepartureBoard"),
(ArrivalBoard::PATH, "ArrivalBoard"),
(JourneyDetail::PATH, "JourneyDetail"),
(TripSearch::PATH, "TripList"),
(Recon::PATH, "TripList"),
];
for schema in &schemas.0 {
for (path, response) in services {
assert_eq!(
schema["services"][path]["responses"],
serde_json::json!([response]),
"{path}"
);
}
}
}
fn known(values: &[&str]) -> BTreeSet<String> {
values.iter().map(|&value| value.to_owned()).collect()
}
#[test]
fn every_enum_value_exists_in_the_schema() {
let schemas = Schemas::load();
let checks: [(&str, &[&str]); 5] = [
("JourneyStatusType", JourneyStatus::KNOWN),
("PrognosisType", PrognosisType::KNOWN),
("PlatformTypeType", PlatformKind::KNOWN),
("Departure@type", LocationKind::KNOWN),
("RtModeType", RtMode::KNOWN),
];
for (name, values) in checks {
let missing: BTreeSet<_> = known(values)
.difference(&schemas.enum_values(name))
.cloned()
.collect();
assert!(missing.is_empty(), "{name} lacks {missing:?}");
}
}
fn check_request<R: Request>(schemas: &Schemas, request: &R) {
let sent: BTreeSet<&str> = request.query().iter().map(|(name, _)| *name).collect();
let mut known = BTreeSet::new();
for schema in &schemas.0 {
let params = schema["services"][R::PATH]["params"]
.as_object()
.unwrap_or_else(|| panic!("{} is not in the schema", R::PATH));
known.extend(params.keys().map(String::as_str));
for (name, param) in params {
let added_by_client = ["accessId", "format", "lang"].contains(&name.as_str());
if param["required"] == true && param.get("default").is_none() && !added_by_client {
assert!(sent.contains(name.as_str()), "{} needs {name}", R::PATH);
}
}
}
let unknown: BTreeSet<_> = sent.difference(&known).collect();
assert!(unknown.is_empty(), "{} lacks {unknown:?}", R::PATH);
}
#[test]
fn every_parameter_exists_in_the_schema() {
let schemas = Schemas::load();
let s = &schemas;
check_request(
s,
&LocationName {
max_no: Some(5),
kind: Some("S".to_owned()),
products: Some(8),
near: Some((50.1, 8.6)),
..LocationName::new("Hauptwache")
},
);
check_request(
s,
&NearbyStops {
r: Some(500),
max_no: Some(5),
kind: Some("S".to_owned()),
products: Some(8),
..NearbyStops::new(50.1, 8.6)
},
);
let board = DepartureBoard {
date: Some("2026-11-26".to_owned()),
time: Some("07:30".to_owned()),
duration: Some(60),
max_journeys: Some(10),
products: Some(8),
direction: Some("3000010".to_owned()),
rt_mode: Some(RtMode::ServerDefault),
..DepartureBoard::new("3000010")
};
check_request(s, &board);
check_request(
s,
&ArrivalBoard {
date: board.date.clone(),
time: board.time.clone(),
duration: board.duration,
max_journeys: board.max_journeys,
products: board.products,
direction: board.direction.clone(),
rt_mode: board.rt_mode.clone(),
..ArrivalBoard::new("3000010")
},
);
let trip = TripSearch {
date: Some("2026-11-26".to_owned()),
time: Some("07:30".to_owned()),
search_for_arrival: Some(true),
num_f: Some(3),
num_b: Some(1),
context: Some("context".to_owned()),
max_change: Some(2),
products: Some(8),
rt_mode: Some(RtMode::Realtime),
passlist: Some(true),
..TripSearch::new(
Place::Id("3000010".to_owned()),
Place::Coord {
lat: 50.1,
lon: 8.6,
},
)
};
check_request(s, &trip);
check_request(
s,
&TripSearch {
origin: Place::Coord {
lat: 50.1,
lon: 8.6,
},
destination: Place::Id("3004734".to_owned()),
..trip
},
);
check_request(
s,
&JourneyDetail {
date: Some("2026-11-26".to_owned()),
rt_mode: Some(RtMode::Full),
..JourneyDetail::new("1|1|1|80|26112026")
},
);
check_request(
s,
&Recon {
rt_mode: Some(RtMode::Full),
passlist: Some(true),
..Recon::new("ctx")
},
);
}