glacier-web 0.4.1

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
//! In-process testing: drive an `App` without opening a socket.
//!
//! `TestClient` behaves like a browser: it keeps cookies between requests,
//! and once it has loaded a page containing a CSRF field it sends that token
//! with later form submissions. So, as in a browser, visit the form before
//! submitting it. Sessions, flash and CSRF protection all work for real.
//!
//! [`setup`] prepares the usual app test: `config/test.toml` plus a freshly
//! migrated database (in memory, with the default test config).
//!
//! ```
//! use glacier::prelude::*;
//! use glacier::testing::TestClient;
//!
//! # glacier::__private::tokio::runtime::Runtime::new().unwrap().block_on(async {
//! let app = App::new().routes(|r| {
//!     r.get("/", |_ctx| async { "hi" });
//! });
//! let res = TestClient::new(app).get("/").await;
//! assert_eq!(res.body_text(), "hi");
//! # });
//! ```

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, delete_json, errors_on, file, get, header,
    insert, insert_for, patch, patch_json, path_prefix, perform_jobs, post, post_json, put,
    put_json, refute_contains, refute_true, run, sequence, test_config,
};

pub struct TestClient {
    service: Service,
    cookies: Mutex<BTreeMap<String, String>>,
    csrf_token: Mutex<Option<String>>,
    /// Headers sent with every later request, such as a bearer token.
    headers: Mutex<Vec<(header::HeaderName, header::HeaderValue)>>,
    /// A prefix put in front of every later request's path (`/42`), for an
    /// app whose URLs start with an id ([`IdPrefix`](crate::middleware::IdPrefix)).
    prefix: Mutex<Option<String>>,
}

/// A background job waiting to run, as [`enqueued_jobs`] lists it.
#[derive(Debug, Clone, PartialEq)]
pub struct Enqueued {
    /// The job's `NAME`: `"send_report"`.
    pub name: String,
    /// Its fields, as JSON: `job.args["report_id"]`.
    pub args: serde_json::Value,
    pub queue: String,
    /// When it's due.
    pub run_at: crate::db::Timestamp,
}

/// What `#[glacier::test]` runs each test in: a clock it can move, and a
/// mailbox, a cache, stubbed HTTP, billing and webhooks of its own.
#[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::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
}

/// Answers requests to URLs matching `pattern` (`*` matches anything; a
/// pattern without `?` ignores the query) with `status` and a JSON
/// `body`, as WebMock's `stub_request`. `method` is `"GET"`, `"POST"`, …
/// or `"*"`. The latest matching stub wins. In a test, a request that
/// matches none fails rather than leaving the process.
///
/// # Panics
///
/// Outside a `#[glacier::test]`, or for a method that isn't one.
pub fn stub_request(method: &str, pattern: &str, status: u16, body: serde_json::Value) {
    let method = (method != "*").then(|| method.parse::<http::Method>().expect("an HTTP method"));
    let status = http::StatusCode::from_u16(status).expect("an HTTP status");
    crate::client::stub(
        method,
        pattern,
        status,
        body.to_string().into(),
        "application/json",
    );
}

/// As [`stub_request`], answering with plain text: Slack's webhooks answer
/// `ok`.
///
/// # Panics
///
/// Outside a `#[glacier::test]`, or for a method that isn't one.
pub fn stub_request_text(method: &str, pattern: &str, status: u16, body: &str) {
    let method = (method != "*").then(|| method.parse::<http::Method>().expect("an HTTP method"));
    let status = http::StatusCode::from_u16(status).expect("an HTTP status");
    crate::client::stub(
        method,
        pattern,
        status,
        body.to_owned().into(),
        "text/plain; charset=utf-8",
    );
}

/// The requests this test has made, oldest first, stubbed or not.
pub fn requests() -> Vec<crate::client::Requested> {
    crate::client::requested()
}

/// The mail this test has sent, oldest first, as Rails'
/// `ActionMailer::Base.deliveries`: what `deliver_now` sent, and what
/// `deliver_later` queued once `perform_jobs` has run it.
/// `delivered_mail()` in a `.glacier` test.
pub fn delivered_mail() -> Vec<crate::mail::Mail> {
    crate::mail::delivered()
}

/// Forgets the mail this test has sent so far.
pub fn clear_delivered_mail() {
    crate::mail::clear_delivered();
}

