glacier-web 0.1.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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
//! The runtime behind `.glacier` tests: an ambient client, responses that
//! read well in assertions, forms, factories' `insert`, and asserts that
//! explain themselves.
//!
//! Each test runs inside [`run`], which gives it a fresh, migrated database
//! (also the ambient connection, so model calls work) and a [`TestClient`]
//! for the app. [`get`], [`post`] and friends use that client, so a test
//! never passes one around:
//!
//! ```text
//! test "lists posts" do
//!   insert(Post)
//!   res = get "/posts"
//!   assert res.status == :ok
//!   assert res.body =~ "Example title"
//! end
//! ```
//!
//! Plain Rust tests can use all of this too, through `#[glacier::test(app)]`
//! in a crate that declares its `.glacier` tests with `glacier::tests!`.

use std::fmt;
use std::future::Future;
use std::sync::Arc;

use http::{HeaderMap, Method, StatusCode};
use serde::Serialize;

use super::{TestClient, setup};
use crate::app::App;
use crate::config::Config;
use crate::context::Params;
use crate::db::migration::Migration;
use crate::db::{Changeset, Repo, Save};
use crate::model::Model;
use crate::response::Response;
use crate::router::ToPath;

/// How to build the app under test: its constructor and migrations.
#[derive(Clone, Copy)]
pub struct Harness {
    app: fn(Config, Repo) -> crate::Result<App>,
    migrations: fn() -> Vec<Migration>,
}

impl Harness {
    pub fn new(
        app: fn(Config, Repo) -> crate::Result<App>,
        migrations: fn() -> Vec<Migration>,
    ) -> Self {
        Self { app, migrations }
    }
}

tokio::task_local! {
    static CLIENT: Arc<TestClient>;
}

/// Runs a test against a fresh app and database. `#[glacier::test(app)]`
/// calls this.
///
/// An in-memory SQLite test database is new for every test. Any other (a
/// Postgres database loaded from a Rails app's `structure.sql`, say) is
/// shared, so each test runs in a transaction that is rolled back, as
/// Rails' transactional tests do.
///
/// # Panics
///
/// If the config, database, migrations or app fail to set up.
pub async fn run<F: Future<Output = ()>>(harness: Harness, test: F) {
    let (config, repo) = setup((harness.migrations)()).await;
    let url: String = config.get("database.url").unwrap_or_default();
    let fresh = url.starts_with("sqlite:") && url.contains(":memory:");
    let app = (harness.app)(config, repo.clone()).expect("building the app under test");
    let client = Arc::new(TestClient::new(app));
    if fresh {
        CLIENT.scope(client, crate::db::with(&repo, test)).await;
    } else {
        CLIENT
            .scope(client, crate::db::sandbox(&repo, test))
            .await
            .expect("rolling back the test's transaction");
    }
}

/// Sends `Authorization: Bearer <token>` with the test's later requests:
/// `glacier::testing::bearer(&token)` after signing in through an API.
pub fn bearer(token: impl AsRef<str>) {
    client().bearer(token);
}

/// Sends `name: value` with the test's later requests:
/// `glacier::testing::header("authorization", token)`.
pub fn header(name: &str, value: impl AsRef<str>) {
    client().header(name, value);
}

fn client() -> Arc<TestClient> {
    CLIENT.try_with(Arc::clone).expect(
        "get/post/patch/put/delete need a test client: use them in a .glacier test \
         or a #[glacier::test(app)] function",
    )
}

/// A number no earlier call returned, for unique factory values:
/// `email_address: format!("user{}@example.com", glacier::testing::sequence())`,
/// as FactoryBot's `sequence`.
pub fn sequence() -> u64 {
    static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
    NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}

/// Runs the background jobs that are due, as Rails'
/// `perform_enqueued_jobs`: `perform_jobs()!` in a `.glacier` test.
pub async fn perform_jobs() -> crate::Result<usize> {
    client().perform_jobs().await
}

/// `GET path`.
pub async fn get(path: impl ToPath) -> TestResponse {
    client().get(&path.to_path()).await.into()
}

