1use std::collections::BTreeMap;
25use std::sync::Mutex;
26
27use bytes::Bytes;
28use http::{Method, header};
29use serde::Serialize;
30
31use crate::app::{App, Service};
32use crate::config::{Config, Env};
33use crate::cookies::Cookie;
34use crate::db::Repo;
35use crate::db::migration::{Migration, Migrator};
36use crate::response::Response;
37
38mod ambient;
39mod fake;
40mod select;
41mod snapshot;
42
43pub use ambient::{
44 Form, FormValue, Harness, JsonBody, Status, TestResponse, assert_contains, assert_equal,
45 assert_not_equal, assert_true, basic_auth, bearer, cycle, delete, delete_json, errors_on, file,
46 get, header, insert, insert_for, patch, patch_json, path_prefix, perform_jobs, post, post_json,
47 put, put_json, recycle, recycled_or, refute_contains, refute_true, run, run_task, sequence,
48 set_cookie, test_config,
49};
50pub use fake::Fake;
51pub use select::{
52 HtmlBody, assert_select, assert_select_count, assert_select_text, refute_select, select_text,
53};
54pub use snapshot::{Snapshot, assert_snapshot, assert_snapshot_redacted};
55
56pub struct TestClient {
57 service: Service,
58 cookies: Mutex<BTreeMap<String, String>>,
59 csrf_token: Mutex<Option<String>>,
60 headers: Mutex<Vec<(header::HeaderName, header::HeaderValue)>>,
62 prefix: Mutex<Option<String>>,
65 pub(crate) cycles: Mutex<std::collections::HashMap<(&'static str, u32, u32), usize>>,
67 pub(crate) recycled:
69 Mutex<std::collections::HashMap<std::any::TypeId, Box<dyn std::any::Any + Send>>>,
70}
71
72#[derive(Debug, Clone, PartialEq)]
74pub struct Enqueued {
75 pub name: String,
77 pub args: serde_json::Value,
80 pub queue: String,
81 pub run_at: crate::db::Timestamp,
83}
84
85#[doc(hidden)]
88pub async fn scope<F: std::future::Future>(fut: F) -> F::Output {
89 let fut = crate::client::with_fake(crate::cache::with_test_store(fut));
90 let fut = crate::process::with_fake(fut);
91 let fut = crate::billing::with_test_slot(crate::webhooks::with_test_slot(fut));
92 let fut = crate::pdf::with_test_recorder(fut);
93 crate::time::with_test_clock(crate::mail::with_test_mailbox(fut)).await
94}
95
96pub fn stub_request(method: &str, pattern: &str, status: u16, body: serde_json::Value) -> Stubbed {
108 stub_answer(method, pattern, json_answer(status, &body))
109}
110
111pub fn stub_request_text(method: &str, pattern: &str, status: u16, body: &str) -> Stubbed {
118 stub_answer(method, pattern, text_answer(status, body))
119}
120
121pub fn stub_failure(method: &str, pattern: &str, kind: &str) -> Stubbed {
129 stub_answer(method, pattern, crate::client::fail(kind))
130}
131
132fn stub_answer(method: &str, pattern: &str, answer: crate::client::Answer) -> Stubbed {
133 let method = (method != "*").then(|| method.parse::<http::Method>().expect("an HTTP method"));
134 Stubbed(crate::client::stub(method, pattern, answer))
135}
136
137fn json_answer(status: u16, body: &serde_json::Value) -> crate::client::Answer {
138 let status = http::StatusCode::from_u16(status).expect("an HTTP status");
139 crate::client::respond(status, body.to_string().into(), "application/json")
140}
141
142fn text_answer(status: u16, body: &str) -> crate::client::Answer {
143 let status = http::StatusCode::from_u16(status).expect("an HTTP status");
144 crate::client::respond(status, body.to_owned().into(), "text/plain; charset=utf-8")
145}
146
147#[derive(Debug, Clone, Copy)]
150pub struct Stubbed(usize);
151
152impl Stubbed {
153 pub fn header(self, name: &str, value: &str) -> Self {
155 crate::client::with_stub(self.0, |answers| {
156 if let Some(last) = answers.last_mut() {
157 crate::client::add_header(last, name, value);
158 }
159 });
160 self
161 }
162
163 pub fn then(self, status: u16, body: serde_json::Value) -> Self {
165 crate::client::with_stub(self.0, |answers| answers.push(json_answer(status, &body)));
166 self
167 }
168
169 pub fn then_text(self, status: u16, body: &str) -> Self {
171 crate::client::with_stub(self.0, |answers| answers.push(text_answer(status, body)));
172 self
173 }
174
175 pub fn then_fail(self, kind: &str) -> Self {
177 crate::client::with_stub(self.0, |answers| answers.push(crate::client::fail(kind)));
178 self
179 }
180}
181
182pub async fn assert_stored(key: &str) -> crate::Result<()> {
193 let stored = crate::storage::current().exists(key).await?;
194 assert!(
195 stored,
196 "expected a stored file at `{key}`, but there's none"
197 );
198 Ok(())
199}
200
201pub async fn assert_missing(key: &str) -> crate::Result<()> {
211 let stored = crate::storage::current().exists(key).await?;
212 assert!(
213 !stored,
214 "expected no stored file at `{key}`, but there's one"
215 );
216 Ok(())
217}
218
219pub fn stub_process(program: &str, status: i32, stdout: &str) {
227 crate::process::stub(program, status, stdout);
228}
229
230pub fn processes_run() -> Vec<Vec<String>> {
232 crate::process::ran()
233}
234
235pub fn requests() -> Vec<crate::client::Requested> {
237 crate::client::requested()
238}
239
240pub fn delivered_mail() -> Vec<crate::mail::Mail> {
245 crate::mail::delivered()
246}
247
248pub fn clear_delivered_mail() {
250 crate::mail::clear_delivered();
251}
252
253pub async fn enqueued_jobs() -> crate::Result<Vec<Enqueued>> {
257 let rows = crate::db::sql(
258 "SELECT name, queue, args, run_at FROM glacier_jobs \
259 WHERE locked_at IS NULL AND failed_at IS NULL ORDER BY id",
260 )
261 .fetch_all()
262 .await?;
263 rows.iter()
264 .map(|row| {
265 let args: String = row.get("args")?;
266 Ok(Enqueued {
267 name: row.get("name")?,
268 args: crate::jobs::own_args(serde_json::from_str(&args)?),
269 queue: row.get("queue")?,
270 run_at: row.get("run_at")?,
271 })
272 })
273 .collect()
274}
275
276pub fn travel_to(at: impl Moment) {
286 assert!(
287 crate::time::set_clock(Some(at.moment())),
288 "travel_to works inside a #[glacier::test]"
289 );
290}
291
292pub trait Moment {
294 fn moment(self) -> crate::db::Timestamp;
295}
296
297impl Moment for crate::db::Timestamp {
298 fn moment(self) -> crate::db::Timestamp {
299 self
300 }
301}
302
303impl Moment for &str {
304 fn moment(self) -> crate::db::Timestamp {
305 crate::time::parse(self, "UTC").unwrap_or_else(|| panic!("`{self}` isn't a time"))
306 }
307}
308
309pub fn travel(by: chrono::TimeDelta) {
312 travel_to(crate::time::now() + by);
313}
314
315pub fn freeze_time() {
317 travel_to(crate::time::now());
318}
319
320pub fn rendered_pdfs() -> Vec<crate::pdf::Rendered> {
324 crate::pdf::rendered()
325}
326
327pub fn travel_back() {
329 crate::time::set_clock(None);
330}
331
332pub async fn queries<F: Future>(fut: F) -> (F::Output, Vec<String>) {
340 crate::db::logging_queries(fut).await
341}
342
343pub async fn setup(migrations: Vec<Migration>) -> (Config, Repo) {
358 let config = Config::load_from("config", Env::Test).expect("loading config/test.toml");
359 let repo = Repo::from_config(&config)
360 .await
361 .expect("connecting to the test database (database.url in config/test.toml)");
362 Migrator::new(&repo, migrations)
363 .expect("invalid migrations")
364 .migrate()
365 .await
366 .expect("migrating the test database");
367 (config, repo)
368}
369
370impl TestClient {
371 pub fn new(mut app: App) -> Self {
373 crate::access::strict(true);
375 app.env.get_or_insert(Env::Test);
376 Self {
377 service: app.build(),
378 cookies: Mutex::default(),
379 csrf_token: Mutex::default(),
380 headers: Mutex::default(),
381 prefix: Mutex::default(),
382 cycles: Mutex::default(),
383 recycled: Mutex::default(),
384 }
385 }
386
387 pub fn service(&self) -> &crate::app::Service {
389 &self.service
390 }
391
392 pub async fn get(&self, path: &str) -> Response {
393 self.send(Method::GET, path, Bytes::new(), None).await
394 }
395
396 pub async fn delete(&self, path: &str) -> Response {
397 self.send(Method::DELETE, path, Bytes::new(), None).await
398 }
399
400 pub async fn post_form<T: Serialize + ?Sized>(&self, path: &str, form: &T) -> Response {
401 self.send_form(Method::POST, path, form).await
402 }
403
404 pub async fn patch_form<T: Serialize + ?Sized>(&self, path: &str, form: &T) -> Response {
405 self.send_form(Method::PATCH, path, form).await
406 }
407
408 pub async fn post_json<T: Serialize + ?Sized>(&self, path: &str, json: &T) -> Response {
409 self.send_json(Method::POST, path, json).await
410 }
411
412 pub async fn patch_json<T: Serialize + ?Sized>(&self, path: &str, json: &T) -> Response {
413 self.send_json(Method::PATCH, path, json).await
414 }
415
416 pub async fn put_json<T: Serialize + ?Sized>(&self, path: &str, json: &T) -> Response {
417 self.send_json(Method::PUT, path, json).await
418 }
419
420 async fn send_json<T: Serialize + ?Sized>(
421 &self,
422 method: Method,
423 path: &str,
424 json: &T,
425 ) -> Response {
426 let body = serde_json::to_vec(json).expect("failed to serialize test JSON");
427 self.send(method, path, body.into(), Some("application/json"))
428 .await
429 }
430
431 pub fn config(&self) -> crate::Config {
444 self.service
445 .state::<crate::Config>()
446 .cloned()
447 .expect("the app has no Config: App::config registers it")
448 }
449
450 pub async fn perform_jobs(&self) -> crate::Result<usize> {
451 let jobs = self
452 .service
453 .state::<crate::jobs::Jobs>()
454 .expect("perform_jobs needs App::jobs")
455 .clone();
456 jobs.perform_due().await
457 }
458
459 pub async fn run_task(&self, name: &str, args: Vec<String>) -> crate::Result<()> {
466 let task = self
467 .service
468 .task(name)
469 .unwrap_or_else(|| panic!("the app has no task `{name}` (src/tasks.glacier)"));
470 (task.run)(args).await
471 }
472
473 pub fn bearer(&self, token: impl AsRef<str>) {
476 self.header("authorization", format!("Bearer {}", token.as_ref()));
477 }
478
479 pub fn header(&self, name: &str, value: impl AsRef<str>) {
485 let name = header::HeaderName::try_from(name).expect("invalid header name");
486 let value = header::HeaderValue::try_from(value.as_ref()).expect("invalid header value");
487 let mut headers = self.headers.lock().unwrap();
488 headers.retain(|(existing, _)| *existing != name);
489 headers.push((name, value));
490 }
491
492 pub fn path_prefix(&self, prefix: impl Into<String>) {
497 *self.prefix.lock().unwrap() = Some(prefix.into());
498 }
499
500 pub async fn request(&self, mut req: http::Request<Bytes>) -> Response {
501 if let Some(prefix) = self.prefix.lock().unwrap().clone() {
502 let path = req.uri().path();
503 let has_it = path == prefix || path.starts_with(&format!("{prefix}/"));
504 if !has_it {
505 let uri = match req.uri().query() {
506 Some(query) => format!("{prefix}{path}?{query}"),
507 None => format!("{prefix}{path}"),
508 };
509 if let Ok(uri) = uri.parse() {
510 *req.uri_mut() = uri;
511 }
512 }
513 }
514 for (name, value) in self.headers.lock().unwrap().iter() {
515 if !req.headers().contains_key(name) {
516 req.headers_mut().insert(name.clone(), value.clone());
517 }
518 }
519 if !req.headers().contains_key(header::HOST) && req.uri().authority().is_none() {
522 req.headers_mut()
523 .insert(header::HOST, http::HeaderValue::from_static("localhost"));
524 }
525 let unsafe_method = !matches!(*req.method(), Method::GET | Method::HEAD);
526 let has_token = req.headers().contains_key(crate::csrf::HEADER)
528 || req.body().windows(12).any(|w| w == b"_csrf_token=")
529 || req.body().windows(19).any(|w| w == b"name=\"_csrf_token\"");
530 if unsafe_method
531 && !has_token
532 && let Some(token) = self.csrf_token.lock().unwrap().clone()
533 {
534 req.headers_mut().insert(
535 crate::csrf::HEADER,
536 token.try_into().expect("invalid CSRF token"),
537 );
538 }
539 if !req.headers().contains_key(header::COOKIE)
540 && let Some(cookie) = self.cookie_header()
541 {
542 req.headers_mut().insert(
543 header::COOKIE,
544 cookie.try_into().expect("invalid cookie header"),
545 );
546 }
547 let (method, path) = (req.method().clone(), req.uri().path().to_owned());
548 let res = self.service.call(req).await;
549 if res.status().is_server_error()
553 && let Some(report) = res.extensions().get::<crate::error::ErrorReport>()
554 {
555 eprintln!(
556 "{method} {path} answered {}: {}",
557 report.status, report.message
558 );
559 for cause in &report.causes {
560 eprintln!(" caused by: {cause}");
561 }
562 }
563 self.store_cookies(&res);
564 self.remember_csrf_token(&res);
565 res
566 }
567
568 fn remember_csrf_token(&self, res: &Response) {
571 let body = res.body();
572 let marker = format!(r#"name="{}" value=""#, crate::csrf::FORM_FIELD);
573 let Some(start) = body
574 .windows(marker.len())
575 .position(|w| w == marker.as_bytes())
576 .map(|i| i + marker.len())
577 else {
578 return;
579 };
580 let token: String = body[start..]
581 .iter()
582 .take_while(|b| b.is_ascii_hexdigit())
583 .map(|&b| b as char)
584 .collect();
585 if !token.is_empty() {
586 *self.csrf_token.lock().unwrap() = Some(token);
587 }
588 }
589
590 pub fn cookie(&self, name: &str) -> Option<String> {
592 self.cookies.lock().unwrap().get(name).cloned()
593 }
594
595 pub fn set_cookie(&self, name: &str, value: impl Into<String>) {
598 self.cookies
599 .lock()
600 .unwrap()
601 .insert(name.to_owned(), value.into());
602 }
603
604 pub fn clear_cookies(&self) {
605 self.cookies.lock().unwrap().clear();
606 }
607
608 fn cookie_header(&self) -> Option<String> {
609 let cookies = self.cookies.lock().unwrap();
610 (!cookies.is_empty()).then(|| {
611 cookies
612 .iter()
613 .map(|(name, value)| format!("{name}={value}"))
614 .collect::<Vec<_>>()
615 .join("; ")
616 })
617 }
618
619 fn store_cookies(&self, res: &Response) {
620 let mut cookies = self.cookies.lock().unwrap();
621 for value in res.headers().get_all(header::SET_COOKIE) {
622 let Some(cookie) = value.to_str().ok().and_then(|v| Cookie::parse(v).ok()) else {
623 continue;
624 };
625 let removed = cookie.max_age().is_some_and(|age| age.is_zero());
626 if removed {
627 cookies.remove(cookie.name());
628 } else {
629 cookies.insert(cookie.name().to_owned(), cookie.value().to_owned());
630 }
631 }
632 }
633
634 pub async fn put_form<T: Serialize + ?Sized>(&self, path: &str, form: &T) -> Response {
635 self.send_form(Method::PUT, path, form).await
636 }
637
638 pub async fn send_form<T: Serialize + ?Sized>(
640 &self,
641 method: Method,
642 path: &str,
643 form: &T,
644 ) -> Response {
645 let body = serde_urlencoded::to_string(form).expect("failed to serialize test form");
646 self.send(
647 method,
648 path,
649 body.into(),
650 Some("application/x-www-form-urlencoded"),
651 )
652 .await
653 }
654
655 async fn send(
656 &self,
657 method: Method,
658 path: &str,
659 body: Bytes,
660 content_type: Option<&str>,
661 ) -> Response {
662 let mut req = http::Request::builder().method(method).uri(path);
663 if let Some(content_type) = content_type {
664 req = req.header(header::CONTENT_TYPE, content_type);
665 }
666 self.request(req.body(body).expect("invalid test request"))
667 .await
668 }
669}