Skip to main content

mold_server/
test_support.rs

1//! Lightweight in-process test client for catalog route integration tests.
2//! Avoids the full hyper boot — uses `tower::ServiceExt::oneshot` directly.
3
4use axum::body::Body;
5use axum::http::{Request, StatusCode};
6use tower::ServiceExt;
7
8#[cfg(test)]
9pub fn env_lock() -> &'static std::sync::Mutex<()> {
10    static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
11    &ENV_LOCK
12}
13
14pub struct TestResponse {
15    pub status: StatusCode,
16    pub body: String,
17}
18
19pub struct TestApp {
20    router: axum::Router,
21}
22
23impl TestApp {
24    /// Build an empty AppState (catalog endpoints proxy live HF/Civitai;
25    /// tests that exercise live behaviour point catalog_live_civitai_base
26    /// at a wiremock instance via `with_civitai_base`).
27    pub async fn with_seeded_catalog() -> Self {
28        let state = crate::state::AppState::for_tests();
29        let router = crate::routes::create_router(state);
30        Self { router }
31    }
32
33    pub async fn get(&self, uri: &str) -> TestResponse {
34        let req = Request::builder().uri(uri).body(Body::empty()).unwrap();
35        let resp = self.router.clone().oneshot(req).await.unwrap();
36        let status = resp.status();
37        let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
38            .await
39            .unwrap();
40        let body = String::from_utf8(bytes.to_vec()).unwrap();
41        TestResponse { status, body }
42    }
43
44    pub async fn post_json(&self, uri: &str, body: &str) -> TestResponse {
45        let req = Request::builder()
46            .method("POST")
47            .uri(uri)
48            .header("content-type", "application/json")
49            .body(Body::from(body.to_string()))
50            .unwrap();
51        let resp = self.router.clone().oneshot(req).await.unwrap();
52        let status = resp.status();
53        let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
54            .await
55            .unwrap();
56        let body = String::from_utf8(bytes.to_vec()).unwrap();
57        TestResponse { status, body }
58    }
59}