summaryrefslogtreecommitdiff
path: root/server/src/tests.rs
blob: b6476a0e51f47e700905150364f43a71241b84b3 (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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
use rocket::figment::util::map;
use rocket::figment::value::{Map, Value};
use rocket::http::{ContentType, Header, Status};
use rocket::local::asynchronous::{Client, LocalRequest};
use sqlx::mysql::{MySql, MySqlConnectOptions, MySqlPoolOptions};
use sqlx::{Acquire, Executor, Pool};
use std::sync::OnceLock;
use stdext::function_name;

use crate::api_model;

struct RealIP(&'static str);

impl From<&RealIP> for Header<'static> {
    fn from(ip: &RealIP) -> Header<'static> {
        Header::new("X-Real-IP", ip.0)
    }
}

static FAKE_IP: RealIP = RealIP("127.0.1.10");
static ANOTHER_FAKE_IP: RealIP = RealIP("192.168.0.1");

static MASTER_POOL: OnceLock<Pool<MySql>> = OnceLock::new();

fn find_password(url: &'_ str) -> Option<&'_ str> {
    let protocol = url.find("://");
    if protocol.is_none() {
        return None;
    }
    let specific = &url[protocol.unwrap() + 3..];
    let at = specific.find('@');
    if at.is_none() {
        return None;
    }
    let auth = &specific[0..at.unwrap()];
    let colon = auth.find(':');
    if colon.is_none() {
        return None;
    }
    return Some(&auth[colon.unwrap() + 1..]);
}

fn make_db_name_safe(name: &str) -> String {
    let mut ret = String::new();
    for c in name.chars() {
        if c >= 'a' && c <= 'z' {
            ret.push(c);
        } else if c >= '0' && c <= '9' {
            ret.push(c);
        } else {
            ret.push('_');
        }
    }
    return ret;
}

async fn async_client_with_private_database(test_name: String) -> Client {
    let base_figment = rocket::Config::figment();

    let base_url_value = base_figment
        .find_value("databases.eyeballs.url")
        .expect("database_url");
    let base_url = base_url_value.as_str().expect("database_url as string");
    let base_options: MySqlConnectOptions = base_url.parse().expect("valid database_url");

    let maybe_password = find_password(base_url);

    let database =
        make_db_name_safe(&format!("_{}", test_name.trim_end_matches("::{{closure}}"))[..]);

    // Cannot get sqlx::test (0.7.4) to work with MySQL, always errors out
    // with connection (already?) closed when closing the setup connection.
    // So doing our own lazier setup where each test gets a db based on
    // their name.
    {
        let mut pool_conn = MASTER_POOL
            .get_or_init(|| {
                let options: MySqlConnectOptions =
                    base_url_value.as_str().unwrap().parse().unwrap();

                MySqlPoolOptions::new()
                    .max_connections(20)
                    .after_release(|_conn, _| Box::pin(async move { Ok(false) }))
                    .connect_lazy_with(options)
            })
            .acquire()
            .await
            .unwrap();

        let conn = pool_conn.acquire().await.unwrap();
        conn.execute(&format!("DROP DATABASE IF EXISTS {database}")[..])
            .await
            .unwrap();
        conn.execute(&format!("CREATE DATABASE {database}")[..])
            .await
            .unwrap();
    }

    let db_url = format!(
        "mysql://{}{}@{}:{}/{}",
        base_options.get_username(),
        if let Some(password) = maybe_password {
            format!(":{}", password)
        } else {
            "".to_string()
        },
        base_options.get_host(),
        base_options.get_port(),
        database,
    );

    let db_config: Map<_, Value> = map! {
        "url" => db_url.into(),
    };

    let figment = base_figment.merge(("databases", map!["eyeballs" => db_config]));

    Client::tracked(crate::rocket_from_config(figment))
        .await
        .expect("valid rocket instance")
}

async fn get_status_from<'a>(request: LocalRequest<'a>) -> api_model::StatusResponse {
    request
        .header(&FAKE_IP)
        .dispatch()
        .await
        .into_json::<api_model::StatusResponse>()
        .await
        .unwrap()
}

async fn get_status<'a>(client: &Client) -> api_model::StatusResponse {
    get_status_from(client.get("/api/v1/status")).await
}

async fn login(client: &Client) {
    let login = get_status_from(
        client
            .post("/api/v1/login")
            .body("username=user&password=password")
            .header(ContentType::Form),
    )
    .await;
    assert_eq!(login.ok, true);
}

async fn get_projects<'a>(client: &Client) -> api_model::Projects {
    client
        .get("/api/v1/projects")
        .header(&FAKE_IP)
        .dispatch()
        .await
        .into_json::<api_model::Projects>()
        .await
        .unwrap()
}

async fn get_project_from<'a>(request: LocalRequest<'a>) -> api_model::Project {
    request
        .header(&FAKE_IP)
        .dispatch()
        .await
        .into_json::<api_model::Project>()
        .await
        .unwrap()
}

async fn get_users<'a>(client: &Client) -> api_model::Users {
    client
        .get("/api/v1/users")
        .header(&FAKE_IP)
        .dispatch()
        .await
        .into_json::<api_model::Users>()
        .await
        .unwrap()
}

async fn new_project(client: &Client) -> api_model::Project {
    get_project_from(
        client
            .post("/api/v1/project/new")
            .json(&api_model::ProjectData {
                title: Some("foo"),
                description: Some("bar"),
            }),
    )
    .await
}

