about summary refs log tree commit diff
path: root/tests/common/mod.rs
blob: 2050cb6b9b99b2f910e81acc394a4d3c717f39da (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
//! 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<String> {
    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<String> {
    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::<serde_json::Value>(&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 <token>` 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 <token>`
/// 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<T: serde::de::DeserializeOwned>(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()
}