hafas 1.0.0

Client for the HAFAS ReST public transport API
Documentation
//! Decodes the trimmed responses of both dialect versions.

use hafas::{
    ArrivalBoard, Client, DepartureBoard, Error, JourneyDetail, JourneyStatus, Location,
    LocationKind, LocationName, NearbyStops, Recon, Request, TripSearch,
};

fn fixture(version: &str, name: &str) -> Vec<u8> {
    let path = format!(
        "{}/../hafas-sim/fixtures/{version}/{name}",
        env!("CARGO_MANIFEST_DIR")
    );
    std::fs::read(&path).unwrap_or_else(|error| panic!("{path}: {error}"))
}

fn client() -> Client {
    Client::builder("http://127.0.0.1:9/")
        .access_id("invalid-key-for-format-check")
        .build()
        .unwrap()
}

fn decode<R: Request>(version: &str, name: &str) -> R::Response {
    client()
        .decode::<R>(&fixture(version, name))
        .unwrap_or_else(|error| panic!("{version}/{name}: {error:?}"))
}

const VERSIONS: [(&str, &str); 2] = [("2.39", "2.39.1"), ("2.52", "2.52.0")];

#[test]
fn reads_the_server_and_dialect_version() {
    for (dialect, server) in VERSIONS {
        let list = decode::<LocationName>(dialect, "location.name.json");
        assert_eq!(list.info.dialect_version.as_deref(), Some(dialect));
        assert_eq!(list.info.server_version.as_deref(), Some(server));
        assert_eq!(list.info.error_code, None);
    }
}

#[test]
fn decodes_location_search() {
    for (dialect, _) in VERSIONS {
        let list = decode::<LocationName>(dialect, "location.name.json");
        let first = list.stops().next().unwrap();
        assert_eq!(first.ext_id, "3000001");
        assert_eq!(first.name, "Frankfurt (Main) Hauptwache");
        assert!(first.id.contains("@L=3000001@"));
        assert!(first.lat.is_some() && first.lon.is_some());
    }
    let list = decode::<LocationName>("2.52", "location.name.json");
    let coord = list
        .stop_location_or_coord_location
        .iter()
        .find_map(|location| match location {
            Location::CoordLocation(coord) => Some(coord),
            Location::StopLocation(_) => None,
        })
        .unwrap();
    assert_eq!(coord.kind, LocationKind::Poi);
    assert_eq!(list.stops().count(), 2);
}

#[test]
fn reads_one_or_no_alternative_id_of_a_stop() {
    let body = br#"{"stopLocationOrCoordLocation":[
        {"StopLocation":{"id":"A","extId":"1","name":"One","altId":"de:06412:1"}},
        {"StopLocation":{"id":"B","extId":"2","name":"Two","altId":null}}]}"#;
    let list = client().decode::<LocationName>(body).unwrap();
    let ids: Vec<_> = list.stops().map(|stop| stop.alt_id.clone()).collect();
    assert_eq!(ids, [vec!["de:06412:1".to_owned()], vec![]]);
}

#[test]
fn decodes_nearby_stops() {
    let list = decode::<NearbyStops>("2.39", "location.nearbystops.json");
    let ids: Vec<_> = list.stops().map(|stop| stop.ext_id.as_str()).collect();
    assert_eq!(ids, ["3000010", "3007010", "3007011"]);
    assert!(list.stops().all(|stop| stop.dist.is_some()));
    // latest/ finds nothing at the same position.
    let list = decode::<NearbyStops>("2.52", "location.nearbystops.json");
    assert_eq!(list.stops().count(), 0);
}

#[test]
fn decodes_departure_boards() {
    for (dialect, _) in VERSIONS {
        let board = decode::<DepartureBoard>(dialect, "departureBoard.json");
        assert_eq!(board.departures.len(), 3);
        for departure in &board.departures {
            let event = &departure.event;
            assert_ne!(event.name.len(), 0);
            assert_ne!(event.journey_detail_ref.reference.len(), 0);
            assert_eq!(event.journey_status, Some(JourneyStatus::Planned));
            assert_eq!(event.kind, LocationKind::Stop);
            assert!(departure.direction.is_some());
            assert_ne!(event.product.len(), 0);
            assert!(event.reachable);
        }
    }
    let first = &decode::<DepartureBoard>("2.39", "departureBoard.json").departures[0];
    assert_eq!(first.event.product[0].class(), Some(8));
    assert_eq!(first.event.name, "S2");
    assert_eq!(first.event.time, "08:40:00");
    assert_eq!(first.event.rt_time.as_deref(), Some("08:55:00"));
}

#[test]
fn decodes_cancelled_departures() {
    let board = decode::<DepartureBoard>("2.39", "departureBoard-cancellations.json");
    let cancelled: Vec<_> = board
        .departures
        .iter()
        .filter(|departure| departure.event.cancelled)
        .map(|departure| departure.event.name.as_str())
        .collect();
    assert_eq!(cancelled, ["Tram 21", "Tram 17"]);
    for departure in board.departures.iter().filter(|d| d.event.cancelled) {
        assert_eq!(departure.event.rt_time, None);
    }
}