/// `POST path` with a form, e.g. `post "/posts", title: "Hi"`.
pub async fn post(path: impl ToPath, form: impl Into<Form>) -> TestResponse {
    send(Method::POST, path, form.into()).await
}

/// `PATCH path` with a form.
pub async fn patch(path: impl ToPath, form: impl Into<Form>) -> TestResponse {
    send(Method::PATCH, path, form.into()).await
}

/// `PUT path` with a form.
pub async fn put(path: impl ToPath, form: impl Into<Form>) -> TestResponse {
    send(Method::PUT, path, form.into()).await
}

/// `POST path` with a JSON body, as an API client sends it: JSON text
/// (`post_json "/posts", r#"{"post": {"title": "Hi"}}"#`) or a form, sent
/// as the object it describes (`post_json "/posts", params_for(Post)`).
pub async fn post_json(path: impl ToPath, json: impl JsonBody) -> TestResponse {
    send_json(Method::POST, path, json.json_body()).await
}

/// `PATCH path` with a JSON body.
pub async fn patch_json(path: impl ToPath, json: impl JsonBody) -> TestResponse {
    send_json(Method::PATCH, path, json.json_body()).await
}

/// `PUT path` with a JSON body.
pub async fn put_json(path: impl ToPath, json: impl JsonBody) -> TestResponse {
    send_json(Method::PUT, path, json.json_body()).await
}

async fn send_json(method: Method, path: impl ToPath, json: String) -> TestResponse {
    let req = http::Request::builder()
        .method(method)
        .uri(path.to_path())
        .header(http::header::CONTENT_TYPE, "application/json")
        .body(bytes::Bytes::from(json))
        .expect("invalid test request");
    client().request(req).await.into()
}

/// A JSON request body: JSON text as is, or a [`Form`] as the object its
/// fields describe.
pub trait JsonBody {
    fn json_body(&self) -> String;
}

impl JsonBody for str {
    fn json_body(&self) -> String {
        self.to_owned()
    }
}

impl JsonBody for String {
    fn json_body(&self) -> String {
        self.clone()
    }
}

impl JsonBody for Form {
    /// `post[title]=Hi` → `{"post": {"title": "Hi"}}`, and `ids[]` fields
    /// → an array. Values are strings, as a form's are.
    fn json_body(&self) -> String {
        let mut root = serde_json::Map::new();
        for (name, value) in &self.0 {
            let mut keys: Vec<&str> = Vec::new();
            let (first, mut rest) = name
                .split_once('[')
                .map_or((name.as_str(), ""), |(a, b)| (a, b));
            keys.push(first);
            while let Some((key, after)) = rest.split_once(']') {
                keys.push(key);
                rest = after.strip_prefix('[').unwrap_or(after);
            }
            insert_json(&mut root, &keys, value);
        }
        serde_json::Value::Object(root).to_string()
    }
}

fn insert_json(
    object: &mut serde_json::Map<String, serde_json::Value>,
    keys: &[&str],
    value: &str,
) {
    use serde_json::Value;
    let (key, rest) = (keys[0].to_owned(), &keys[1..]);
    match rest {
        [] => {
            object.insert(key, Value::String(value.to_owned()));
        }
        [""] => {
            let entry = object
                .entry(key)
                .or_insert_with(|| Value::Array(Vec::new()));
            if let Value::Array(items) = entry {
                items.push(Value::String(value.to_owned()));
            }
        }
        _ => {
            let entry = object
                .entry(key)
                .or_insert_with(|| Value::Object(serde_json::Map::new()));
            if !entry.is_object() {
                *entry = Value::Object(serde_json::Map::new());
            }
            if let Value::Object(inner) = entry {
                insert_json(inner, rest, value);
            }
        }
    }
}

impl<T: JsonBody + ?Sized> JsonBody for &T {
    fn json_body(&self) -> String {
        (**self).json_body()
    }
}

/// `DELETE path`.
pub async fn delete(path: impl ToPath) -> TestResponse {
    client().delete(&path.to_path()).await.into()
}

