shared/screens/select_org_bucket_measurements/
influx_get_orgs.rs

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
use crate::model::ExampleData;
use crate::screens::input_fields_and_tags::RemoteResource;
use crate::screens::select_org_bucket_measurements::influx_get_orgs_response::{Org, OrgsResult};
use crate::screens::select_org_bucket_measurements::{
    ScEvSelectOrgBucketMeasurement, SelectOrgBucketMeasurementScreenData,
};
use crate::screens_common::model::multi_choice::MultiChoice;
use crate::Event::EvSelectOrgBucketMeasurementScreen;
use crate::{Effect, Event};
use crux_core::Command;

pub fn influx_get_orgs(
    screen_data: &mut SelectOrgBucketMeasurementScreenData,
    example_data: &ExampleData,
) -> Command<Effect, Event> {
    match example_data {
        ExampleData::Tutorial(_) => {
            screen_data.orgs = RemoteResource::Loaded(MultiChoice {
                options: vec![
                    Org {
                        name: "First org".to_string(),
                        id: "1".to_string(),
                    },
                    Org {
                        name: "second org".to_string(),
                        id: "2".to_string(),
                    },
                    Org {
                        name: "Third org".to_string(),
                        id: "3".to_string(),
                    },
                ],
                selected: Some(1),
            });
            crux_core::render::render()
        }
        ExampleData::FakeData => {
            screen_data.orgs = RemoteResource::Loaded(MultiChoice {
                options: vec![
                    Org {
                        name: "First org".to_string(),
                        id: "1".to_string(),
                    },
                    Org {
                        name: "second org".to_string(),
                        id: "2".to_string(),
                    },
                    Org {
                        name: "Third org".to_string(),
                        id: "3".to_string(),
                    },
                ],
                selected: None,
            });
            crux_core::render::render()
        }
        ExampleData::Real => crux_http::command::Http::get(
            screen_data
                .base_url
                .join("/api/v2/orgs")
                .expect("appended static string to create url"),
        )
        .header("Authorization", format!("Token {}", screen_data.api_token))
        .expect_json()
        .build()
        .then_send(construct_response_event),
    }
}

//  F: FnOnce(crate::Result<Response<ExpectBody>>) -> Event + Send + 'static,
fn construct_response_event(body: crux_http::Result<crux_http::Response<OrgsResult>>) -> Event {
    EvSelectOrgBucketMeasurementScreen(ScEvSelectOrgBucketMeasurement::InfluxGetOrgsResponse(body))
}

// todo come up with unhappy tests malformed base url and such, ideally i should catch that earlier but good to check again
#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::{Model, Screens};
    use crate::screens::select_org_bucket_measurements::influx_get_orgs_response::Org;
    use crate::{Counter, Effect};
    use crux_core::{assert_effect, testing::AppTester};
    use crux_http::http::Url;
    use crux_http::{
        protocol::{HttpRequest, HttpResponse},
        testing::ResponseBuilder,
    };

    #[test]
    fn confirm_happy_path() {
        // instantiate our app via the test harness, which gives us access to the model
        let app = AppTester::<Counter>::default();

        // set up our initial model
        let mut model = Model {
            screen: Screens::SelectOrgBucketMeasurementScreen(Box::from(
                SelectOrgBucketMeasurementScreenData {
                    base_url: Url::parse("http://notaurl.com").unwrap(),
                    api_token: "some random token".to_owned(),
                    ..Default::default()
                },
            )),
            ..Default::default()
        };

        // send a `Get` event to the app
        let mut update = app.update(
            EvSelectOrgBucketMeasurementScreen(ScEvSelectOrgBucketMeasurement::InfluxGetOrgs),
            &mut model,
        );

        assert_effect!(update, Effect::Http(_));
        let Effect::Http(ref mut request) = update.effects[0] else {
            panic!("Not HTTP Effect")
        };

        // check that the request is a GET to the correct URL
        let actual = &request.operation;
        let expected = &HttpRequest::get("http://notaurl.com/api/v2/orgs")
            .header("authorization", "Token some random token")
            .build();
        assert_eq!(actual, expected);

        // resolve the request with a simulated response from the web API
        let response = HttpResponse::ok()
            .body(
                r#"
                {
                  "links": {
                    "self": "/api/v2/orgs"
                  },
                  "orgs": [
                    {
                      "createdAt": "2022-07-17T23:00:30.778487Z",
                      "description": "Example InfluxDB organization",
                      "id": "INFLUX_ORG_ID",
                      "links": {
                        "buckets": "/api/v2/buckets?org=INFLUX_ORG",
                        "dashboards": "/api/v2/dashboards?org=INFLUX_ORG",
                        "labels": "/api/v2/orgs/INFLUX_ORG_ID/labels",
                        "logs": "/api/v2/orgs/INFLUX_ORG_ID/logs",
                        "members": "/api/v2/orgs/INFLUX_ORG_ID/members",
                        "owners": "/api/v2/orgs/INFLUX_ORG_ID/owners",
                        "secrets": "/api/v2/orgs/INFLUX_ORG_ID/secrets",
                        "self": "/api/v2/orgs/INFLUX_ORG_ID",
                        "tasks": "/api/v2/tasks?org=InfluxData"
                      },
                      "name": "INFLUX_ORG",
                      "updatedAt": "2022-07-17T23:00:30.778487Z"
                    }
                  ]
                }
            "#,
            )
            .build();
        let update = app
            .resolve(request, crux_http::protocol::HttpResult::Ok(response))
            .expect("an update");

        // check that the app emitted an (internal) event to update the model
        // let actual = update.events;
        let expected = ResponseBuilder::ok()
            .header("content-type", "application/oct et-stream")
            .body(OrgsResult {
                orgs: vec![Org {
                    name: "INFLUX_ORG".to_owned(),
                    id: "INFLUX_ORG_ID".to_owned(),
                }],
            })
            .build();
        let EvSelectOrgBucketMeasurementScreen(
            ScEvSelectOrgBucketMeasurement::InfluxGetOrgsResponse(actual),
        ) = &update.events[0]
        else {
            panic!("Not InfluxBucketsConnectionResponse")
        };
        assert_eq!(actual.clone().unwrap().body(), expected.body());
    }
}