#[test]
fn decodes_arrival_boards() {
    for (dialect, _) in VERSIONS {
        let board = decode::<ArrivalBoard>(dialect, "arrivalBoard.json");
        assert_eq!(board.arrivals.len(), 3);
        assert!(
            board
                .arrivals
                .iter()
                .all(|arrival| arrival.origin.is_some())
        );
    }
}

#[test]
fn decodes_trips() {
    for (dialect, _) in VERSIONS {
        let list = decode::<TripSearch>(dialect, "trip.json");
        assert_eq!(list.trips.len(), 2);
        assert!(list.scr_b.is_some() && list.scr_f.is_some());
        for trip in &list.trips {
            assert!(trip.ctx_recon.is_some());
            assert!(trip.duration.as_deref().unwrap().starts_with("PT"));
            assert!(trip.valid);
            let leg = &trip.legs[0];
            assert_eq!(leg.kind, "JNY");
            assert_ne!(leg.origin.name.len(), 0);
            assert_ne!(leg.destination.name.len(), 0);
            assert_ne!(leg.product.len(), 0);
        }
    }
    let list = decode::<TripSearch>("2.52", "trip.json");
    let status = list.trips[0].trip_status.as_ref().unwrap();
    assert!(status.slow_direct && status.economic && status.convenient);
    assert_eq!(status.hint_code, Some(390));
    // Only 2.52 sends the ID of a leg.
    assert!(list.trips[0].legs[0].id.is_some());
    let list = decode::<TripSearch>("2.39", "trip.json");
    assert!(list.trips[0].legs[0].id.is_none());
}

#[test]
fn decodes_recon() {
    for (dialect, _) in VERSIONS {
        let list = decode::<Recon>(dialect, "recon.json");
        assert_eq!(list.trips.len(), 1);
        assert!(list.trips[0].ctx_recon.is_some());
        assert!(list.scr_b.is_none());
    }
}

#[test]
fn decodes_journey_details() {
    for (dialect, _) in VERSIONS {
        let journey = decode::<JourneyDetail>(dialect, "journeyDetail.json");
        assert_eq!(journey.stops.len(), 3);
        assert!(!journey.cancelled);
        assert_eq!(journey.day_of_operation, "2026-11-28");
        assert_ne!(journey.product.len(), 0);
        let first = &journey.stops[0];
        assert!(first.dep_time.is_some());
        assert!(first.arr_time.is_none());
        let last = journey.stops.last().unwrap();
        assert!(last.arr_time.is_some());
        assert!(last.dep_time.is_none());
    }
}

#[test]
fn decodes_cancelled_journeys() {
    let journey = decode::<JourneyDetail>("2.39", "journeyDetail-cancelled.json");
    assert!(journey.cancelled);
    assert_eq!(journey.product[0].name.as_deref(), Some("Tram 17"));
    assert!(journey.stops[0].cancelled_departure);
    assert!(journey.stops.last().unwrap().cancelled_arrival);
}

#[test]
fn reads_the_error_of_a_successful_response() {
    for (dialect, _) in VERSIONS {
        for name in ["errors/auth.json", "errors/auth.xml"] {
            let error = client()
                .decode::<LocationName>(&fixture(dialect, name))
                .unwrap_err();
            assert_eq!(error.code(), Some("API_AUTH"), "{dialect}/{name}");
            assert_eq!(error.status(), None);
            let text = error.to_string();
            assert!(!text.contains("invalid-key-for-format-check"), "{text}");
            assert!(text.contains(hafas::REDACTED), "{text}");
        }
    }
}

#[test]
fn redacts_the_key_in_the_diagnostic_of_the_decoder() {
    let body = br#"{"cancelled":"invalid-key-for-format-check"}"#;
    let error = client().decode::<JourneyDetail>(body).unwrap_err();
    assert!(matches!(error, Error::Decode(_)), "{error:?}");
    for text in [error.to_string(), format!("{error:?}")] {
        assert!(!text.contains("invalid-key-for-format-check"), "{text}");
        assert!(text.contains(hafas::REDACTED), "{text}");
    }
}

#[test]
fn redacts_the_key_in_the_error_code() {
    let body = br#"{"errorCode":"invalid-key-for-format-check","errorText":"denied"}"#;
    let error = client().decode::<LocationName>(body).unwrap_err();
    assert_eq!(error.code(), Some(hafas::REDACTED));
    assert!(!format!("{error:?}").contains("invalid-key-for-format-check"));
}

#[test]
fn keeps_the_error_text_without_a_key_to_redact() {
    let client = Client::builder("http://127.0.0.1:9/").build().unwrap();
    let error = client
        .decode::<LocationName>(br#"{"errorCode":"API_PARAM","errorText":"bad input"}"#)
        .unwrap_err();
    assert_eq!(error.to_string(), "the API answered API_PARAM: bad input");
}

#[test]
fn rejects_a_body_of_the_wrong_form() {
    let error = client().decode::<TripSearch>(b"<html/>").unwrap_err();
    assert!(matches!(error, Error::Decode(_)), "{error:?}");
    let error = client()
        .decode::<TripSearch>(br#"{"Trip":"nope"}"#)
        .unwrap_err();
    assert!(matches!(error, Error::Decode(_)), "{error:?}");
}