async fn send(method: Method, path: impl ToPath, form: Form) -> TestResponse {
    if form.1.is_empty() {
        return client()
            .send_form(method, &path.to_path(), &form.0)
            .await
            .into();
    }
    // With files, as a browser sends them: multipart/form-data.
    let boundary = format!("----glacier{:016x}", rand_boundary());
    let mut body = Vec::new();
    for (name, value) in &form.0 {
        body.extend_from_slice(
            format!(
                "--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n"
            )
            .as_bytes(),
        );
    }
    for (name, upload) in &form.1 {
        body.extend_from_slice(
            format!(
                "--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"; filename=\"{}\"\r\nContent-Type: {}\r\n\r\n",
                upload.filename, upload.content_type
            )
            .as_bytes(),
        );
        body.extend_from_slice(&upload.bytes);
        body.extend_from_slice(b"\r\n");
    }
    body.extend_from_slice(format!("--{boundary}--\r\n").as_bytes());
    let req = http::Request::builder()
        .method(method)
        .uri(path.to_path())
        .header(
            http::header::CONTENT_TYPE,
            format!("multipart/form-data; boundary={boundary}"),
        )
        .body(bytes::Bytes::from(body))
        .expect("invalid test request");
    client().request(req).await.into()
}

fn rand_boundary() -> u64 {
    use std::hash::{BuildHasher, Hasher};
    let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
    hasher.write_u128(
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos(),
    );
    hasher.finish()
}

/// A file to put in a test form, as a client would upload it:
/// `post "/comments", [comment: [note_image: file("shelf.png", "image/png", bytes)]]`.
pub fn file(
    filename: &str,
    content_type: &str,
    bytes: impl Into<bytes::Bytes>,
) -> crate::upload::Upload {
    crate::upload::Upload {
        filename: filename.to_owned(),
        content_type: content_type.to_owned(),
        bytes: bytes.into(),
    }
}

/// A response, shaped for assertions: `res.status == :ok`,
/// `res.body =~ "Saved"`, `get res.location`.
#[derive(Debug)]
pub struct TestResponse {
    pub status: Status,
    pub body: String,
    /// The `Location` header; empty when there is none.
    pub location: String,
    pub headers: HeaderMap,
}

impl From<Response> for TestResponse {
    fn from(res: Response) -> Self {
        Self {
            status: Status(res.status()),
            body: res.body_text(),
            location: res.header("location").unwrap_or_default().to_owned(),
            headers: res.headers().clone(),
        }
    }
}

/// A status that compares with its name (`:see_other` in `.glacier`, or
/// `"see_other"`) or its number.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Status(pub StatusCode);

impl Status {
    /// The snake_case name: `see_other`, `unprocessable_entity`.
    pub fn name(&self) -> String {
        crate::response::status_name(self.0)
    }

    /// The status called `name`.
    ///
    /// # Panics
    ///
    /// If no status has that name, so a typo fails loudly rather than never
    /// matching.
    #[track_caller]
    pub fn named(name: &str) -> Self {
        crate::response::status_named(name)
            .map(Status)
            .unwrap_or_else(|| panic!("no HTTP status is called `:{name}`"))
    }
}

impl fmt::Debug for Status {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, ":{} ({})", self.name(), self.0.as_u16())
    }
}

impl PartialEq<&str> for Status {
    #[track_caller]
    fn eq(&self, name: &&str) -> bool {
        *self == Status::named(name)
    }
}

impl PartialEq<u16> for Status {
    fn eq(&self, code: &u16) -> bool {
        self.0.as_u16() == *code
    }
}

impl PartialEq<i32> for Status {
    fn eq(&self, code: &i32) -> bool {
        i32::from(self.0.as_u16()) == *code
    }
}

impl PartialEq<StatusCode> for Status {
    fn eq(&self, code: &StatusCode) -> bool {
        self.0 == *code
    }
}

/// Form fields, in order; setting a field again replaces it. A keyword
/// list `[title: "Hi", published: true]` in `.glacier` builds one.
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
pub struct Form(
    Vec<(String, String)>,
    /// Files, which make the request multipart.
    #[serde(skip)]
    Vec<(String, crate::upload::Upload)>,
);

