hafas 1.0.0

Client for the HAFAS ReST public transport API
Documentation
//! What the client logs. A test binary of its own: the tracing callsites
//! cache whether anyone listens, and other tests on other threads would fill
//! that cache before the subscriber of this test is set.

use std::sync::{Arc, Mutex};

use axum::Router;
use axum::http::Uri;
use hafas::{Client, LocationName};

const KEY: &str = "test key+/=";

/// Collects what the subscriber writes.
#[derive(Clone, Default)]
struct Buffer(Arc<Mutex<Vec<u8>>>);

impl std::io::Write for Buffer {
    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
        self.0.lock().unwrap().extend_from_slice(bytes);
        Ok(bytes.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

#[tokio::test(flavor = "current_thread")]
async fn logs_the_request_and_the_server_without_the_key() {
    let buffer = Buffer::default();
    let writer = buffer.clone();
    let subscriber = tracing_subscriber::fmt()
        .with_max_level(tracing::Level::TRACE)
        .with_ansi(false)
        .with_writer(move || writer.clone())
        .finish();
    tracing::subscriber::set_global_default(subscriber).unwrap();

    let path = format!(
        "{}/../hafas-sim/fixtures/2.52/location.name.json",
        env!("CARGO_MANIFEST_DIR")
    );
    let body = std::fs::read_to_string(path).unwrap();
    // Below /echo/, the versions repeat the key.
    let echo = format!(r#"{{"serverVersion":"{KEY}","dialectVersion":"{KEY}"}}"#);
    let app = Router::new().fallback(move |uri: Uri| {
        let body = if uri.path().starts_with("/echo/") {
            echo.clone()
        } else {
            body.clone()
        };
        async move { body }
    });
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let address = listener.local_addr().unwrap();
    tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });

    Client::builder(format!("http://{address}"))
        .access_id(KEY)
        .build()
        .unwrap()
        .send(&LocationName::new("Hauptwache"))
        .await
        .unwrap();
    Client::builder(format!("http://{address}/echo/"))
        .access_id(KEY)
        .build()
        .unwrap()
        .send(&LocationName::new("Hauptwache"))
        .await
        .unwrap();
    let logged = String::from_utf8(buffer.0.lock().unwrap().clone()).unwrap();
    assert!(
        logged.contains("location.name?input=Hauptwache&format=json"),
        "{logged}"
    );
    assert!(logged.contains("dialect_version=\"2.52\""), "{logged}");
    assert!(logged.contains("server_version=\"2.52.0\""), "{logged}");
    let redacted = format!("server_version=\"{}\"", hafas::REDACTED);
    assert!(logged.contains(&redacted), "{logged}");
    for form in [KEY, "test+key", "test%20key", "accessId"] {
        assert!(!logged.contains(form), "{form} in {logged}");
    }
}