diff options
| author | Alexander_Kabui <alexanderkabui@proton.me> | 2026-11-16 13:28:55 +0300 |
|---|---|---|
| committer | Alexander_Kabui <alexanderkabui@proton.me> | 2026-11-17 14:06:50 +0300 |
| commit | e13bbd27d0b7addd277d0f50d9e90fee2a936211 (patch) | |
| tree | c715d1e28b0b22ed9d7e0060428cacbd5af7df20 | |
| parent | 204fde4eca2c83c57a1306ba65d9462dbf45c6e6 (diff) | |
| download | genenetwork4-e13bbd27d0b7addd277d0f50d9e90fee2a936211.tar.gz | |
* tests (search): the extracted engine through the seam and the route.
Two tests keep the extraction honest: one asserts the seam's three promises (a malformed query stays the 422 class, an unset index is a named misconfiguration, a hit crosses with unknown keys), and one drives GET /search through the app so the envelope and the token check are exercised with the engine in another crate.
| -rw-r--r-- | tests/search_crate_engine.rs | 126 | ||||
| -rw-r--r-- | tests/search_crate_http.rs | 108 |
2 files changed, 234 insertions, 0 deletions
diff --git a/tests/search_crate_engine.rs b/tests/search_crate_engine.rs new file mode 100644 index 0000000..446bbf5 --- /dev/null +++ b/tests/search_crate_engine.rs @@ -0,0 +1,126 @@ +//! Does GN4 link the extracted engine, and does the seam keep its promises? +//! +//! Three assertions that are true of the SHIPPED contract and need nothing +//! external — no index, no database, no network: +//! 1 a malformed query is the 422 class, decided before any index is opened; +//! 2 an unset index path is `Internal` and names `XAPIAN_DB_PATH`, which is +//! the same guard `SEARCH_ENGINE=native` and `SEARCH_ENGINE=crate` reach; +//! 3 a hit crosses the seam with its unknown keys intact. +//! +//! Re-baselined when the engine moved into the crate: the previous version +//! asserted that the crate's fixture test double answered `""` with five +//! recorded hits, which is exactly the fabricated-result behaviour the move +//! removed (an unset index must never look like a successful search). The +//! hit in assertion 3 is therefore constructed, not fetched. + +use std::collections::BTreeMap; + +use genenetwork4::search::{SearchError, SearchHit}; + +#[test] +fn a_malformed_query_is_the_route_422_class() { + // A numeric bound that is not a number: the engine's app-level guard + // rejects it before the index is opened, so this is InvalidQuery even + // with no index configured at all. + let error = gn_search_engine::search("", "alcohol mean:abc..def", "phenotype", 5, 1) + .expect_err("a non-numeric range bound is rejected"); + match error { + gn_search_engine::SearchError::InvalidQuery { + message, + xapian_error_type, + } => { + assert_eq!(message, "Unknown range operation"); + assert!( + xapian_error_type.as_deref() == Some("QueryParserError"), + "the class travels with the rejection, got {xapian_error_type:?}" + ); + } + other => panic!("expected InvalidQuery, got {other:?}"), + } + // The same for a query the parser itself cannot read. + match gn_search_engine::search("", "alcohol AND", "phenotype", 5, 1) { + Err(SearchError::InvalidQuery { + xapian_error_type, .. + }) => assert_eq!(xapian_error_type.as_deref(), Some("QueryParserError")), + other => panic!("expected InvalidQuery, got {other:?}"), + } +} + +#[test] +fn an_unset_index_path_is_a_named_misconfiguration() { + // The one guard both engine names reach: no index path is a local + // misconfiguration (500 `internal_error`), never a hit set and never an + // empty page. + match gn_search_engine::search("", "alcohol", "phenotype", 5, 1) { + Err(SearchError::Internal(message)) => { + assert!( + message.contains("XAPIAN_DB_PATH is not configured"), + "the error must name the config key an operator sets, got {message:?}" + ); + } + other => panic!("expected Internal, got {other:?}"), + } + // And a path that is not an index is the unreachable class, not Internal: + // the two pre-checks are distinct (502 `backend_unreachable`). + match gn_search_engine::search( + "/nonexistent/gn4-crate-engine-test", + "alcohol", + "phenotype", + 5, + 1, + ) { + Err(SearchError::Unreachable(_)) => {} + other => panic!("expected Unreachable, got {other:?}"), + } +} + +#[test] +fn a_crate_hit_deserialises_into_the_route_hit_without_losing_keys() { + // One shape, one definition: `genenetwork4::search::SearchHit` IS + // `gn_search_engine::SearchHit` (re-exported, not redeclared), so a hit built + // with the crate's constructor must survive serialisation into the + // route's type with the unknown keys the proxy path relies on. + let mut extra = BTreeMap::new(); + extra.insert( + "pubmed_link".to_string(), + serde_json::json!("https://pubmed.ncbi.nlm.nih.gov/23247194/"), + ); + let hit = gn_search_engine::SearchHit { + name: Some("10199".to_string()), + dataset: Some("C57BL-6JxC57BL-6NJF2Publish".to_string()), + dataset_fullname: None, + group: None, + species: Some("mouse".to_string()), + authors: None, + year: None, + description: None, + mean: None, + additive: None, + lrs: Some(6.62875131299756), + lod: None, + locus: None, + abbreviation: None, + geno_chr: None, + geno_mb: None, + inbredsetcode: None, + pubmed_id: None, + extra, + }; + let value = serde_json::to_value(&hit).expect("serialisable"); + let route_hit: SearchHit = serde_json::from_value(value).expect("the shapes agree"); + assert_eq!(route_hit.name.as_deref(), Some("10199")); + assert_eq!( + route_hit.dataset.as_deref(), + Some("C57BL-6JxC57BL-6NJF2Publish") + ); + assert_eq!( + route_hit.extra.get("pubmed_link"), + Some(&serde_json::json!( + "https://pubmed.ncbi.nlm.nih.gov/23247194/" + )), + "the unknown key survives the seam" + ); + // `SearchError` is the crate's type too, so the route's mapping is not a + // twin that could drift from it. + let _: Option<SearchError> = None; +} diff --git a/tests/search_crate_http.rs b/tests/search_crate_http.rs new file mode 100644 index 0000000..7248dca --- /dev/null +++ b/tests/search_crate_http.rs @@ -0,0 +1,108 @@ +//! Does the ROUTE serve the extracted engine end to end? +//! +//! The seam tests prove the engine answers; this proves the HTTP contract above +//! it — auth, envelope, `lod`, `next` links — is produced unchanged when the +//! engine lives in another crate. +//! +//! Needs `XAPIAN_DB_PATH` pointing at a real index (the 47,040-doc dev index) +//! and `SEARCH_ENGINE=crate`. Hermetic otherwise: no gn3, no network. + +use axum::body::Body; +use axum::http::{Request, StatusCode}; +use http_body_util::BodyExt; +use tower::util::ServiceExt; + +const TEST_JWKS: &str = include_str!("../test/data/test_jwks.json"); +use axum::{routing::get, Router}; + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn the_route_serves_the_extracted_engine() { + unsafe { + std::env::set_var("SEARCH_ENGINE", "crate"); + std::env::set_var( + "XAPIAN_DB_PATH", + std::env::var("XAPIAN_DB_PATH").unwrap_or_else(|_| { + format!("{}/xapian-index-dev", std::env::var("HOME").unwrap_or_default()) + }), + ); + } + + // gn-auth's JWKS stub: token verification must not need a live gn-auth. + let auth_stub = { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + let app = Router::new().route( + "/auth/public-jwks", + get(|| async { (StatusCode::OK, TEST_JWKS) }), + ); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + format!("http://127.0.0.1:{port}") + }; + unsafe { std::env::set_var("AUTH_SERVER_URL", &auth_stub) }; + let token = gn4_test_token(&auth_stub); + let response = genenetwork4::app() + .oneshot( + Request::builder() + .uri("/search?q=alcohol&type=phenotype&limit=3") + .header("Authorization", format!("Bearer {token}")) + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + + let status = response.status(); + let body = response.into_body().collect().await.unwrap().to_bytes(); + let text = String::from_utf8_lossy(&body).to_string(); + let json: serde_json::Value = + serde_json::from_str(&text).unwrap_or_else(|e| panic!("json body ({e}); status={status}; body={text:?}")); + + assert_eq!(status, StatusCode::OK, "route status; body={json}"); + let hits = json + .get("data") + .and_then(|d| d.as_array()) + .or_else(|| json.as_array()) + .expect("hits array in the envelope"); + assert!( + !hits.is_empty(), + "the engine returned no hits for a query the index answers; body={json}" + ); + let first = &hits[0]; + assert!(first.get("dataset").is_some(), "a hit carries its dataset"); + assert!(first.get("name").is_some(), "a hit carries its name"); + println!( + "route served {} hit(s), first {}/{}", + hits.len(), + first.get("dataset").and_then(|v| v.as_str()).unwrap_or("?"), + first.get("name").and_then(|v| v.as_str()).unwrap_or("?") + ); +} + +/// A token the dev issuer accepts (same shape gn4's own search tests mint). +fn gn4_test_token(issuer: &str) -> String { + use jsonwebtoken::{encode, Algorithm, EncodingKey, Header}; + use serde::Serialize; + const TEST_PRIVATE_KEY: &str = include_str!("../test/data/test_rsa_private.pem"); + #[derive(Serialize)] + struct Claims { + sub: String, + scope: String, + iss: String, + iat: u64, + exp: u64, + } + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs(); + let iss = issuer.to_string(); + let claims = Claims { + sub: "crate-http-test".into(), + scope: "profile".into(), + iss, + iat: now, + exp: now + 3600, + }; + let key = EncodingKey::from_rsa_pem(TEST_PRIVATE_KEY.as_bytes()).unwrap(); + encode(&Header::new(Algorithm::RS256), &claims, &key).unwrap() +} |