impl Form {
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets `name` to `value`. A nested form's fields become
    /// `name[field]`, as Rails nests params:
    /// `[post: [title: "Hi"]]` sends `post[title]=Hi`.
    #[must_use]
    pub fn with(self, name: &str, value: impl FormValue) -> Self {
        value.add_to(self, name)
    }

    fn set(mut self, name: &str, value: String) -> Self {
        match self.0.iter_mut().find(|(k, _)| k == name) {
            Some(field) => field.1 = value,
            None => self.0.push((name.to_owned(), value)),
        }
        self
    }

    /// Removes `name`.
    #[must_use]
    pub fn without(mut self, name: &str) -> Self {
        self.0.retain(|(k, _)| k != name);
        self
    }

    pub fn get(&self, name: &str) -> Option<&str> {
        self.0
            .iter()
            .find(|(k, _)| k == name)
            .map(|(_, v)| v.as_str())
    }
}

/// A value in a test form: anything displayable, or a nested [`Form`].
pub trait FormValue {
    fn add_to(self, form: Form, name: &str) -> Form;
}

impl<T: fmt::Display> FormValue for T {
    fn add_to(self, form: Form, name: &str) -> Form {
        form.set(name, self.to_string())
    }
}

impl FormValue for Form {
    fn add_to(self, form: Form, name: &str) -> Form {
        // `title` → `post[title]`; `tags[0]` → `post[tags][0]`.
        let nest = |field: &str| {
            let (head, rest) = field.split_at(field.find('[').unwrap_or(field.len()));
            format!("{name}[{head}]{rest}")
        };
        let mut form = self
            .0
            .into_iter()
            .fold(form, |form, (field, value)| form.set(&nest(&field), value));
        for (field, upload) in self.1 {
            let field = nest(&field);
            form.1.retain(|(name, _)| *name != field);
            form.1.push((field, upload));
        }
        form
    }
}

/// A file field: the request goes as multipart/form-data.
impl FormValue for crate::upload::Upload {
    fn add_to(self, mut form: Form, name: &str) -> Form {
        form.1.retain(|(field, _)| field != name);
        form.1.push((name.to_owned(), self));
        form
    }
}

impl From<&Form> for Form {
    fn from(form: &Form) -> Self {
        form.clone()
    }
}

impl From<()> for Form {
    fn from((): ()) -> Self {
        Form::new()
    }
}

impl From<Form> for Params {
    fn from(form: Form) -> Self {
        form.0.into_iter().collect()
    }
}

impl<K: AsRef<str>, V: fmt::Display> FromIterator<(K, V)> for Form {
    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
        iter.into_iter()
            .fold(Form::new(), |form, (k, v)| form.with(k.as_ref(), v))
    }
}

/// `Post.create(params_for(Post, title: ""))` in a test.
impl<M: Model> From<Form> for Changeset<M> {
    fn from(form: Form) -> Self {
        Params::from(form).into()
    }
}

/// The validation errors of a save that failed, joined with `; `, for
/// `assert errors_on(saved) =~ "title can't be blank"`.
///
/// # Panics
///
/// If the record was saved.
#[track_caller]
pub fn errors_on<M: Model>(save: Save<M>) -> String {
    save.unwrap_invalid().full_messages().join("; ")
}

/// Inserts a record from `form` as `Model::build` + `save` would, so its
/// validations and callbacks run. `.unwrap()` the result for the record.
///
/// # Panics
///
/// On a database error.
pub async fn insert<M: Model + Default + Clone>(form: Form) -> Save<M> {
    // Built and saved like any record, so its callbacks run.
    let mut record = M::build(Params::from(form));
    let saved = record
        .save()
        .await
        .unwrap_or_else(|e| panic!("inserting a {}: {e}", std::any::type_name::<M>()));
    if saved {
        return Save::Saved(record);
    }
    let mut changeset = Changeset::<M>::new();
    for (column, message) in record.errors() {
        changeset = changeset.push_error(column, message.clone());
    }
    Save::Invalid(changeset)
}

/// `assert left == right`.
#[track_caller]
pub fn assert_equal<L, R>(left: &L, right: &R, source: &str)
where
    L: PartialEq<R> + fmt::Debug + ?Sized,
    R: fmt::Debug + ?Sized,
{
    if left != right {
        panic!("assertion failed: {source}\n  left:  {left:?}\n  right: {right:?}");
    }
}