#[rocket::async_test]
async fn test_not_logged_in_status() {
    let client = async_client_with_private_database(function_name!().to_string()).await;
    let not_logged_in = get_status(&client).await;
    assert_eq!(not_logged_in.ok, false);
}

#[rocket::async_test]
async fn test_login_status() {
    let client = async_client_with_private_database(function_name!().to_string()).await;

    login(&client).await;

    let logged_in = get_status(&client).await;
    assert_eq!(logged_in.ok, true);
}

#[rocket::async_test]
async fn test_bad_login_status() {
    let client = async_client_with_private_database(function_name!().to_string()).await;

    let bad_password = client
        .post("/api/v1/login")
        .body("username=user&password=incorrect")
        .header(ContentType::Form)
        .header(&FAKE_IP)
        .dispatch()
        .await;
    assert_eq!(bad_password.status(), Status::Unauthorized);

    let bad_username = client
        .post("/api/v1/login")
        .body("username=incorrect&password=password")
        .header(ContentType::Form)
        .header(&FAKE_IP)
        .dispatch()
        .await;
    assert_eq!(bad_username.status(), Status::Unauthorized);
}

#[rocket::async_test]
async fn test_change_ip() {
    let client = async_client_with_private_database(function_name!().to_string()).await;

    login(&client).await;

    let new_ip = client
        .get("/api/v1/status")
        .header(&ANOTHER_FAKE_IP)
        .dispatch()
        .await;
    assert_eq!(new_ip.status(), Status::Unauthorized);
}

#[rocket::async_test]
async fn test_logout() {
    let client = async_client_with_private_database(function_name!().to_string()).await;

    login(&client).await;

    let logged_in = get_status(&client).await;
    assert_eq!(logged_in.ok, true);

    let logout = get_status_from(client.get("/api/v1/logout")).await;
    assert_eq!(logout.ok, true);

    let not_logged_in = get_status(&client).await;
    assert_eq!(not_logged_in.ok, false);
}

#[rocket::async_test]
async fn test_projects_empty() {
    let client = async_client_with_private_database(function_name!().to_string()).await;

    login(&client).await;

    let projects = get_projects(&client).await;
    assert_eq!(projects.total_count, 0);
    assert_eq!(projects.more, false);
    assert_eq!(projects.projects.len(), 0);
}

#[rocket::async_test]
async fn test_project_new() {
    let client = async_client_with_private_database(function_name!().to_string()).await;

    login(&client).await;

    let project = new_project(&client).await;

    assert_eq!(project.title, "foo");
    assert_eq!(project.description, "bar");
    assert_eq!(project.users.len(), 1);
    let user = project.users.get(0).unwrap();
    assert_eq!(user.user.username, "user");
    assert_eq!(user.default_role, api_model::UserReviewRole::Reviewer);
    assert_eq!(user.maintainer, true);

    let projects = get_projects(&client).await;
    assert_eq!(projects.total_count, 1);
    assert_eq!(projects.more, false);
    assert_eq!(projects.projects.len(), 1);
    let project_entry = projects.projects.get(0).unwrap();
    assert_eq!(project_entry.id, project.id);
    assert_eq!(project_entry.title, project.title);

    let project2 = get_project_from(client.get(format!("/api/v1/project/{}", project.id))).await;
    assert_eq!(project, project2);
}

#[rocket::async_test]
async fn test_project_update() {
    let client = async_client_with_private_database(function_name!().to_string()).await;

    login(&client).await;

    let project = get_project_from(client.post("/api/v1/project/new").json(
        &api_model::ProjectData {
            title: Some("foo"),
            description: None,
        },
    ))
    .await;

    let project_url = format!("/api/v1/project/{}", project.id);

    let update = client
        .post(project_url.clone())
        .json(&api_model::ProjectData {
            title: None,
            description: Some("bar"),
        })
        .header(&FAKE_IP)
        .dispatch()
        .await;
    assert_eq!(update.status(), Status::Ok);

    let updated_project = get_project_from(client.get(project_url)).await;
    assert_eq!(updated_project.title, project.title);
    assert_eq!(updated_project.description, "bar");
}

#[rocket::async_test]
async fn test_project_new_user() {
    let client = async_client_with_private_database(function_name!().to_string()).await;

    login(&client).await;

    let project = new_project(&client).await;
    let project_url = format!("/api/v1/project/{}", project.id);

    let users = get_users(&client).await;
    let other = users.users.iter().find(|u| u.username == "other").unwrap();

    let new = client
        .post(format!("{project_url}/user/new?userid={}", other.id))
        .json(&api_model::ProjectUserEntryData {
            default_role: Some(api_model::UserReviewRole::Watcher),
            maintainer: Some(true),
        })
        .header(&FAKE_IP)
        .dispatch()
        .await;
    assert_eq!(new.status(), Status::Ok);

    let updated_project = get_project_from(client.get(project_url)).await;
    assert_eq!(updated_project.users.len(), 2);
    let other_entry = updated_project
        .users
        .iter()
        .find(|ue| ue.user.id == other.id)
        .unwrap();
    assert_eq!(other_entry.user, *other);
    assert_eq!(other_entry.default_role, api_model::UserReviewRole::Watcher);
    assert_eq!(other_entry.maintainer, true);
}