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;
mod fake;
mod select;
mod snapshot;
pub use ambient::{
Form, FormValue, Harness, JsonBody, Status, TestResponse, assert_contains, assert_equal,
assert_not_equal, assert_true, basic_auth, bearer, cycle, delete, delete_json, errors_on, file,
get, header, insert, insert_for, patch, patch_json, path_prefix, perform_jobs, post, post_json,
put, put_json, recycle, recycled_or, refute_contains, refute_true, run, run_task, sequence,
set_cookie, test_config,
};
pub use fake::Fake;
pub use select::{
HtmlBody, assert_select, assert_select_count, assert_select_text, refute_select, select_text,
};
pub use snapshot::{Snapshot, assert_snapshot, assert_snapshot_redacted};
pub struct TestClient {
service: Service,
cookies: Mutex<BTreeMap<String, String>>,
csrf_token: Mutex<Option<String>>,
headers: Mutex<Vec<(header::HeaderName, header::HeaderValue)>>,
prefix: Mutex<Option<String>>,
pub(crate) cycles: Mutex<std::collections::HashMap<(&'static str, u32, u32), usize>>,
pub(crate) recycled:
Mutex<std::collections::HashMap<std::any::TypeId, Box<dyn std::any::Any + Send>>>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Enqueued {
pub name: String,
pub args: serde_json::Value,
pub queue: String,
pub run_at: crate::db::Timestamp,
}
#[doc(hidden)]
pub async fn scope<F: std::future::Future>(fut: F) -> F::Output {
let fut = crate::client::with_fake(crate::cache::with_test_store(fut));
let fut = crate::process::with_fake(fut);
let fut = crate::billing::with_test_slot(crate::webhooks::with_test_slot(fut));
let fut = crate::pdf::with_test_recorder(fut);
crate::time::with_test_clock(crate::mail::with_test_mailbox(fut)).await
}
pub fn stub_request(method: &str, pattern: &str, status: u16, body: serde_json::Value) -> Stubbed {
stub_answer(method, pattern, json_answer(status, &body))
}
pub fn stub_request_text(method: &str, pattern: &str, status: u16, body: &str) -> Stubbed {
stub_answer(method, pattern, text_answer(status, body))
}
pub fn stub_failure(method: &str, pattern: &str, kind: &str) -> Stubbed {
stub_answer(method, pattern, crate::client::fail(kind))
}
fn stub_answer(method: &str, pattern: &str, answer: crate::client::Answer) -> Stubbed {
let method = (method != "*").then(|| method.parse::<http::Method>().expect("an HTTP method"));
Stubbed(crate::client::stub(method, pattern, answer))
}
fn json_answer(status: u16, body: &serde_json::Value) -> crate::client::Answer {
let status = http::StatusCode::from_u16(status).expect("an HTTP status");
crate::client::respond(status, body.to_string().into(), "application/json")
}
fn text_answer(status: u16, body: &str) -> crate::client::Answer {
let status = http::StatusCode::from_u16(status).expect("an HTTP status");
crate::client::respond(status, body.to_owned().into(), "text/plain; charset=utf-8")
}
#[derive(Debug, Clone, Copy)]
pub struct Stubbed(usize);
impl Stubbed {
pub fn header(self, name: &str, value: &str) -> Self {
crate::client::with_stub(self.0, |answers| {
if let Some(last) = answers.last_mut() {
crate::client::add_header(last, name, value);
}
});
self
}
pub fn then(self, status: u16, body: serde_json::Value) -> Self {
crate::client::with_stub(self.0, |answers| answers.push(json_answer(status, &body)));
self
}
pub fn then_text(self, status: u16, body: &str) -> Self {
crate::client::with_stub(self.0, |answers| answers.push(text_answer(status, body)));
self
}
pub fn then_fail(self, kind: &str) -> Self {
crate::client::with_stub(self.0, |answers| answers.push(crate::client::fail(kind)));
self
}
}
pub async fn assert_stored(key: &str) -> crate::Result<()> {
let stored = crate::storage::current().exists(key).await?;
assert!(
stored,
"expected a stored file at `{key}`, but there's none"
);
Ok(())
}
pub async fn assert_missing(key: &str) -> crate::Result<()> {
let stored = crate::storage::current().exists(key).await?;
assert!(
!stored,
"expected no stored file at `{key}`, but there's one"
);
Ok(())
}
pub fn stub_process(program: &str, status: i32, stdout: &str) {
crate::process::stub(program, status, stdout);
}
pub fn processes_run() -> Vec<Vec<String>> {
crate::process::ran()
}
pub fn requests() -> Vec<crate::client::Requested> {
crate::client::requested()
}
pub fn delivered_mail() -> Vec<crate::mail::Mail> {
crate::mail::delivered()
}
pub fn clear_delivered_mail() {
crate::mail::clear_delivered();
}
pub async fn enqueued_jobs() -> crate::Result<Vec<Enqueued>> {
let rows = crate::db::sql(
"SELECT name, queue, args, run_at FROM glacier_jobs \
WHERE locked_at IS NULL AND failed_at IS NULL ORDER BY id",
)
.fetch_all()
.await?;
rows.iter()
.map(|row| {
let args: String = row.get("args")?;
Ok(Enqueued {
name: row.get("name")?,
args: crate::jobs::own_args(serde_json::from_str(&args)?),
queue: row.get("queue")?,
run_at: row.get("run_at")?,
})
})
.collect()
}
pub fn travel_to(at: impl Moment) {
assert!(
crate::time::set_clock(Some(at.moment())),
"travel_to works inside a #[glacier::test]"
);
}
pub trait Moment {
fn moment(self) -> crate::db::Timestamp;
}
impl Moment for crate::db::Timestamp {
fn moment(self) -> crate::db::Timestamp {
self
}
}
impl Moment for &str {
fn moment(self) -> crate::db::Timestamp {
crate::time::parse(self, "UTC").unwrap_or_else(|| panic!("`{self}` isn't a time"))
}
}
pub fn travel(by: chrono::TimeDelta) {
travel_to(crate::time::now() + by);
}
pub fn freeze_time() {
travel_to(crate::time::now());
}
pub fn rendered_pdfs() -> Vec<crate::pdf::Rendered> {
crate::pdf::rendered()
}
pub fn travel_back() {
crate::time::set_clock(None);
}
pub async fn queries<F: Future>(fut: F) -> (F::Output, Vec<String>) {
crate::db::logging_queries(fut).await
}
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 {
crate::access::strict(true);
app.env.get_or_insert(Env::Test);
Self {
service: app.build(),
cookies: Mutex::default(),
csrf_token: Mutex::default(),
headers: Mutex::default(),
prefix: Mutex::default(),
cycles: Mutex::default(),
recycled: Mutex::default(),
}
}
pub fn service(&self) -> &crate::app::Service {
&self.service
}
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 fn config(&self) -> crate::Config {
self.service
.state::<crate::Config>()
.cloned()
.expect("the app has no Config: App::config registers it")
}
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 async fn run_task(&self, name: &str, args: Vec<String>) -> crate::Result<()> {
let task = self
.service
.task(name)
.unwrap_or_else(|| panic!("the app has no task `{name}` (src/tasks.glacier)"));
(task.run)(args).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 fn path_prefix(&self, prefix: impl Into<String>) {
*self.prefix.lock().unwrap() = Some(prefix.into());
}
pub async fn request(&self, mut req: http::Request<Bytes>) -> Response {
if let Some(prefix) = self.prefix.lock().unwrap().clone() {
let path = req.uri().path();
let has_it = path == prefix || path.starts_with(&format!("{prefix}/"));
if !has_it {
let uri = match req.uri().query() {
Some(query) => format!("{prefix}{path}?{query}"),
None => format!("{prefix}{path}"),
};
if let Ok(uri) = uri.parse() {
*req.uri_mut() = uri;
}
}
}
for (name, value) in self.headers.lock().unwrap().iter() {
if !req.headers().contains_key(name) {
req.headers_mut().insert(name.clone(), value.clone());
}
}
if !req.headers().contains_key(header::HOST) && req.uri().authority().is_none() {
req.headers_mut()
.insert(header::HOST, http::HeaderValue::from_static("localhost"));
}
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=")
|| req.body().windows(19).any(|w| w == b"name=\"_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 (method, path) = (req.method().clone(), req.uri().path().to_owned());
let res = self.service.call(req).await;
if res.status().is_server_error()
&& let Some(report) = res.extensions().get::<crate::error::ErrorReport>()
{
eprintln!(
"{method} {path} answered {}: {}",
report.status, report.message
);
for cause in &report.causes {
eprintln!(" caused by: {cause}");
}
}
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 set_cookie(&self, name: &str, value: impl Into<String>) {
self.cookies
.lock()
.unwrap()
.insert(name.to_owned(), value.into());
}
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
}
}