use std::collections::BTreeMap;
use std::sync::Mutex;
use bytes::Bytes;
use http::{Method, header};
use serde::Serialize;
use crate::app::{App, Service};
use crate::config::{Config, Env};
use crate::cookies::Cookie;
use crate::db::Repo;
use crate::db::migration::{Migration, Migrator};
use crate::response::Response;
mod ambient;
pub use ambient::{
Form, FormValue, Harness, JsonBody, Status, TestResponse, assert_contains, assert_equal,
assert_not_equal, assert_true, bearer, delete, errors_on, file, get, header, insert, patch,
patch_json, perform_jobs, post, post_json, put, put_json, refute_contains, refute_true, run,
sequence,
};
pub struct TestClient {
service: Service,
cookies: Mutex<BTreeMap<String, String>>,
csrf_token: Mutex<Option<String>>,
headers: Mutex<Vec<(header::HeaderName, header::HeaderValue)>>,
}
pub async fn setup(migrations: Vec<Migration>) -> (Config, Repo) {
let config = Config::load_from("config", Env::Test).expect("loading config/test.toml");
let repo = Repo::from_config(&config)
.await
.expect("connecting to the test database (database.url in config/test.toml)");
Migrator::new(&repo, migrations)
.expect("invalid migrations")
.migrate()
.await
.expect("migrating the test database");
(config, repo)
}
impl TestClient {
pub fn new(mut app: App) -> Self {
app.env.get_or_insert(Env::Test);
Self {
service: app.build(),
cookies: Mutex::default(),
csrf_token: Mutex::default(),
headers: Mutex::default(),
}
}
pub async fn get(&self, path: &str) -> Response {
self.send(Method::GET, path, Bytes::new(), None).await
}
pub async fn delete(&self, path: &str) -> Response {
self.send(Method::DELETE, path, Bytes::new(), None).await
}
pub async fn post_form<T: Serialize + ?Sized>(&self, path: &str, form: &T) -> Response {
self.send_form(Method::POST, path, form).await
}
pub async fn patch_form<T: Serialize + ?Sized>(&self, path: &str, form: &T) -> Response {
self.send_form(Method::PATCH, path, form).await
}
pub async fn post_json<T: Serialize + ?Sized>(&self, path: &str, json: &T) -> Response {
self.send_json(Method::POST, path, json).await
}
pub async fn patch_json<T: Serialize + ?Sized>(&self, path: &str, json: &T) -> Response {
self.send_json(Method::PATCH, path, json).await
}
pub async fn put_json<T: Serialize + ?Sized>(&self, path: &str, json: &T) -> Response {
self.send_json(Method::PUT, path, json).await
}
async fn send_json<T: Serialize + ?Sized>(
&self,
method: Method,
path: &str,
json: &T,
) -> Response {
let body = serde_json::to_vec(json).expect("failed to serialize test JSON");
self.send(method, path, body.into(), Some("application/json"))
.await
}
pub async fn perform_jobs(&self) -> crate::Result<usize> {
let jobs = self
.service
.state::<crate::jobs::Jobs>()
.expect("perform_jobs needs App::jobs")
.clone();
jobs.perform_due().await
}
pub fn bearer(&self, token: impl AsRef<str>) {
self.header("authorization", format!("Bearer {}", token.as_ref()));
}
pub fn header(&self, name: &str, value: impl AsRef<str>) {
let name = header::HeaderName::try_from(name).expect("invalid header name");
let value = header::HeaderValue::try_from(value.as_ref()).expect("invalid header value");
let mut headers = self.headers.lock().unwrap();
headers.retain(|(existing, _)| *existing != name);
headers.push((name, value));
}
pub async fn request(&self, mut req: http::Request<Bytes>) -> Response {
for (name, value) in self.headers.lock().unwrap().iter() {
if !req.headers().contains_key(name) {
req.headers_mut().insert(name.clone(), value.clone());
}
}
let unsafe_method = !matches!(*req.method(), Method::GET | Method::HEAD);
let has_token = req.headers().contains_key(crate::csrf::HEADER)
|| req.body().windows(12).any(|w| w == b"_csrf_token=");
if unsafe_method
&& !has_token
&& let Some(token) = self.csrf_token.lock().unwrap().clone()
{
req.headers_mut().insert(
crate::csrf::HEADER,
token.try_into().expect("invalid CSRF token"),
);
}
if !req.headers().contains_key(header::COOKIE)
&& let Some(cookie) = self.cookie_header()
{
req.headers_mut().insert(
header::COOKIE,
cookie.try_into().expect("invalid cookie header"),
);
}
let res = self.service.call(req).await;
self.store_cookies(&res);
self.remember_csrf_token(&res);
res
}
fn remember_csrf_token(&self, res: &Response) {
let body = res.body();
let marker = format!(r#"name="{}" value=""#, crate::csrf::FORM_FIELD);
let Some(start) = body
.windows(marker.len())
.position(|w| w == marker.as_bytes())
.map(|i| i + marker.len())
else {
return;
};
let token: String = body[start..]
.iter()
.take_while(|b| b.is_ascii_hexdigit())
.map(|&b| b as char)
.collect();
if !token.is_empty() {
*self.csrf_token.lock().unwrap() = Some(token);
}
}
pub fn cookie(&self, name: &str) -> Option<String> {
self.cookies.lock().unwrap().get(name).cloned()
}
pub fn clear_cookies(&self) {
self.cookies.lock().unwrap().clear();
}
fn cookie_header(&self) -> Option<String> {
let cookies = self.cookies.lock().unwrap();
(!cookies.is_empty()).then(|| {
cookies
.iter()
.map(|(name, value)| format!("{name}={value}"))
.collect::<Vec<_>>()
.join("; ")
})
}
fn store_cookies(&self, res: &Response) {
let mut cookies = self.cookies.lock().unwrap();
for value in res.headers().get_all(header::SET_COOKIE) {
let Some(cookie) = value.to_str().ok().and_then(|v| Cookie::parse(v).ok()) else {
continue;
};
let removed = cookie.max_age().is_some_and(|age| age.is_zero());
if removed {
cookies.remove(cookie.name());
} else {
cookies.insert(cookie.name().to_owned(), cookie.value().to_owned());
}
}
}
pub async fn put_form<T: Serialize + ?Sized>(&self, path: &str, form: &T) -> Response {
self.send_form(Method::PUT, path, form).await
}
pub async fn send_form<T: Serialize + ?Sized>(
&self,
method: Method,
path: &str,
form: &T,
) -> Response {
let body = serde_urlencoded::to_string(form).expect("failed to serialize test form");
self.send(
method,
path,
body.into(),
Some("application/x-www-form-urlencoded"),
)
.await
}
async fn send(
&self,
method: Method,
path: &str,
body: Bytes,
content_type: Option<&str>,
) -> Response {
let mut req = http::Request::builder().method(method).uri(path);
if let Some(content_type) = content_type {
req = req.header(header::CONTENT_TYPE, content_type);
}
self.request(req.body(body).expect("invalid test request"))
.await
}
}