//! The success envelope (src/response.rs): `data` next to `meta`, //! `notes` and `next`, on every endpoint except `/` and `/openapi.json`. use axum::http::StatusCode; use http_body_util::BodyExt; use serde_json::Value; mod common; async fn json_body(response: axum::response::Response) -> (StatusCode, Option, Value) { let status = response.status(); let request_id = response .headers() .get("x-request-id") .map(|v| v.to_str().unwrap().to_string()); let body = response.into_body().collect().await.unwrap().to_bytes(); (status, request_id, serde_json::from_slice(&body).unwrap()) } /// `/version` needs neither a token nor a database. #[tokio::test] async fn version_is_wrapped_in_the_envelope() { let (status, request_id, body) = json_body(common::get("GET /version", "/version").await).await; assert_eq!(status, StatusCode::OK); assert_eq!(body["data"]["name"], "GeneNetwork4"); assert_eq!(body["meta"]["state"], "complete"); assert!(body["meta"]["took_ms"].is_u64()); assert!(request_id.is_some()); assert_eq!(body["meta"]["request_id"].as_str(), request_id.as_deref()); assert_eq!(body["notes"], serde_json::json!([])); // `/version` is the natural first call -- a client asking "what is this // and what is there" -- so it offers the same root links `/species` and // the other listings do, rather than an empty `next`. let next: Vec<&str> = body["next"] .as_array() .unwrap() .iter() .map(|link| link["href"].as_str().unwrap()) .collect(); assert!(next.contains(&"/groups"), "{next:?}"); assert!(next.contains(&"/openapi.json"), "{next:?}"); } /// The two exceptions: a plain-text greeting and the OpenAPI document. #[tokio::test] async fn the_greeting_and_the_openapi_document_are_not_wrapped() { let response = common::get("GET /", "/").await; assert_eq!(response.status(), StatusCode::OK); let body = response.into_body().collect().await.unwrap().to_bytes(); assert_eq!(&body[..], b"Hello, world!"); let (status, _, doc) = json_body(common::get("GET /openapi.json", "/openapi.json").await).await; assert_eq!(status, StatusCode::OK); assert!(doc["openapi"].is_string() && doc.get("meta").is_none()); } /// An error carries the same facts as a success's `meta`: the request id /// (also the `x-request-id` header) and the server's time. This one is /// the token extractor's rejection, which needs no database or gn-auth. #[tokio::test] async fn errors_carry_the_request_id_and_took_ms() { let (status, request_id, body) = json_body(common::get("GET /species", "/species").await).await; assert_eq!(status, StatusCode::UNAUTHORIZED); assert_eq!(body["code"], "invalid_token"); assert!(request_id.is_some()); assert_eq!(body["request_id"].as_str(), request_id.as_deref()); assert!(body["took_ms"].is_u64()); } /// Hrefs not followed: lists of thousands of rows (every trait of a /// group, every probeset of a dataset). fn too_large_to_follow(href: &str) -> bool { href.ends_with("/traits") || href.ends_with("/probesets") } /// The two documents that are deliberately *not* enveloped (see /// `the_greeting_and_the_openapi_document_are_not_wrapped`). They are still /// legitimate `next` links -- the API document is a resource -- so they are /// followed and must answer 200, just without an envelope to inspect. fn not_enveloped(href: &str) -> bool { href == "/" || href == "/openapi.json" } /// Every endpoint's response is an envelope whose `request_id` is the /// response's `x-request-id`, and every `next` href it suggests is /// itself a 200 envelope. Needs a live MariaDB and a reachable gn-auth. #[tokio::test] async fn next_links_resolve() { if !common::db_available() { eprintln!("skipping next_links_resolve: no usable database (check SQL_URI credentials)"); return; } let Some(token) = common::auth_token().await else { eprintln!("skipping next_links_resolve: no token (see docs/gn-auth.md)"); return; }; if !common::auth_server_available() { eprintln!("skipping next_links_resolve: no gn-auth reachable"); return; } let seeds = [ "/species", "/species/mouse", "/species/mouse/datasets", "/groups", "/groups/BXD", "/groups/BXD/strains", "/groups/BXD/case-attributes", "/groups/BXD/datasets", "/mapping-methods", "/accessions/GN602", "/accessions/GN1", "/groups/BXD/traits?abbreviation=5HT_MB_M", "/groups/BXD/traits/17985", "/groups/BXD/traits/17985/values", "/datasets/Br_U_0803_M", "/datasets/Br_U_0803_M/probesets/100001_at", "/datasets/Br_U_0803_M/probesets/100001_at/values", "/traits/BXDPublish/17985", "/traits/BXDPublish/17985/values", "/publications/24102824/traits", ]; let mut followed = 0; for seed in seeds { let (status, request_id, body) = json_body(common::get_with_token(&format!("GET {seed}"), seed, &token).await).await; assert_eq!(status, StatusCode::OK, "GET {seed}: {body}"); assert_eq!( body["meta"]["request_id"].as_str(), request_id.as_deref(), "{seed}" ); assert!(body["meta"]["took_ms"].is_u64(), "{seed}"); for next in body["next"].as_array().unwrap() { let href = next["href"].as_str().unwrap(); assert!(href.starts_with('/'), "{seed}: relative href, got {href}"); assert!(next["description"].is_string(), "{seed} -> {href}"); if too_large_to_follow(href) { continue; } if href.contains('{') { // A link with a placeholder is guidance for a shape the // caller completes (`.../markers/{marker}/classes?trait= // {trait_id}`), not an address this test can fetch -- but the // description has to say so, or a client reading `next` has no // way to know it must substitute something. let description = next["description"].as_str().unwrap().to_ascii_lowercase(); assert!( description.contains("fill in") || description.contains("substitute"), "{seed} -> {href}: placeholder with no instruction in its description" ); continue; } if not_enveloped(href) { let response = common::get_with_token(&format!("GET {href}"), href, &token).await; assert_eq!(response.status(), StatusCode::OK, "{seed} suggests {href}"); followed += 1; continue; } // Status before parse: an empty body would otherwise panic inside // `json_body` and hide which href produced it. let response = common::get_with_token(&format!("GET {href}"), href, &token).await; let status = response.status(); let bytes = response.into_body().collect().await.unwrap().to_bytes(); assert_eq!( status, StatusCode::OK, "{seed} suggests {href}: {}", String::from_utf8_lossy(&bytes) ); let linked: Value = serde_json::from_slice(&bytes) .unwrap_or_else(|error| panic!("{seed} -> {href}: not JSON: {error}")); assert!(linked["meta"]["state"].is_string(), "{seed} -> {href}"); followed += 1; } } assert!(followed >= 20, "followed only {followed} next links"); }