about summary refs log tree commit diff
path: root/tests/peakgenotypes.rs
blob: 56461f84cbba7ae8a09f0c40f3571852162d7008 (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
//! `GET /groups/{group}/traits/{id}/peak-genotypes` and `POST /plot/genotypes`.
//!
//! Returning genotypes is the one thing this API otherwise never does, so the
//! tests are as much about the fence as the data: the marker must sit at a peak
//! the server re-confirms, and only animals with a value get a call.

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

mod common;

async fn ready() -> Option<String> {
    if !common::db_available() {
        eprintln!("skipping: no usable database");
        return None;
    }
    common::auth_token().await
}

/// The peak of a fresh scan, so the marker asked for is genuinely the peak.
async fn scan_peak(token: &str, values: &Value) -> Value {
    let response = common::post_json_with_token(
        "POST /compute/rqtl (peak)",
        "/compute/rqtl",
        token,
        &serde_json::json!({
            "group": "DOL",
            "trait_name": "DOL::10003",
            "samples": values,
        }),
    )
    .await;
    assert_eq!(response.status(), StatusCode::OK);
    let bytes = response.into_body().collect().await.unwrap().to_bytes();
    let envelope: Value = serde_json::from_slice(&bytes).unwrap();
    envelope["data"]["markers"]
        .as_array()
        .unwrap()
        .iter()
        .max_by(|left, right| {
            left[3]
                .as_f64()
                .unwrap()
                .partial_cmp(&right[3].as_f64().unwrap())
                .unwrap()
        })
        .unwrap()
        .clone()
}

#[tokio::test]
async fn the_peak_markers_genotypes_come_back_for_animals_with_values() {
    let Some(token) = ready().await else { return };
    let values = common::get_with_token(
        "GET /groups/DOL/traits/10003/values",
        "/groups/DOL/traits/10003/values",
        &token,
    )
    .await;
    assert_eq!(values.status(), StatusCode::OK);
    let bytes = values.into_body().collect().await.unwrap().to_bytes();
    let values: Value = common::data(&bytes);

    let peak = scan_peak(&token, &values).await;
    let marker = peak[0].as_str().unwrap();
    let response = common::get_with_token(
        "GET .../peak-genotypes",
        &format!("/groups/DOL/traits/10003/peak-genotypes?marker={marker}"),
        &token,
    )
    .await;
    let status = response.status();
    let bytes = response.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();
    let data = &envelope["data"];
    assert_eq!(data["marker"], serde_json::json!(marker));
    assert_eq!(data["chr"], peak[1], "the marker's chromosome comes from the marker table");
    // The scan that confirmed it is in the reply.
    assert_eq!(data["peak"]["marker"], serde_json::json!(marker));
    assert!(data["peak"]["lod"].as_f64().unwrap() >= 3.0);

    let animals = data["animals"].as_array().unwrap();
    assert!(animals.len() > 50, "a real panel: {}", animals.len());
    let mut counted = std::collections::BTreeMap::new();
    for animal in animals {
        assert!(animal["individual"].is_string());
        assert!(animal["genotype"].is_string());
        assert!(
            animal["value"].is_f64() || animal["value"].is_i64(),
            "every animal has a value: {animal}"
        );
        *counted
            .entry(animal["genotype"].as_str().unwrap().to_string())
            .or_insert(0usize) += 1;
    }
    // The counts agree with the animals, which is what the plot's x axis is.
    for (genotype, count) in counted {
        assert_eq!(data["counts"][&genotype].as_u64().unwrap() as usize, count);
    }
    // Only animals with a value are here: the trait has fewer than the panel.
    assert!(
        animals.len() <= 200,
        "no more animals than the panel: {}",
        animals.len()
    );

    // And the plot takes the reply and the values.
    let plot = serde_json::json!({
        "marker": marker,
        "genotypes": animals.iter().map(|animal| {
            (animal["individual"].as_str().unwrap().to_string(), animal["genotype"].clone())
        }).collect::<std::collections::BTreeMap<_, _>>(),
        "values": values,
    });
    let response = common::post_json_with_token("POST /plot/genotypes", "/plot/genotypes", &token, &plot).await;
    let status = response.status();
    let bytes = response.into_body().collect().await.unwrap().to_bytes();
    assert_eq!(status, StatusCode::OK, "{}", String::from_utf8_lossy(&bytes));
    let svg = String::from_utf8_lossy(&bytes);
    assert!(svg.trim_start().starts_with("<svg"), "an SVG: {}", &svg[..80.min(svg.len())]);
    assert!(svg.contains(marker), "the plot names the marker");
    assert!(svg.contains("<circle"), "one point per animal");
}

#[tokio::test]
async fn a_marker_away_from_the_peak_is_refused() {
    let Some(token) = ready().await else { return };
    let values = common::get_with_token(
        "GET /groups/DOL/traits/10003/values",
        "/groups/DOL/traits/10003/values",
        &token,
    )
    .await;
    assert_eq!(values.status(), StatusCode::OK);
    let bytes = values.into_body().collect().await.unwrap().to_bytes();
    let values: Value = common::data(&bytes);
    let peak = scan_peak(&token, &values).await;

    // A marker on another chromosome is not covered by this hit.
    let response = common::post_json_with_token(
        "POST /compute/rqtl (for a distant marker)",
        "/compute/rqtl",
        &token,
        &serde_json::json!({"group": "DOL", "trait_name": "DOL::10003", "samples": values}),
    )
    .await;
    let bytes = response.into_body().collect().await.unwrap().to_bytes();
    let envelope: Value = serde_json::from_slice(&bytes).unwrap();
    let rows = envelope["data"]["markers"].as_array().unwrap();
    let distant = rows
        .iter()
        .find(|row| row[1] != peak[1])
        .expect("a marker on another chromosome");
    let response = common::get_with_token(
        "GET .../peak-genotypes (distant)",
        &format!(
            "/groups/DOL/traits/10003/peak-genotypes?marker={}",
            distant[0].as_str().unwrap()
        ),
        &token,
    )
    .await;
    assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
    let bytes = response.into_body().collect().await.unwrap().to_bytes();
    let error: Value = serde_json::from_slice(&bytes).unwrap();
    assert_eq!(error["code"], "not_the_peak");
    let detail = error["detail"].as_str().unwrap();
    assert!(detail.contains("Genotypes are only returned at a confirmed hit"), "{detail}");
}