li7y/tests/common/mod.rs

70 lines
1.7 KiB
Rust
Raw Permalink Normal View History

2024-07-27 22:16:12 +02:00
// SPDX-FileCopyrightText: 2024 Simon Bruder <simon@sbruder.de>
//
// SPDX-License-Identifier: AGPL-3.0-or-later
use std::env;
use actix_http::header;
use actix_web::{cookie::Cookie, dev::ServiceResponse, test};
use clap::Parser;
use serde::Serialize;
use li7y::Config;
pub const SUPERUSER_PASSWORD: &str = "correct horse battery staple";
#[derive(Serialize)]
pub struct LoginForm {
password: String,
}
impl Default for LoginForm {
fn default() -> Self {
Self {
password: SUPERUSER_PASSWORD.to_string(),
}
}
}
pub fn config() -> Config {
env::set_var("SUPERUSER_PASSWORD", SUPERUSER_PASSWORD);
Config::parse_from(Vec::<std::ffi::OsString>::new().iter())
}
#[allow(dead_code)] // for some reason rustc detects this as unused
pub fn assert_redirect(res: ServiceResponse) -> String {
assert!(res.status().is_redirection());
res.headers()
.get(header::LOCATION)
.expect("No location header set when expected")
.to_str()
.expect("Location header is not valid UTF-8")
.to_string()
}
pub async fn session_cookie<'a>(
srv: &impl actix_web::dev::Service<
actix_http::Request,
Response = ServiceResponse<actix_web::body::EitherBody<actix_web::body::BoxBody>>,
Error = actix_web::Error,
>,
) -> Cookie<'a> {
let req = test::TestRequest::post()
.uri("/login")
.set_form(LoginForm::default())
.to_request();
Cookie::parse_encoded(
test::call_service(&srv, req)
.await
.headers()
.get(header::SET_COOKIE)
.unwrap()
.to_str()
.unwrap()
.to_string(),
)
.unwrap()
}