about summary refs log tree commit diff
path: root/tests/envelope.rs
blob: e14c555d36bd5fa742432eec7f9236d5c8b83d3a (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
//! 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<String>, 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");
}