/// `assert left != right`, or `refute left == right`.
#[track_caller]
pub fn assert_not_equal<L, R>(left: &L, right: &R, source: &str)
where
    L: PartialEq<R> + fmt::Debug + ?Sized,
    R: fmt::Debug + ?Sized,
{
    if left == right {
        panic!("assertion failed: {source}\n  both sides: {left:?}");
    }
}

/// `assert text =~ part`: `text` contains `part`.
#[track_caller]
pub fn assert_contains(
    text: &(impl AsRef<str> + ?Sized),
    part: &(impl AsRef<str> + ?Sized),
    source: &str,
) {
    let (text, part) = (text.as_ref(), part.as_ref());
    if !text.contains(part) {
        panic!(
            "assertion failed: {source}\n  expected to contain: {part:?}\n  but was: {}",
            excerpt(text)
        );
    }
}

/// `refute text =~ part`.
#[track_caller]
pub fn refute_contains(
    text: &(impl AsRef<str> + ?Sized),
    part: &(impl AsRef<str> + ?Sized),
    source: &str,
) {
    let (text, part) = (text.as_ref(), part.as_ref());
    if text.contains(part) {
        panic!(
            "refute failed: {source}\n  expected not to contain: {part:?}\n  but was: {}",
            excerpt(text)
        );
    }
}

/// `assert condition`.
#[track_caller]
pub fn assert_true(condition: bool, source: &str) {
    if !condition {
        panic!("assertion failed: {source}");
    }
}

/// `refute condition`.
#[track_caller]
pub fn refute_true(condition: bool, source: &str) {
    if condition {
        panic!("refute failed: {source}");
    }
}

/// The start of a long text (a page body, say), debug-quoted.
fn excerpt(text: &str) -> String {
    const MAX: usize = 600;
    match text.char_indices().nth(MAX) {
        Some((cut, _)) => format!("{:?}… ({} more bytes)", &text[..cut], text.len() - cut),
        None => format!("{text:?}"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn statuses_compare_by_name_and_number() {
        let s = Status(StatusCode::SEE_OTHER);
        assert_eq!(s.name(), "see_other");
        assert!(s == "see_other");
        assert!(s == 303);
        assert!(Status(StatusCode::UNPROCESSABLE_ENTITY) == "unprocessable_entity");
        assert!(Status(StatusCode::OK) == "ok");
        assert_eq!(format!("{s:?}"), ":see_other (303)");
    }

    #[test]
    #[should_panic(expected = "no HTTP status is called `:se_other`")]
    fn unknown_status_names_fail() {
        let _ = Status(StatusCode::OK) == "se_other";
    }

    #[test]
    fn forms_replace_fields() {
        let form = Form::new()
            .with("title", "a")
            .with("n", 1)
            .with("title", "b");
        assert_eq!(form.get("title"), Some("b"));
        assert_eq!(form.without("n"), Form::new().with("title", "b"));
    }

    #[test]
    fn nested_forms_send_rails_style_keys() {
        let tags = Form::new().with("0", "a");
        let form = Form::new().with("post", Form::new().with("title", "Hi").with("tags", tags));
        assert_eq!(form.get("post[title]"), Some("Hi"));
        assert_eq!(form.get("post[tags][0]"), Some("a"));
    }

    #[test]
    #[should_panic(expected = "assertion failed: res.body =~ \"x\"")]
    fn contains_explains_itself() {
        assert_contains("hello", "x", "res.body =~ \"x\"");
    }

    #[test]
    fn forms_become_json_objects() {
        let form = Form::new()
            .with("post", Form::new().with("title", "Hi").with("n", 3))
            .with("ids[]", 1)
            .with("ids[]", 2)
            .with("q", "x");
        assert_eq!(
            form.json_body(),
            r#"{"post":{"title":"Hi","n":"3"},"ids":["2"],"q":"x"}"#,
            "setting ids[] again replaces it, as in a form"
        );
        assert_eq!("{}".json_body(), "{}");
    }
}