//! Shared helpers for integration tests. use axum::body::Body; use axum::extract::ConnectInfo; use axum::http::{Method, Request}; use axum::response::Response; use http_body_util::BodyExt; use std::net::SocketAddr; use std::time::{Duration, Instant}; use tower::ServiceExt; /// True only when the database in `SQL_URI` actually accepts the /// configured credentials. Tests that need a live MariaDB skip (rather /// than fail) when this is false — a server may be listening on the /// port yet still be unusable (wrong credentials), which a plain port /// check cannot see. pub fn db_available() -> bool { let config = genenetwork4::config::Config::load(); let Ok(opts) = mysql::Opts::from_url(&config.sql_uri) else { return false; }; mysql::Conn::new(opts).is_ok() } /// True only when gn-auth is actually reachable at the configured /// AUTH_SERVER_URL. Tests that need a live gn-auth skip (rather than /// fail) when this is false, same reasoning as `db_available`. pub fn auth_server_available() -> bool { let config = genenetwork4::config::Config::load(); ureq::get(format!( "{}/auth/public-jwks", config.auth_server_url.trim_end_matches('/') )) .call() .is_ok() } /// A bearer token to use against a live gn-auth instance in tests that /// need one, e.g. for an endpoint requiring `AuthToken`. Tries /// `POST /get-test-token` first (src/routes/dev.rs) -- requests from /// these tests carry a local peer address, so this just works with a /// reachable gn-auth, no externally managed token needed -- falling back /// to the GN4_TEST_AUTH_TOKEN env var (see docs/gn-auth.md) when there /// is none. Tests using this skip rather than fail when neither /// produces a token. pub async fn auth_token() -> Option { if let Some(token) = fetch_test_token().await { return Some(token); } std::env::var("GN4_TEST_AUTH_TOKEN").ok() } async fn fetch_test_token() -> Option { let response = post("POST /get-test-token", "/get-test-token").await; if response.status() != axum::http::StatusCode::OK { return None; } let body = response.into_body().collect().await.ok()?.to_bytes(); let token: serde_json::Value = serde_json::from_slice::(&body).ok()?["data"].clone(); token["access_token"].as_str().map(str::to_string) } /// Above this, a request's timing is reported as a warning (see `get`). const SLOW_THRESHOLD: Duration = Duration::from_secs(1); /// The peer address requests carry by default: this machine, as for a /// client of a real server (see `post_from` for other callers). fn local_peer() -> SocketAddr { SocketAddr::from(([127, 0, 0, 1], 40000)) } async fn request(label: &str, method: Method, uri: &str, bearer_token: Option<&str>) -> Response { request_from(label, method, uri, bearer_token, local_peer()).await } async fn request_from( label: &str, method: Method, uri: &str, bearer_token: Option<&str>, peer: SocketAddr, ) -> Response { let start = Instant::now(); let mut builder = Request::builder() .method(method) .uri(uri) .extension(ConnectInfo(peer)); if let Some(token) = bearer_token { builder = builder.header("Authorization", format!("Bearer {token}")); } let response = genenetwork4::app() .oneshot(builder.body(Body::empty()).unwrap()) .await .unwrap(); let elapsed = start.elapsed(); if elapsed > SLOW_THRESHOLD { eprintln!("WARNING: {label} took {elapsed:?} (> {SLOW_THRESHOLD:?})"); } response } /// GETs `uri` against genenetwork4::app() and warns on stderr if the /// response -- which for every endpoint using this helper means its SQL /// query -- takes longer than SLOW_THRESHOLD. Warnings only show with /// `cargo test -- --nocapture` (or on a failing test), since cargo /// captures stdout/stderr for passing tests otherwise. pub async fn get(label: &str, uri: &str) -> Response { request(label, Method::GET, uri, None).await } /// Like `get`, but with an `Authorization: Bearer ` header, for /// endpoints that require `AuthToken`. pub async fn get_with_token(label: &str, uri: &str, token: &str) -> Response { request(label, Method::GET, uri, Some(token)).await } /// POSTs to `uri` with an empty body, same timing/warning behavior as /// `get`. pub async fn post(label: &str, uri: &str) -> Response { request(label, Method::POST, uri, None).await } /// Like `post`, but as a request from `peer` (the TCP peer address a /// real server would see). pub async fn post_from(label: &str, uri: &str, peer: SocketAddr) -> Response { request_from(label, Method::POST, uri, None, peer).await } /// POSTs `body` as JSON to `uri` with an `Authorization: Bearer ` /// header, for endpoints needing both a request body and `AuthToken` /// (e.g. POST /compute/gemma). Same timing/warning behavior as `get`. pub async fn post_json_with_token( label: &str, uri: &str, token: &str, body: &serde_json::Value, ) -> Response { let start = Instant::now(); let request = Request::builder() .method(Method::POST) .uri(uri) .extension(ConnectInfo(local_peer())) .header("content-type", "application/json") .header("Authorization", format!("Bearer {token}")) .body(Body::from(serde_json::to_vec(body).unwrap())) .unwrap(); let response = genenetwork4::app().oneshot(request).await.unwrap(); let elapsed = start.elapsed(); if elapsed > SLOW_THRESHOLD { eprintln!("WARNING: {label} took {elapsed:?} (> {SLOW_THRESHOLD:?})"); } response } /// PATCHes `body` as JSON with a bearer token, for the endpoints that edit /// what they stored (`PATCH /baskets/{name}`). pub async fn patch_json_with_token( label: &str, uri: &str, token: &str, body: &serde_json::Value, ) -> Response { let start = Instant::now(); let request = Request::builder() .method(Method::PATCH) .uri(uri) .extension(ConnectInfo(local_peer())) .header("content-type", "application/json") .header("Authorization", format!("Bearer {token}")) .body(Body::from(serde_json::to_vec(body).unwrap())) .unwrap(); let response = genenetwork4::app().oneshot(request).await.unwrap(); let elapsed = start.elapsed(); if elapsed > SLOW_THRESHOLD { eprintln!("WARNING: {label} took {elapsed:?} (> {SLOW_THRESHOLD:?})"); } response } /// DELETEs with a bearer token. pub async fn delete_with_token(label: &str, uri: &str, token: &str) -> Response { let start = Instant::now(); let request = Request::builder() .method(Method::DELETE) .uri(uri) .extension(ConnectInfo(local_peer())) .header("Authorization", format!("Bearer {token}")) .body(Body::empty()) .unwrap(); let response = genenetwork4::app().oneshot(request).await.unwrap(); let elapsed = start.elapsed(); if elapsed > SLOW_THRESHOLD { eprintln!("WARNING: {label} took {elapsed:?} (> {SLOW_THRESHOLD:?})"); } response } /// The `data` of a success response body, after checking that the body /// is the standard envelope: `meta` (state, took_ms, request_id), /// `notes` and `next` next to `data`. pub fn data(body: &[u8]) -> T { let envelope: serde_json::Value = serde_json::from_slice(body).unwrap(); assert!( envelope["meta"]["state"].is_string(), "meta.state in {envelope}" ); assert!( envelope["meta"]["took_ms"].is_u64(), "meta.took_ms in {envelope}" ); assert!(envelope["notes"].is_array(), "notes in {envelope}"); assert!(envelope["next"].is_array(), "next in {envelope}"); serde_json::from_value(envelope["data"].clone()).unwrap() }