use std::time::Duration;
use hafas::{
ArrivalBoard, Client, DepartureBoard, Error, JourneyDetail, LocationName, NearbyStops, Place,
Recon, TripSearch,
};
use hafas_sim::{
ACCESS_ID, CANCELLED_JOURNEY, DEPARTURE_JOURNEY, Endpoint, Failure, Injection, REDACTED, Sim,
Version, fixture,
};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
fn client(base: &str) -> Client {
Client::builder(base).access_id(ACCESS_ID).build().unwrap()
}
async fn get(sim: &Sim, path_and_query: &str) -> (u16, String, String) {
let base = sim.base_url();
let address = base
.trim_start_matches("http://")
.trim_end_matches("/hapi/");
let mut stream = tokio::net::TcpStream::connect(address).await.unwrap();
let request =
format!("GET {path_and_query} HTTP/1.1\r\nHost: {address}\r\nConnection: close\r\n\r\n");
stream.write_all(request.as_bytes()).await.unwrap();
let mut response = String::new();
stream.read_to_string(&mut response).await.unwrap();
let (head, body) = response.split_once("\r\n\r\n").unwrap();
let status = head.split(' ').nth(1).unwrap().parse().unwrap();
let kind = head
.lines()
.find_map(|line| line.strip_prefix("content-type: "))
.unwrap_or_default()
.to_owned();
(status, kind, body.to_owned())
}
#[tokio::test]
async fn serves_both_versions() {
let sim = Sim::start().await;
for (base, dialect) in [(sim.base_url(), "2.39"), (sim.latest_url(), "2.52")] {
let client = client(&base);
let list = client.send(&LocationName::new("Hauptwache")).await.unwrap();
assert_eq!(list.info.dialect_version.as_deref(), Some(dialect));
assert_ne!(list.stops().count(), 0);
client.send(&NearbyStops::new(50.1, 8.6)).await.unwrap();
let board = client.send(&DepartureBoard::new("3000010")).await.unwrap();
assert_eq!(board.departures.len(), 3);
let board = client.send(&ArrivalBoard::new("3000010")).await.unwrap();
assert_eq!(board.arrivals.len(), 3);
let trips = TripSearch::new(Place::Id("3000010".into()), Place::Id("3004734".into()));
assert_eq!(client.send(&trips).await.unwrap().trips.len(), 2);
assert_eq!(
client.send(&Recon::new("ctx")).await.unwrap().trips.len(),
1
);
let journey = client.send(&JourneyDetail::new("any")).await.unwrap();
assert!(!journey.cancelled);
}
assert_eq!(sim.requests().len(), 14);
}
#[tokio::test]
async fn records_the_requests() {
let sim = Sim::start().await;
assert_eq!(sim.requests(), []);
Client::builder(sim.latest_url())
.access_id(ACCESS_ID)
.user_agent("sim-test/1")
.build()
.unwrap()
.send(&LocationName::new("Konstablerwache"))
.await
.unwrap();
let requests = sim.requests();
assert_eq!(requests.len(), 1);
let request = &requests[0];
assert_eq!(request.path, "/hapi/latest/location.name");
assert_eq!(request.param("input"), Some("Konstablerwache"));
assert_eq!(request.param("format"), Some("json"));
assert_eq!(request.param("missing"), None);
assert_eq!(request.user_agent.as_deref(), Some("sim-test/1"));
}
#[tokio::test]
async fn answers_a_missing_key_with_the_error_of_the_server() {
let sim = Sim::start().await;
for path in [
"/hapi/departureBoard?id=1&format=json",
"/hapi/latest/trip?accessId=",
] {
let (status, kind, body) = get(&sim, path).await;
assert_eq!(status, 400);
assert!(kind.starts_with("application/xml"), "{kind}");
assert!(body.contains("API_PARAM"), "{body}");
}
}
#[tokio::test]
async fn answers_a_wrong_key_in_json_or_xml() {
let sim = Sim::start().await;
for base in [sim.base_url(), sim.latest_url()] {
let error = Client::builder(base)
.access_id("wrong-key")
.build()
.unwrap()
.send(&DepartureBoard::new("3000010"))
.await
.unwrap_err();
assert_eq!(error.code(), Some("API_AUTH"));
assert_eq!(error.status(), Some(401));
}
let (status, kind, body) = get(&sim, "/hapi/departureBoard?accessId=wrong-key").await;
assert_eq!(status, 401);
assert!(kind.starts_with("application/xml"), "{kind}");
assert!(body.contains("API_AUTH"), "{body}");
let requests = sim.requests();
assert!(
requests
.iter()
.all(|request| request.param("accessId") == Some(REDACTED)),
"{requests:?}"
);
assert!(!format!("{sim:?}{requests:?}").contains("wrong-key"));
}
#[tokio::test]
async fn never_repeats_the_key_it_was_sent() {
const KEY: &str = "secret-key-of-the-test";
let sim = Sim::start().await;
let paths: Vec<String> = [
"location.name?input=x",
"departureBoard?id=1",
"trip?originId=1&destId=2",
"journeyDetail?id=1",
"unknown",
]
.iter()
.flat_map(|service| {
["/hapi/", "/hapi/latest/"].map(|base| format!("{base}{service}&accessId={KEY}"))
})
.flat_map(|path| [format!("{path}&format=json"), path])
.collect();
for path in &paths {
let (_, _, body) = get(&sim, path).await;
assert!(!body.contains(KEY), "{path}: {body}");
}
sim.inject(Injection::Fail(Failure::quota()));
sim.inject(Injection::Fail(Failure::quota().xml()));
let path = format!("/hapi/trip?accessId={ACCESS_ID}&echo={KEY}");
let (status, _, body) = get(&sim, &path).await;
assert_eq!(status, 400);
assert!(!body.contains(KEY) && !body.contains(ACCESS_ID), "{body}");
}
#[tokio::test]
async fn answers_an_unknown_path_with_404() {
let sim = Sim::start().await;
for path in ["/", "/hapi/latest/nothing", "/other/trip"] {
let (status, kind, _) = get(&sim, path).await;
assert_eq!(status, 404, "{path}");
assert!(kind.starts_with("text/plain"), "{kind}");
}
}
#[tokio::test]
async fn fails_as_often_as_asked() {
let sim = Sim::start().await;
let client = client(&sim.base_url());
sim.inject(Injection::Fail(
Failure::status(503).retry_after(5).times(1),
));
let error = client.send(&LocationName::new("x")).await.unwrap_err();
assert!(
matches!(error, Error::Status { status: 503, .. }),
"{error:?}"
);
assert_eq!(error.retry_after(), Some(Duration::from_secs(5)));
client.send(&LocationName::new("x")).await.unwrap();
}
#[tokio::test]
async fn a_rejected_key_does_not_use_up_a_failure() {
let sim = Sim::start().await;
sim.inject(Injection::Fail(Failure::status(503).times(1)));
let (status, _, _) = get(&sim, "/hapi/location.name?input=x").await;
assert_eq!(status, 400);
let (status, _, _) = get(&sim, "/hapi/location.name?input=x&accessId=wrong").await;
assert_eq!(status, 401);
let error = client(&sim.base_url())
.send(&LocationName::new("x"))
.await
.unwrap_err();
assert_eq!(error.status(), Some(503), "{error:?}");
}
#[tokio::test]
async fn fails_with_hafas_errors() {
let sim = Sim::start().await;
let client = client(&sim.latest_url());
for (failure, code, status) in [
(Failure::quota(), "API_QUOTA", 400),
(Failure::quota().xml(), "API_QUOTA", 400),
(Failure::too_many_requests(), "API_TOO_MANY_REQUESTS", 429),
(Failure::api(503, "SVC_FAIL").xml(), "SVC_FAIL", 503),
] {
sim.clear();
sim.inject(Injection::Fail(failure));
let error = client.send(&TripSearch::default()).await.unwrap_err();
assert_eq!(error.code(), Some(code));
assert_eq!(error.status(), Some(status));
}
}
#[tokio::test]
async fn fails_only_on_the_endpoint_asked_for() {
let sim = Sim::start().await;
let client = client(&sim.base_url());
sim.inject(Injection::Fail(Failure::status(502).on(Endpoint::Trip)));
client.send(&DepartureBoard::new("1")).await.unwrap();
let error = client.send(&TripSearch::default()).await.unwrap_err();
assert_eq!(error.status(), Some(502));
sim.clear();
client.send(&TripSearch::default()).await.unwrap();
}
#[tokio::test]
async fn cancels_a_journey() {
let sim = Sim::start().await;
sim.inject(Injection::Cancel {
journey: DEPARTURE_JOURNEY.to_owned(),
});
let board = client(&sim.base_url())
.send(&DepartureBoard::new("3000010"))
.await
.unwrap();
let first = &board.departures[0].event;
assert!(first.cancelled);
assert_eq!(first.rt_time, None);
assert!(board.departures[1..].iter().all(|d| !d.event.cancelled));
}
#[tokio::test]
async fn cancels_the_stops_of_a_journey() {
let sim = Sim::start().await;
let reference = {
let body = fixture(Version::V2_52, "journeyDetail.json").unwrap();
let value: serde_json::Value = serde_json::from_str(body).unwrap();
value["ref"].as_str().unwrap().to_owned()
};
sim.inject(Injection::Cancel { journey: reference });
let journey = client(&sim.latest_url())
.send(&JourneyDetail::new("any"))
.await
.unwrap();
assert!(journey.cancelled);
assert!(journey.stops[0].cancelled_departure);
assert!(journey.stops.last().unwrap().cancelled_arrival);
assert!(journey.stops.iter().all(|stop| stop.cancelled));
assert!(journey.stops.iter().all(|stop| stop.rt_dep_time.is_none()));
}
#[tokio::test]
async fn delays_a_journey() {
let sim = Sim::start().await;
sim.inject(Injection::Delay {
journey: DEPARTURE_JOURNEY.to_owned(),
minutes: 7,
});
let board = client(&sim.base_url())
.send(&DepartureBoard::new("3000010"))
.await
.unwrap();
let first = &board.departures[0].event;
assert_eq!(first.time, "08:40:00");
assert_eq!(first.rt_time.as_deref(), Some("08:47:00"));
assert_eq!(first.rt_date.as_deref(), Some(first.date.as_str()));
}
fn first_leg() -> (String, serde_json::Value) {
let body = fixture(Version::V2_39, "trip.json").unwrap();
let value: serde_json::Value = serde_json::from_str(body).unwrap();
let leg = &value["Trip"][0]["LegList"]["Leg"][0];
let reference = leg["JourneyDetailRef"]["ref"].as_str().unwrap().to_owned();
(reference, leg["Freq"]["journey"].clone())
}
async fn trip(sim: &Sim) -> serde_json::Value {
let path = format!("/hapi/trip?accessId={ACCESS_ID}&format=json");
let (status, _, body) = get(sim, &path).await;
assert_eq!(status, 200, "{body}");
serde_json::from_str(&body).unwrap()
}
#[tokio::test]
async fn changes_only_the_journey_asked_for() {
let (reference, alternatives) = first_leg();
assert!(alternatives.as_array().is_some_and(|a| !a.is_empty()));
let sim = Sim::start().await;
sim.inject(Injection::Delay {
journey: reference.clone(),
minutes: 5,
});
let delayed = trip(&sim).await;
let leg = &delayed["Trip"][0]["LegList"]["Leg"][0];
assert!(leg["Origin"]["rtTime"].is_string(), "{}", leg["Origin"]);
assert_eq!(leg["Freq"]["journey"], alternatives);
sim.clear();
sim.inject(Injection::Cancel { journey: reference });
let cancelled = trip(&sim).await;
let leg = &cancelled["Trip"][0]["LegList"]["Leg"][0];
assert_eq!(leg["cancelled"], true);
assert_eq!(leg["Origin"]["cancelled"], true);
assert_eq!(leg["Destination"]["cancelled"], true);
assert!(leg["Origin"].get("rtTime").is_none(), "{}", leg["Origin"]);
assert_eq!(leg["Freq"]["journey"], alternatives);
}
#[tokio::test]
async fn delays_over_midnight() {
let sim = Sim::start().await;
sim.inject(Injection::Delay {
journey: DEPARTURE_JOURNEY.to_owned(),
minutes: 16 * 60,
});
let board = client(&sim.base_url())
.send(&DepartureBoard::new("3000010"))
.await
.unwrap();
let first = &board.departures[0].event;
assert_eq!(first.rt_time.as_deref(), Some("00:40:00"));
assert_ne!(first.rt_date.as_deref(), Some(first.date.as_str()));
}
#[tokio::test]
async fn removes_the_realtime_data() {
let sim = Sim::start().await;
sim.inject(Injection::NoRealtime);
let client = client(&sim.base_url());
let board = client.send(&DepartureBoard::new("3000010")).await.unwrap();
assert!(board.departures.iter().all(|d| d.event.rt_time.is_none()));
let journey = client.send(&JourneyDetail::new("any")).await.unwrap();
assert!(journey.stops.iter().all(|stop| stop.rt_arr_time.is_none()));
}
#[tokio::test]
async fn answers_with_another_server_version() {
let sim = Sim::start().await;
sim.inject(Injection::ServerVersion("2.60.0".to_owned()));
let list = client(&sim.latest_url())
.send(&LocationName::new("x"))
.await
.unwrap();
assert_eq!(list.info.server_version.as_deref(), Some("2.60.0"));
}
#[tokio::test]
async fn answers_with_another_fixture() {
let sim = Sim::start().await;
sim.inject(Injection::Fixture {
endpoint: Endpoint::DepartureBoard,
name: "departureBoard-cancellations.json".to_owned(),
});
let client = client(&sim.base_url());
let board = client.send(&DepartureBoard::new("3000010")).await.unwrap();
assert!(board.departures.iter().any(|d| d.event.cancelled));
let board = client.send(&ArrivalBoard::new("3000010")).await.unwrap();
assert_eq!(board.arrivals.len(), 3);
}
#[tokio::test]
async fn answers_the_cancelled_journey() {
let sim = Sim::start().await;
let client = client(&sim.base_url());
let journey = client
.send(&JourneyDetail::new(CANCELLED_JOURNEY))
.await
.unwrap();
assert!(journey.cancelled);
assert_eq!(journey.product[0].name.as_deref(), Some("Tram 17"));
}
#[tokio::test]
async fn answers_a_body_that_is_not_json() {
let sim = Sim::start().await;
sim.inject(Injection::Malformed);
let error = client(&sim.base_url())
.send(&LocationName::new("x"))
.await
.unwrap_err();
assert!(matches!(error, Error::Decode(_)), "{error:?}");
}
#[tokio::test]
async fn answers_slowly() {
let sim = Sim::start().await;
sim.inject(Injection::Slow(Duration::from_millis(500)));
let error = Client::builder(sim.base_url())
.access_id(ACCESS_ID)
.timeout(Duration::from_millis(50))
.build()
.unwrap()
.send(&LocationName::new("x"))
.await
.unwrap_err();
assert!(matches!(error, Error::Timeout(_)), "{error:?}");
}
#[test]
fn finds_the_fixtures() {
for version in [Version::V2_39, Version::V2_52] {
assert!(fixture(version, "trip.json").is_some());
assert!(fixture(version, "errors/nokey.xml").is_some());
assert!(fixture(version, "nothing.json").is_none());
}
assert!(fixture(Version::V2_39, "journeyDetail-cancelled.json").is_some());
assert!(fixture(Version::V2_52, "journeyDetail-cancelled.json").is_none());
}
#[test]
fn runs_as_a_program_until_stdin_ends() {
use std::io::{BufRead, BufReader};
use std::process::{Command, Stdio};
for args in [&[][..], &["0"][..]] {
let mut child = Command::new(env!("CARGO_BIN_EXE_hafas-sim"))
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.unwrap();
let mut lines = BufReader::new(child.stdout.take().unwrap()).lines();
let first = lines.next().unwrap().unwrap();
assert!(first.starts_with("2.39: http://127.0.0.1:"), "{first}");
assert!(first.ends_with("/hapi/"), "{first}");
let second = lines.next().unwrap().unwrap();
assert!(second.ends_with("/hapi/latest/"), "{second}");
drop(child.stdin.take());
assert!(child.wait().unwrap().success());
}
let output = Command::new(env!("CARGO_BIN_EXE_hafas-sim"))
.arg("port")
.output()
.unwrap();
assert_eq!(output.status.code(), Some(2));
assert!(String::from_utf8_lossy(&output.stderr).contains("invalid port"));
}