about summary refs log tree commit diff
path: root/tests/baskets.rs
blob: af2e507ea68afc58918ffdef1ecee7e4bf6e1a0e (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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
//! Baskets: a user's own column of values, stored in their own SQLite file,
//! and mapped by name.
//!
//! The loop these tests walk is the whole point of the feature: take a trait's
//! values, edit one, map the edit, and be able to say exactly which revision
//! produced the result. MariaDB is never written to -- that is why the store is
//! a per-user file, and why nothing here needs a database it can modify.

use axum::http::StatusCode;
use http_body_util::BodyExt;
use serde_json::Value;

mod common;

/// A name that cannot collide with a previous run of this test.
fn unique() -> String {
    format!(
        "basket-test-{}",
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|elapsed| elapsed.as_millis())
            .unwrap_or(0)
    )
}

async fn trait_values(token: &str) -> Vec<Value> {
    let response = common::get_with_token(
        "GET /groups/BXD/traits/10001/values",
        "/groups/BXD/traits/10001/values",
        token,
    )
    .await;
    assert_eq!(response.status(), StatusCode::OK);
    let bytes = response.into_body().collect().await.unwrap().to_bytes();
    let values: Value = common::data(&bytes);
    values.as_array().unwrap().clone()
}

#[tokio::test]
async fn a_basket_is_created_edited_and_mapped_by_name() {
    let Some(token) = common::auth_token().await else {
        eprintln!("skipping a_basket_is_created_edited_and_mapped_by_name: no token");
        return;
    };
    if !common::db_available() {
        eprintln!("skipping a_basket_is_created_edited_and_mapped_by_name: no database");
        return;
    }
    let name = unique();
    let values = trait_values(&token).await;
    assert!(values.len() > 10);

    // 1. Create it from a published trait's values.
    let created = common::post_json_with_token(
        "POST /baskets",
        "/baskets",
        &token,
        &serde_json::json!({
            "name": name,
            "kind": "trait",
            "description": "one value bumped, one marked missing",
            "base_dataset": "BXD",
            "base_trait": 10001,
            "values": values,
        }),
    )
    .await;
    assert_eq!(created.status(), StatusCode::CREATED);
    let bytes = created.into_body().collect().await.unwrap().to_bytes();
    let basket: Value = common::data(&bytes);
    assert_eq!(basket["revision"], 1);
    assert_eq!(basket["name"], serde_json::json!(name));
    let first_digest = basket["digest"].as_str().unwrap().to_string();
    assert!(basket["values"].as_u64().unwrap() as usize > 10);

    // 2. Edit it: a new revision, and a different identity.
    let mut edited = values.clone();
    let bumped = edited[0]["value"].as_f64().unwrap_or(0.0) + 5.0;
    edited[0]["value"] = serde_json::json!(bumped);
    edited[1]["value"] = serde_json::json!("NA");
    let revised = common::patch_json_with_token("/baskets/{name}", &format!("/baskets/{name}"), &token, &serde_json::json!({ "values": edited })).await;
    assert_eq!(revised.status(), StatusCode::OK);
    let bytes = revised.into_body().collect().await.unwrap().to_bytes();
    let basket: Value = common::data(&bytes);
    assert_eq!(basket["revision"], 2);
    assert_ne!(basket["digest"].as_str().unwrap(), first_digest);
    assert_eq!(basket["missing"], 1, "the NA is a missing value, not a 0");

    // 3. The stored column keeps both what was typed and what it parses to.
    let stored = common::get_with_token(
        "GET /baskets/{name}/values",
        &format!("/baskets/{name}/values"),
        &token,
    )
    .await;
    assert_eq!(stored.status(), StatusCode::OK);
    let bytes = stored.into_body().collect().await.unwrap().to_bytes();
    let envelope: Value = serde_json::from_slice(&bytes).unwrap();
    assert_eq!(
        envelope["meta"]["columns"],
        serde_json::json!(["sample", "raw", "value", "status"])
    );
    let rows = envelope["data"].as_array().unwrap();
    assert_eq!(rows.len(), values.len());
    let raw = rows[0][1].as_str().unwrap();
    assert!(raw.parse::<f64>().is_ok(), "the number is kept as text: {raw}");
    assert_eq!(rows[1][3], "missing");

    // 4. Map it by name. The reply records which revision and digest ran.
    let mapped = common::post_json_with_token(
        "POST /compute/qtl2 (basket)",
        "/compute/qtl2",
        &token,
        &serde_json::json!({
            "group": "BXD",
            "genotype_version": "BXD.4",
            "trait_name": format!("basket:{name}"),
            "basket": name,
        }),
    )
    .await;
    let status = mapped.status();
    let bytes = mapped.into_body().collect().await.unwrap().to_bytes();
    assert_eq!(status, StatusCode::OK, "{}", String::from_utf8_lossy(&bytes));
    let envelope: Value = serde_json::from_slice(&bytes).unwrap();
    assert!(!envelope["data"].as_array().unwrap().is_empty());
    let notes: Vec<&str> = envelope["notes"]
        .as_array()
        .unwrap()
        .iter()
        .map(|note| note.as_str().unwrap())
        .collect();
    let note = notes
        .iter()
        .find(|note| note.starts_with("Basket "))
        .unwrap_or_else(|| panic!("the reply names the basket: {notes:?}"));
    assert!(note.contains("revision 2"), "{note}");
    assert!(note.contains(&name), "{note}");
    assert!(note.contains("digest"), "{note}");

    // 5. The history: an edit keeps the revision it replaced, with its own
    //    timestamp, and an older one can still be read and mapped.
    let history = common::get_with_token(
        "GET /baskets/{name}/revisions",
        &format!("/baskets/{name}/revisions"),
        &token,
    )
    .await;
    assert_eq!(history.status(), StatusCode::OK);
    let bytes = history.into_body().collect().await.unwrap().to_bytes();
    let versions: Value = common::data(&bytes);
    let versions = versions.as_array().unwrap();
    assert_eq!(versions.len(), 2, "revision 1 is still there after the edit");
    assert_eq!(versions[0]["revision"], 1);
    assert_eq!(versions[1]["revision"], 2);
    assert_ne!(versions[0]["digest"], versions[1]["digest"]);
    assert!(versions[0]["created_at"].as_i64().unwrap() > 0);

    let old = common::get_with_token(
        "GET /baskets/{name}/values?revision=1",
        &format!("/baskets/{name}/values?revision=1"),
        &token,
    )
    .await;
    assert_eq!(old.status(), StatusCode::OK);
    let bytes = old.into_body().collect().await.unwrap().to_bytes();
    let envelope: Value = serde_json::from_slice(&bytes).unwrap();
    let old_first = envelope["data"][0][2].as_f64().unwrap();
    assert!(
        (old_first - (bumped - 5.0)).abs() < 1e-6,
        "revision 1 has the published value, not the edit: {old_first}"
    );

    // A pinned revision maps the values it had, so a quoted result can be
    // reproduced after the basket moved on.
    let pinned = common::post_json_with_token(
        "POST /compute/rqtl (pinned revision)",
        "/compute/rqtl",
        &token,
        &serde_json::json!({
            "group": "BXD",
            "genotype_version": "BXD.4",
            "trait_name": format!("basket:{name}@1"),
            "basket": format!("{name}@1"),
        }),
    )
    .await;
    assert_eq!(pinned.status(), StatusCode::OK);
    let bytes = pinned.into_body().collect().await.unwrap().to_bytes();
    let envelope: Value = serde_json::from_slice(&bytes).unwrap();
    let notes: Vec<&str> = envelope["notes"]
        .as_array()
        .unwrap()
        .iter()
        .map(|note| note.as_str().unwrap())
        .collect();
    assert!(
        notes
            .iter()
            .any(|note| note.starts_with("Basket ") && note.contains("revision 1")),
        "the pinned run says which revision it used: {notes:?}"
    );

    // 6. Delete it: the name is free again and the values are gone.
    let deleted = common::delete_with_token(
        "DELETE /baskets/{name}",
        &format!("/baskets/{name}"),
        &token,
    )
    .await;
    assert_eq!(deleted.status(), StatusCode::NO_CONTENT);
    let gone = common::get_with_token(
        "GET /baskets/{name}",
        &format!("/baskets/{name}"),
        &token,
    )
    .await;
    assert_eq!(gone.status(), StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn a_basket_refuses_what_it_cannot_represent() {
    let Some(token) = common::auth_token().await else {
        eprintln!("skipping a_basket_refuses_what_it_cannot_represent: no token");
        return;
    };
    let name = unique();
    // A value that is neither a number nor a missing marker, named in the
    // refusal -- silently dropping it would change the trait without saying so.
    let bad = common::post_json_with_token(
        "POST /baskets (bad value)",
        "/baskets",
        &token,
        &serde_json::json!({
            "name": name,
            "values": [{"name": "BXD1", "value": 1.0}, {"name": "BXD2", "value": "twelve"}],
        }),
    )
    .await;
    assert_eq!(bad.status(), StatusCode::UNPROCESSABLE_ENTITY);
    let bytes = bad.into_body().collect().await.unwrap().to_bytes();
    let error: Value = serde_json::from_slice(&bytes).unwrap();
    assert_eq!(error["code"], "invalid_basket");
    assert!(error["detail"].as_str().unwrap().contains("BXD2"), "{error}");

    // A bad name is refused too, and cannot become a path.
    let bad_name = common::post_json_with_token(
        "POST /baskets (bad name)",
        "/baskets",
        &token,
        &serde_json::json!({
            "name": "../etc/passwd",
            "values": [{"name": "BXD1", "value": 1.0}],
        }),
    )
    .await;
    assert_eq!(bad_name.status(), StatusCode::UNPROCESSABLE_ENTITY);

    // Mapping a basket that does not exist is a 404 that points at /baskets,
    // and a basket plus samples is ambiguous rather than a silent choice.
    let missing = common::post_json_with_token(
        "POST /compute/qtl2 (unknown basket)",
        "/compute/qtl2",
        &token,
        &serde_json::json!({"group": "BXD", "basket": "nonesuch-basket"}),
    )
    .await;
    assert_eq!(missing.status(), StatusCode::NOT_FOUND);
    let bytes = missing.into_body().collect().await.unwrap().to_bytes();
    let error: Value = serde_json::from_slice(&bytes).unwrap();
    assert_eq!(error["code"], "basket_not_found");
    assert!(error["detail"].as_str().unwrap().contains("/baskets"), "{error}");

    let ambiguous = common::post_json_with_token(
        "POST /compute/qtl2 (basket and samples)",
        "/compute/qtl2",
        &token,
        &serde_json::json!({
            "group": "BXD",
            "basket": "any",
            "samples": [{"name": "BXD1", "value": 1.0}],
        }),
    )
    .await;
    assert_eq!(ambiguous.status(), StatusCode::UNPROCESSABLE_ENTITY);
    let bytes = ambiguous.into_body().collect().await.unwrap().to_bytes();
    let error: Value = serde_json::from_slice(&bytes).unwrap();
    assert_eq!(error["code"], "ambiguous_samples");
}