Skip to main content

glacier/testing/
mod.rs

1//! In-process testing: drive an `App` without opening a socket.
2//!
3//! `TestClient` behaves like a browser: it keeps cookies between requests,
4//! and once it has loaded a page containing a CSRF field it sends that token
5//! with later form submissions. So, as in a browser, visit the form before
6//! submitting it. Sessions, flash and CSRF protection all work for real.
7//!
8//! [`setup`] prepares the usual app test: `config/test.toml` plus a freshly
9//! migrated database (in memory, with the default test config).
10//!
11//! ```
12//! use glacier::prelude::*;
13//! use glacier::testing::TestClient;
14//!
15//! # glacier::__private::tokio::runtime::Runtime::new().unwrap().block_on(async {
16//! let app = App::new().routes(|r| {
17//!     r.get("/", |_ctx| async { "hi" });
18//! });
19//! let res = TestClient::new(app).get("/").await;
20//! assert_eq!(res.body_text(), "hi");
21//! # });
22//! ```
23
24use 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 sent with every later request, such as a bearer token.
61    headers: Mutex<Vec<(header::HeaderName, header::HeaderValue)>>,
62    /// A prefix put in front of every later request's path (`/42`), for an
63    /// app whose URLs start with an id ([`IdPrefix`](crate::middleware::IdPrefix)).
64    prefix: Mutex<Option<String>>,
65    /// Each `cycle` call site's next turn, for this test.
66    pub(crate) cycles: Mutex<std::collections::HashMap<(&'static str, u32, u32), usize>>,
67    /// Records given to `recycle`, by type, for factories to use.
68    pub(crate) recycled:
69        Mutex<std::collections::HashMap<std::any::TypeId, Box<dyn std::any::Any + Send>>>,
70}
71
72/// A background job waiting to run, as [`enqueued_jobs`] lists it.
73#[derive(Debug, Clone, PartialEq)]
74pub struct Enqueued {
75    /// The job's `NAME`: `"send_report"`.
76    pub name: String,
77    /// Its fields, as JSON: `job.args["report_id"]` (without the access,
78    /// locale and request id Glacier keeps beside them).
79    pub args: serde_json::Value,
80    pub queue: String,
81    /// When it's due.
82    pub run_at: crate::db::Timestamp,
83}
84
85/// What `#[glacier::test]` runs each test in: a clock it can move, and a
86/// mailbox, a cache, stubbed HTTP, billing and webhooks of its own.
87#[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
96/// Answers requests to URLs matching `pattern` (`*` matches anything; a
97/// pattern without `?` ignores the query) with `status` and a JSON
98/// `body`, as WebMock's `stub_request`. `method` is `"GET"`, `"POST"`, …
99/// or `"*"`. The latest matching stub wins. In a test, a request that
100/// matches none fails rather than leaving the process. The stub it
101/// returns takes headers and later answers: `stub_request(…).header("retry-after",
102/// "2").then(200, json)`.
103///
104/// # Panics
105///
106/// Outside a `#[glacier::test]`, or for a method that isn't one.
107pub 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
111/// As [`stub_request`], answering with plain text: Slack's webhooks answer
112/// `ok`.
113///
114/// # Panics
115///
116/// Outside a `#[glacier::test]`, or for a method that isn't one.
117pub fn stub_request_text(method: &str, pattern: &str, status: u16, body: &str) -> Stubbed {
118    stub_answer(method, pattern, text_answer(status, body))
119}
120
121/// Requests to URLs matching `pattern` fail as the network can: `:timeout`
122/// or `:connect` (`"timeout"`, `"connect"`), as a client's retries see
123/// them. `.then(200, json)` answers a later attempt.
124///
125/// # Panics
126///
127/// Outside a `#[glacier::test]`, or for another kind of failure.
128pub 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/// A stub [`stub_request`] made, to add to: its answers come in turn, the
148/// last repeated.
149#[derive(Debug, Clone, Copy)]
150pub struct Stubbed(usize);
151
152impl Stubbed {
153    /// A header on its latest answer: `.header("retry-after", "2")`.
154    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    /// The next request's answer, a JSON body.
164    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    /// The next request's answer, plain text.
170    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    /// The next request fails: `:timeout` or `:connect`.
176    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
182/// Fails the test unless the app's store has a file at `key`, as
183/// Laravel's `Storage::assertExists`: `assert_stored("avatars/1.png")!`.
184///
185/// # Errors
186///
187/// When the store can't be read.
188///
189/// # Panics
190///
191/// When there's no such file.
192pub 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
201/// Fails the test if the app's store has a file at `key`.
202///
203/// # Errors
204///
205/// When the store can't be read.
206///
207/// # Panics
208///
209/// When there is one.
210pub 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
219/// In a test, the program `program` exits with `status` having printed
220/// `stdout`: `stub_process("pdftotext", 0, "Quarterly report")`. Tests
221/// run no real programs.
222///
223/// # Panics
224///
225/// Outside a `#[glacier::test]`.
226pub fn stub_process(program: &str, status: i32, stdout: &str) {
227    crate::process::stub(program, status, stdout);
228}
229
230/// The programs this test ran, each with its arguments.
231pub fn processes_run() -> Vec<Vec<String>> {
232    crate::process::ran()
233}
234
235/// The requests this test has made, oldest first, stubbed or not.
236pub fn requests() -> Vec<crate::client::Requested> {
237    crate::client::requested()
238}
239
240/// The mail this test has sent, oldest first, as Rails'
241/// `ActionMailer::Base.deliveries`: what `deliver_now` sent, and what
242/// `deliver_later` queued once `perform_jobs` has run it.
243/// `delivered_mail()` in a `.glacier` test.
244pub fn delivered_mail() -> Vec<crate::mail::Mail> {
245    crate::mail::delivered()
246}
247
248/// Forgets the mail this test has sent so far.
249pub fn clear_delivered_mail() {
250    crate::mail::clear_delivered();
251}
252
253/// The jobs waiting to run (not running, not failed), oldest first, as
254/// Rails' `enqueued_jobs`: to check what an action queued without running
255/// it. `enqueued_jobs()!` in a `.glacier` test.
256pub 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
276/// Moves the test's clock to `at` and stops it there, as Rails'
277/// `travel_to`: `glacier::time::now()` (and the timestamps records get, and
278/// when jobs are due) reads `at` until the clock moves again. `at` is a
279/// `Timestamp` or text: `travel_to("2026-10-19T09:00:00Z")`, or a date or
280/// time without an offset, taken as UTC.
281///
282/// # Panics
283///
284/// Outside a `#[glacier::test]`, or for text that isn't a time.
285pub 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
292/// A time to travel to: a `Timestamp`, or text naming one.
293pub 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
309/// Moves the test's clock forward by `by` (or back, when negative) and
310/// stops it there: `travel(15.days())`.
311pub fn travel(by: chrono::TimeDelta) {
312    travel_to(crate::time::now() + by);
313}
314
315/// Stops the test's clock at the present moment.
316pub fn freeze_time() {
317    travel_to(crate::time::now());
318}
319
320/// The PDFs this test rendered with `glacier::pdf::render`, oldest first:
321/// their HTML and options. Nothing is printed in a test; each render
322/// answers with a small placeholder PDF.
323pub fn rendered_pdfs() -> Vec<crate::pdf::Rendered> {
324    crate::pdf::rendered()
325}
326
327/// Lets the test's clock run with the real time again.
328pub fn travel_back() {
329    crate::time::set_clock(None);
330}
331
332/// Runs `fut` and returns its output with the SQL of every statement it
333/// ran (placeholders, not values), to check a page's queries:
334///
335/// ```ignore
336/// let (_, queries) = glacier::testing::queries(client.get("/books")).await;
337/// assert_eq!(queries.len(), 2, "the books, then their authors: {queries:#?}");
338/// ```
339pub async fn queries<F: Future>(fut: F) -> (F::Output, Vec<String>) {
340    crate::db::logging_queries(fut).await
341}
342
343/// Loads `config/test.toml`, connects to its database and runs
344/// `migrations`. With the default `sqlite::memory:` test database, every
345/// call gets a fresh, isolated database.
346///
347/// ```ignore
348/// async fn client() -> TestClient {
349///     let (config, repo) = glacier::testing::setup(blog::migrations::all()).await;
350///     TestClient::new(blog::app(config, repo).unwrap())
351/// }
352/// ```
353///
354/// # Panics
355///
356/// If the config, database or migrations fail; this is test setup.
357pub 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    /// Builds the app, in the test environment unless it was set explicitly.
372    pub fn new(mut app: App) -> Self {
373        // In tests, reading an owned model without its access fails.
374        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    /// The app under test, built.
388    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    /// Runs the background jobs that are due (`App::jobs`), as Rails'
432    /// `perform_enqueued_jobs`, returning how many ran.
433    ///
434    /// # Panics
435    ///
436    /// If the app has no jobs registered.
437    /// The app's `Config` (from `config/test.toml` in a test app), as
438    /// `App::config` registered it.
439    ///
440    /// # Panics
441    ///
442    /// If the app has no config.
443    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    /// Runs the app's task `name` with `args`, in the test's database,
460    /// as `glacier run name args…` would.
461    ///
462    /// # Panics
463    ///
464    /// When the app has no such task.
465    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    /// Sends `Authorization: Bearer <token>` with later requests, as an API
474    /// client that has signed in does.
475    pub fn bearer(&self, token: impl AsRef<str>) {
476        self.header("authorization", format!("Bearer {}", token.as_ref()));
477    }
478
479    /// Sends `name: value` with later requests, replacing any earlier value.
480    ///
481    /// # Panics
482    ///
483    /// If the name or value isn't valid in a header.
484    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    /// Sends an arbitrary request, adding stored cookies unless it already
493    /// has a `Cookie` header.
494    /// Puts `prefix` (`/42`) in front of every later request's path that
495    /// doesn't already start with it, as a browser inside org 42 would.
496    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        // As a browser would: `localhost`, which `hosts` allows outside
520        // production.
521        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        // In the body: a form's field, URL-encoded or multipart.
527        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        // A server error's cause, printed with the test's output (shown
550        // when it fails), since the response says only "Internal Server
551        // Error".
552        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    /// Keeps the token from a CSRF field in an HTML page, as a browser
569    /// would by holding the form.
570    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    /// A cookie the client currently holds (raw, possibly encrypted value).
591    pub fn cookie(&self, name: &str) -> Option<String> {
592        self.cookies.lock().unwrap().get(name).cloned()
593    }
594
595    /// Sets a plain cookie for the requests that follow, as a browser
596    /// that had it would send it (Rails' `cookies[name] = value` in a test).
597    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    /// Sends `form` with any method.
639    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}