hafas-sim 1.0.0

Fake HAFAS ReST server built from trimmed RMV responses, for tests
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
//! The sim, through the hafas client and through plain HTTP.

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()
}

/// A plain GET: the status, the `Content-Type` and the body.
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}");
    // A wrong key may be a real one: the recording does not keep it.
    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()));
}

/// The trip fixture of 2.39, the `ref` of its first leg and the
/// alternatives of that leg in `Freq`.
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));
    // Other services keep their own.
    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};

    // Without a port and with 0, both a free one.
    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"));
}