/// The jobs waiting to run (not running, not failed), oldest first, as
/// Rails' `enqueued_jobs`: to check what an action queued without running
/// it. `enqueued_jobs()!` in a `.glacier` test.
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: serde_json::from_str(&args)?,
                queue: row.get("queue")?,
                run_at: row.get("run_at")?,
            })
        })
        .collect()
}

/// Moves the test's clock to `at` and stops it there, as Rails'
/// `travel_to`: `glacier::time::now()` (and the timestamps records get, and
/// when jobs are due) reads `at` until the clock moves again. `at` is a
/// `Timestamp` or text: `travel_to("2026-10-19T09:00:00Z")`, or a date or
/// time without an offset, taken as UTC.
///
/// # Panics
///
/// Outside a `#[glacier::test]`, or for text that isn't a time.
pub fn travel_to(at: impl Moment) {
    assert!(
        crate::time::set_clock(Some(at.moment())),
        "travel_to works inside a #[glacier::test]"
    );
}

/// A time to travel to: a `Timestamp`, or text naming one.
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"))
    }
}

/// Moves the test's clock forward by `by` (or back, when negative) and
/// stops it there: `travel(15.days())`.
pub fn travel(by: chrono::TimeDelta) {
    travel_to(crate::time::now() + by);
}

/// Stops the test's clock at the present moment.
pub fn freeze_time() {
    travel_to(crate::time::now());
}

/// The PDFs this test rendered with `glacier::pdf::render`, oldest first:
/// their HTML and options. Nothing is printed in a test; each render
/// answers with a small placeholder PDF.
pub fn rendered_pdfs() -> Vec<crate::pdf::Rendered> {
    crate::pdf::rendered()
}

/// Lets the test's clock run with the real time again.
pub fn travel_back() {
    crate::time::set_clock(None);
}

/// Runs `fut` and returns its output with the SQL of every statement it
/// ran (placeholders, not values), to check a page's queries:
///
/// ```ignore
/// let (_, queries) = glacier::testing::queries(client.get("/books")).await;
/// assert_eq!(queries.len(), 2, "the books, then their authors: {queries:#?}");
/// ```
pub async fn queries<F: Future>(fut: F) -> (F::Output, Vec<String>) {
    crate::db::logging_queries(fut).await
}

/// Loads `config/test.toml`, connects to its database and runs
/// `migrations`. With the default `sqlite::memory:` test database, every
/// call gets a fresh, isolated database.
///
/// ```ignore
/// async fn client() -> TestClient {
///     let (config, repo) = glacier::testing::setup(blog::migrations::all()).await;
///     TestClient::new(blog::app(config, repo).unwrap())
/// }
/// ```
///
/// # Panics
///
/// If the config, database or migrations fail; this is test setup.
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 {
    /// Builds the app, in the test environment unless it was set explicitly.
    pub fn new(mut app: App) -> Self {
        // In tests, reading an owned model without its access fails.
        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(),
        }
    }

    /// The app under test, built.
    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
    }

    /// Runs the background jobs that are due (`App::jobs`), as Rails'
    /// `perform_enqueued_jobs`, returning how many ran.
    ///
    /// # Panics
    ///
    /// If the app has no jobs registered.
    /// The app's `Config` (from `config/test.toml` in a test app), as
    /// `App::config` registered it.
    ///
    /// # Panics
    ///
    /// If the app has no config.
    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
    }

    /// Sends `Authorization: Bearer <token>` with later requests, as an API
    /// client that has signed in does.
    pub fn bearer(&self, token: impl AsRef<str>) {
        self.header("authorization", format!("Bearer {}", token.as_ref()));
    }

    /// Sends `name: value` with later requests, replacing any earlier value.
    ///
    /// # Panics
    ///
    /// If the name or value isn't valid in a header.
    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));
    }

    /// Sends an arbitrary request, adding stored cookies unless it already
    /// has a `Cookie` header.
    /// Puts `prefix` (`/42`) in front of every later request's path that
    /// doesn't already start with it, as a browser inside org 42 would.
    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());
            }
        }
        // As a browser would: `localhost`, which `hosts` allows outside
        // production.
        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);
        // In the body: a form's field, URL-encoded or multipart.
        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 res = self.service.call(req).await;
        self.store_cookies(&res);
        self.remember_csrf_token(&res);
        res
    }

    /// Keeps the token from a CSRF field in an HTML page, as a browser
    /// would by holding the form.
    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);
        }
    }

    /// A cookie the client currently holds (raw, possibly encrypted value).
    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
    }

    /// Sends `form` with any method.
    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
    }
}