Skip to main content

glacier/testing/
ambient.rs

1//! The runtime behind `.glacier` tests: an ambient client, responses that
2//! read well in assertions, forms, factories' `insert`, and asserts that
3//! explain themselves.
4//!
5//! Each test runs inside [`run`], which gives it a fresh, migrated database
6//! (also the ambient connection, so model calls work) and a [`TestClient`]
7//! for the app. [`get`], [`post`] and friends use that client, so a test
8//! never passes one around:
9//!
10//! ```text
11//! test "lists posts" do
12//!   insert(Post)
13//!   res = get "/posts"
14//!   assert res.status == :ok
15//!   assert res.body =~ "Example title"
16//! end
17//! ```
18//!
19//! Plain Rust tests can use all of this too, through `#[glacier::test(app)]`
20//! in a crate that declares its `.glacier` tests with `glacier::tests!`.
21
22use std::fmt;
23use std::future::Future;
24use std::sync::Arc;
25
26use http::{HeaderMap, Method, StatusCode};
27use serde::Serialize;
28
29use super::{TestClient, setup};
30use crate::app::App;
31use crate::config::Config;
32use crate::context::Params;
33use crate::db::migration::Migration;
34use crate::db::{Changeset, Repo, Save};
35use crate::model::Model;
36use crate::response::Response;
37use crate::router::ToPath;
38
39/// How to build the app under test: its constructor and migrations.
40#[derive(Clone, Copy)]
41pub struct Harness {
42    app: fn(Config, Repo) -> crate::Result<App>,
43    migrations: fn() -> Vec<Migration>,
44}
45
46impl Harness {
47    pub fn new(
48        app: fn(Config, Repo) -> crate::Result<App>,
49        migrations: fn() -> Vec<Migration>,
50    ) -> Self {
51        Self { app, migrations }
52    }
53}
54
55tokio::task_local! {
56    static CLIENT: Arc<TestClient>;
57}
58
59/// Runs a test against a fresh app and database. `#[glacier::test(app)]`
60/// calls this.
61///
62/// An in-memory SQLite test database is new for every test. Any other (a
63/// Postgres database loaded from a Rails app's `structure.sql`, say) is
64/// shared, so each test runs in a transaction that is rolled back, as
65/// Rails' transactional tests do.
66///
67/// # Panics
68///
69/// If the config, database, migrations or app fail to set up.
70pub async fn run<F: Future<Output = ()>>(harness: Harness, test: F) {
71    let (config, repo) = setup((harness.migrations)()).await;
72    let url: String = config.get("database.url").unwrap_or_default();
73    let fresh = url.starts_with("sqlite:") && url.contains(":memory:");
74    let app = (harness.app)(config, repo.clone()).expect("building the app under test");
75    let client = Arc::new(TestClient::new(app));
76    let service = client.service();
77    service
78        .migrate_named()
79        .await
80        .expect("migrating the named test databases");
81    let databases = service
82        .named_databases()
83        .await
84        .expect("connecting to the named test databases");
85    if fresh {
86        let named = databases
87            .iter()
88            .map(|(name, repo)| (name.clone(), crate::db::Connection::from(repo)))
89            .collect();
90        let test = crate::db::scope_named(named, test);
91        CLIENT.scope(client, crate::db::with(&repo, test)).await;
92    } else {
93        // Each named database in a transaction of its own, rolled back
94        // with the app's.
95        let mut transactions = Vec::new();
96        for (name, repo) in &databases {
97            let tx = repo
98                .begin()
99                .await
100                .expect("starting a named test transaction");
101            transactions.push((name.clone(), tx));
102        }
103        let named = transactions
104            .iter()
105            .map(|(name, tx)| (name.clone(), crate::db::Connection::from(tx)))
106            .collect();
107        let test = crate::db::scope_named(named, test);
108        CLIENT
109            .scope(client, crate::db::sandbox(&repo, test))
110            .await
111            .expect("rolling back the test's transaction");
112        for (_, tx) in transactions {
113            tx.rollback()
114                .await
115                .expect("rolling back a named test transaction");
116        }
117    }
118}
119
120/// Sends `Authorization: Bearer <token>` with the test's later requests:
121/// `glacier::testing::bearer(&token)` after signing in through an API.
122pub fn bearer(token: impl AsRef<str>) {
123    client().bearer(token);
124}
125
126/// Puts `prefix` in front of the test's later request paths (unless they
127/// have it): `glacier::testing::path_prefix(format!("/{}", org.id))` for an
128/// app whose URLs start with the org's id.
129pub fn path_prefix(prefix: impl Into<String>) {
130    client().path_prefix(prefix);
131}
132
133/// Sends `name: value` with the test's later requests:
134/// `glacier::testing::header("authorization", token)`.
135pub fn header(name: &str, value: impl AsRef<str>) {
136    client().header(name, value);
137}
138
139/// Sets a plain cookie for the test's later requests, alongside the ones
140/// the app set: `glacier::testing::set_cookie("reading_progress_1", "4/3")`.
141pub fn set_cookie(name: &str, value: impl Into<String>) {
142    client().set_cookie(name, value);
143}
144
145/// Sends HTTP Basic credentials with the test's later requests, for routes
146/// behind `BasicAuth`: `glacier::testing::basic_auth("ops", "secret")`.
147pub fn basic_auth(name: &str, password: &str) {
148    use base64::Engine;
149    let encoded = base64::engine::general_purpose::STANDARD.encode(format!("{name}:{password}"));
150    client().header("authorization", format!("Basic {encoded}"));
151}
152
153fn client() -> Arc<TestClient> {
154    CLIENT.try_with(Arc::clone).expect(
155        "get/post/patch/put/delete need a test client: use them in a .glacier test \
156         or a #[glacier::test(app)] function",
157    )
158}
159
160/// The app's `Config`, from `config/test.toml`: build what the app builds
161/// from it, as `Stripe.from_config(&test_config())?`.
162pub fn test_config() -> crate::Config {
163    client().config()
164}
165
166/// A number no earlier call returned, for unique factory values:
167/// `email_address: format!("user{}@example.com", glacier::testing::sequence())`,
168/// as FactoryBot's `sequence`.
169pub fn sequence() -> u64 {
170    static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
171    NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
172}
173
174/// One of `values` in turn, for factory fields that vary:
175/// `status: cycle([:draft, :published])`, as FactoryBot's cycling
176/// sequences. Each place it's written keeps its own turn, from the start
177/// in each test.
178///
179/// # Panics
180///
181/// When `values` is empty.
182#[track_caller]
183pub fn cycle<T: Clone, const N: usize>(values: [T; N]) -> T {
184    assert!(N > 0, "cycle needs at least one value");
185    let at = std::panic::Location::caller();
186    let site = (at.file(), at.line(), at.column());
187    let turn = match CLIENT.try_with(Arc::clone) {
188        Ok(client) => {
189            let mut cycles = client.cycles.lock().unwrap_or_else(|e| e.into_inner());
190            let turn = cycles.entry(site).or_insert(0);
191            *turn += 1;
192            *turn - 1
193        }
194        Err(_) => usize::try_from(sequence()).unwrap_or(0),
195    };
196    values[turn % N].clone()
197}
198
199/// Has factories use `record` for the rest of the test wherever they'd
200/// insert a record of its model, as Laravel's `recycle`:
201/// `recycle(author)`, then each `insert(Book)` belongs to that author
202/// instead of a new one. A test's own `insert(Author)` still inserts.
203pub fn recycle<M: Clone + Send + 'static>(record: &M) {
204    let client = client();
205    client
206        .recycled
207        .lock()
208        .unwrap_or_else(|e| e.into_inner())
209        .insert(std::any::TypeId::of::<M>(), Box::new(record.clone()));
210}
211
212/// The record `recycle` gave for `M`, else `insert`'s: a factory's
213/// `insert(Author)`.
214#[doc(hidden)]
215pub async fn recycled_or<M: Clone + Send + 'static>(insert: impl Future<Output = M>) -> M {
216    let recycled = CLIENT.try_with(|client| {
217        client
218            .recycled
219            .lock()
220            .unwrap_or_else(|e| e.into_inner())
221            .get(&std::any::TypeId::of::<M>())
222            .and_then(|record| record.downcast_ref::<M>().cloned())
223    });
224    match recycled {
225        Ok(Some(record)) => record,
226        _ => insert.await,
227    }
228}
229
230/// Runs the background jobs that are due, as Rails'
231/// `perform_enqueued_jobs`: `perform_jobs()!` in a `.glacier` test.
232pub async fn perform_jobs() -> crate::Result<usize> {
233    client().perform_jobs().await
234}
235
236/// Runs the app's task `name`, as `glacier run name args…` would:
237/// `run_task("reports:send", [user.id])!`.
238pub async fn run_task<T: std::fmt::Display>(
239    name: &str,
240    args: impl IntoIterator<Item = T>,
241) -> crate::Result<()> {
242    let args = args.into_iter().map(|a| a.to_string()).collect();
243    client().run_task(name, args).await
244}
245
246/// `GET path`.
247pub async fn get(path: impl ToPath) -> TestResponse {
248    client().get(&path.to_path()).await.into()
249}
250
251/// `POST path` with a form, e.g. `post "/posts", title: "Hi"`.
252pub async fn post(path: impl ToPath, form: impl Into<Form>) -> TestResponse {
253    send(Method::POST, path, form.into()).await
254}
255
256/// `PATCH path` with a form.
257pub async fn patch(path: impl ToPath, form: impl Into<Form>) -> TestResponse {
258    send(Method::PATCH, path, form.into()).await
259}
260
261/// `PUT path` with a form.
262pub async fn put(path: impl ToPath, form: impl Into<Form>) -> TestResponse {
263    send(Method::PUT, path, form.into()).await
264}
265
266/// `POST path` with a JSON body, as an API client sends it: JSON text
267/// (`post_json "/posts", r#"{"post": {"title": "Hi"}}"#`) or a form, sent
268/// as the object it describes (`post_json "/posts", params_for(Post)`).
269pub async fn post_json(path: impl ToPath, json: impl JsonBody) -> TestResponse {
270    send_json(Method::POST, path, json.json_body()).await
271}
272
273/// `PATCH path` with a JSON body.
274pub async fn patch_json(path: impl ToPath, json: impl JsonBody) -> TestResponse {
275    send_json(Method::PATCH, path, json.json_body()).await
276}
277
278/// `PUT path` with a JSON body.
279pub async fn put_json(path: impl ToPath, json: impl JsonBody) -> TestResponse {
280    send_json(Method::PUT, path, json.json_body()).await
281}
282
283/// `DELETE path` with a JSON body, as `{"ids": [1, 3]}` for a bulk delete.
284pub async fn delete_json(path: impl ToPath, json: impl JsonBody) -> TestResponse {
285    send_json(Method::DELETE, path, json.json_body()).await
286}
287
288async fn send_json(method: Method, path: impl ToPath, json: String) -> TestResponse {
289    let req = http::Request::builder()
290        .method(method)
291        .uri(path.to_path())
292        .header(http::header::CONTENT_TYPE, "application/json")
293        .body(bytes::Bytes::from(json))
294        .expect("invalid test request");
295    client().request(req).await.into()
296}
297
298/// A JSON request body: JSON text as is, or a [`Form`] as the object its
299/// fields describe.
300pub trait JsonBody {
301    fn json_body(&self) -> String;
302}
303
304impl JsonBody for str {
305    fn json_body(&self) -> String {
306        self.to_owned()
307    }
308}
309
310impl JsonBody for String {
311    fn json_body(&self) -> String {
312        self.clone()
313    }
314}
315
316impl JsonBody for Form {
317    /// `post[title]=Hi` → `{"post": {"title": "Hi"}}`, and `ids[]` fields
318    /// → an array. Values are strings, as a form's are.
319    fn json_body(&self) -> String {
320        let mut root = serde_json::Map::new();
321        for (name, value) in &self.0 {
322            let mut keys: Vec<&str> = Vec::new();
323            let (first, mut rest) = name
324                .split_once('[')
325                .map_or((name.as_str(), ""), |(a, b)| (a, b));
326            keys.push(first);
327            while let Some((key, after)) = rest.split_once(']') {
328                keys.push(key);
329                rest = after.strip_prefix('[').unwrap_or(after);
330            }
331            insert_json(&mut root, &keys, value);
332        }
333        serde_json::Value::Object(root).to_string()
334    }
335}
336
337fn insert_json(
338    object: &mut serde_json::Map<String, serde_json::Value>,
339    keys: &[&str],
340    value: &str,
341) {
342    use serde_json::Value;
343    let (key, rest) = (keys[0].to_owned(), &keys[1..]);
344    match rest {
345        [] => {
346            object.insert(key, Value::String(value.to_owned()));
347        }
348        [""] => {
349            let entry = object
350                .entry(key)
351                .or_insert_with(|| Value::Array(Vec::new()));
352            if let Value::Array(items) = entry {
353                items.push(Value::String(value.to_owned()));
354            }
355        }
356        _ => {
357            let entry = object
358                .entry(key)
359                .or_insert_with(|| Value::Object(serde_json::Map::new()));
360            if !entry.is_object() {
361                *entry = Value::Object(serde_json::Map::new());
362            }
363            if let Value::Object(inner) = entry {
364                insert_json(inner, rest, value);
365            }
366        }
367    }
368}
369
370impl<T: JsonBody + ?Sized> JsonBody for &T {
371    fn json_body(&self) -> String {
372        (**self).json_body()
373    }
374}
375
376/// `DELETE path`.
377pub async fn delete(path: impl ToPath) -> TestResponse {
378    client().delete(&path.to_path()).await.into()
379}
380
381async fn send(method: Method, path: impl ToPath, form: Form) -> TestResponse {
382    if form.1.is_empty() {
383        return client()
384            .send_form(method, &path.to_path(), &form.0)
385            .await
386            .into();
387    }
388    // With files, as a browser sends them: multipart/form-data.
389    let boundary = format!("----glacier{:016x}", rand_boundary());
390    let mut body = Vec::new();
391    for (name, value) in &form.0 {
392        body.extend_from_slice(
393            format!(
394                "--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n"
395            )
396            .as_bytes(),
397        );
398    }
399    for (name, upload) in &form.1 {
400        body.extend_from_slice(
401            format!(
402                "--{boundary}\r\nContent-Disposition: form-data; name=\"{name}\"; filename=\"{}\"\r\nContent-Type: {}\r\n\r\n",
403                upload.filename, upload.content_type
404            )
405            .as_bytes(),
406        );
407        body.extend_from_slice(&upload.bytes);
408        body.extend_from_slice(b"\r\n");
409    }
410    body.extend_from_slice(format!("--{boundary}--\r\n").as_bytes());
411    let req = http::Request::builder()
412        .method(method)
413        .uri(path.to_path())
414        .header(
415            http::header::CONTENT_TYPE,
416            format!("multipart/form-data; boundary={boundary}"),
417        )
418        .body(bytes::Bytes::from(body))
419        .expect("invalid test request");
420    client().request(req).await.into()
421}
422
423fn rand_boundary() -> u64 {
424    use std::hash::{BuildHasher, Hasher};
425    let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
426    hasher.write_u128(
427        std::time::SystemTime::now()
428            .duration_since(std::time::UNIX_EPOCH)
429            .unwrap_or_default()
430            .as_nanos(),
431    );
432    hasher.finish()
433}
434
435/// A file to put in a test form, as a client would upload it:
436/// `post "/comments", [comment: [note_image: file("shelf.png", "image/png", bytes)]]`.
437pub fn file(
438    filename: &str,
439    content_type: &str,
440    bytes: impl Into<bytes::Bytes>,
441) -> crate::upload::Upload {
442    crate::upload::Upload {
443        filename: filename.to_owned(),
444        content_type: content_type.to_owned(),
445        bytes: bytes.into(),
446    }
447}
448
449/// A response, shaped for assertions: `res.status == :ok`,
450/// `res.body =~ "Saved"`, `get res.location`.
451#[derive(Debug)]
452pub struct TestResponse {
453    pub status: Status,
454    pub body: String,
455    /// The `Location` header; empty when there is none.
456    pub location: String,
457    pub headers: HeaderMap,
458}
459
460impl TestResponse {
461    /// A header as text: `res.header("link")?`. `None` when it's missing
462    /// or isn't text.
463    pub fn header(&self, name: &str) -> Option<&str> {
464        self.headers.get(name).and_then(|value| value.to_str().ok())
465    }
466
467    /// The body as JSON: `res.json()["books"][0]["title"]`.
468    ///
469    /// # Panics
470    ///
471    /// When the body isn't JSON, showing it.
472    #[track_caller]
473    pub fn json(&self) -> serde_json::Value {
474        serde_json::from_str(&self.body)
475            .unwrap_or_else(|e| panic!("the response isn't JSON ({e}):\n{}", self.body))
476    }
477}
478
479impl From<Response> for TestResponse {
480    fn from(res: Response) -> Self {
481        Self {
482            status: Status(res.status()),
483            body: res.body_text(),
484            location: res.header("location").unwrap_or_default().to_owned(),
485            headers: res.headers().clone(),
486        }
487    }
488}
489
490/// A status that compares with its name (`:see_other` in `.glacier`, or
491/// `"see_other"`) or its number.
492#[derive(Clone, Copy, PartialEq, Eq)]
493pub struct Status(pub StatusCode);
494
495impl Status {
496    /// The snake_case name: `see_other`, `unprocessable_entity`.
497    pub fn name(&self) -> String {
498        crate::response::status_name(self.0)
499    }
500
501    /// The status called `name`.
502    ///
503    /// # Panics
504    ///
505    /// If no status has that name, so a typo fails loudly rather than never
506    /// matching.
507    #[track_caller]
508    pub fn named(name: &str) -> Self {
509        crate::response::status_named(name)
510            .map(Status)
511            .unwrap_or_else(|| panic!("no HTTP status is called `:{name}`"))
512    }
513}
514
515impl fmt::Debug for Status {
516    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
517        write!(f, ":{} ({})", self.name(), self.0.as_u16())
518    }
519}
520
521impl PartialEq<&str> for Status {
522    #[track_caller]
523    fn eq(&self, name: &&str) -> bool {
524        *self == Status::named(name)
525    }
526}
527
528impl PartialEq<u16> for Status {
529    fn eq(&self, code: &u16) -> bool {
530        self.0.as_u16() == *code
531    }
532}
533
534impl PartialEq<i32> for Status {
535    fn eq(&self, code: &i32) -> bool {
536        i32::from(self.0.as_u16()) == *code
537    }
538}
539
540impl PartialEq<StatusCode> for Status {
541    fn eq(&self, code: &StatusCode) -> bool {
542        self.0 == *code
543    }
544}
545
546/// Form fields, in order; setting a field again replaces it. A keyword
547/// list `[title: "Hi", published: true]` in `.glacier` builds one.
548#[derive(Debug, Clone, Default, PartialEq, Serialize)]
549pub struct Form(
550    Vec<(String, String)>,
551    /// Files, which make the request multipart.
552    #[serde(skip)]
553    Vec<(String, crate::upload::Upload)>,
554);
555
556impl Form {
557    pub fn new() -> Self {
558        Self::default()
559    }
560
561    /// Sets `name` to `value`. A nested form's fields become
562    /// `name[field]`, as Rails nests params:
563    /// `[post: [title: "Hi"]]` sends `post[title]=Hi`.
564    #[must_use]
565    pub fn with(self, name: &str, value: impl FormValue) -> Self {
566        value.add_to(self, name)
567    }
568
569    /// Sends each value as `name[]`, as Rails sends a list:
570    /// `[ids: [1, 2]]` in `.glacier` is `ids[]=1&ids[]=2`.
571    #[must_use]
572    pub fn with_all<T: fmt::Display>(
573        mut self,
574        name: &str,
575        values: impl IntoIterator<Item = T>,
576    ) -> Self {
577        let field = format!("{name}[]");
578        self.0.retain(|(k, _)| *k != field);
579        self.0.extend(
580            values
581                .into_iter()
582                .map(|value| (field.clone(), value.to_string())),
583        );
584        self
585    }
586
587    fn set(mut self, name: &str, value: String) -> Self {
588        match self.0.iter_mut().find(|(k, _)| k == name) {
589            Some(field) => field.1 = value,
590            None => self.0.push((name.to_owned(), value)),
591        }
592        self
593    }
594
595    /// Removes `name`.
596    #[must_use]
597    pub fn without(mut self, name: &str) -> Self {
598        self.0.retain(|(k, _)| k != name);
599        self
600    }
601
602    pub fn get(&self, name: &str) -> Option<&str> {
603        self.0
604            .iter()
605            .find(|(k, _)| k == name)
606            .map(|(_, v)| v.as_str())
607    }
608}
609
610/// A value in a test form: anything displayable, or a nested [`Form`].
611pub trait FormValue {
612    fn add_to(self, form: Form, name: &str) -> Form;
613}
614
615impl<T: fmt::Display> FormValue for T {
616    fn add_to(self, form: Form, name: &str) -> Form {
617        form.set(name, self.to_string())
618    }
619}
620
621impl FormValue for Form {
622    fn add_to(self, form: Form, name: &str) -> Form {
623        // `title` → `post[title]`; `tags[0]` → `post[tags][0]`.
624        let nest = |field: &str| {
625            let (head, rest) = field.split_at(field.find('[').unwrap_or(field.len()));
626            format!("{name}[{head}]{rest}")
627        };
628        let mut form = self
629            .0
630            .into_iter()
631            .fold(form, |form, (field, value)| form.set(&nest(&field), value));
632        for (field, upload) in self.1 {
633            let field = nest(&field);
634            form.1.retain(|(name, _)| *name != field);
635            form.1.push((field, upload));
636        }
637        form
638    }
639}
640
641/// A file field: the request goes as multipart/form-data.
642impl FormValue for crate::upload::Upload {
643    fn add_to(self, mut form: Form, name: &str) -> Form {
644        form.1.retain(|(field, _)| field != name);
645        form.1.push((name.to_owned(), self));
646        form
647    }
648}
649
650impl From<&Form> for Form {
651    fn from(form: &Form) -> Self {
652        form.clone()
653    }
654}
655
656impl From<()> for Form {
657    fn from((): ()) -> Self {
658        Form::new()
659    }
660}
661
662impl From<Form> for Params {
663    fn from(form: Form) -> Self {
664        form.0.into_iter().collect()
665    }
666}
667
668impl<K: AsRef<str>, V: fmt::Display> FromIterator<(K, V)> for Form {
669    fn from_iter<I: IntoIterator<Item = (K, V)>>(iter: I) -> Self {
670        iter.into_iter()
671            .fold(Form::new(), |form, (k, v)| form.with(k.as_ref(), v))
672    }
673}
674
675/// `Post.create(params_for(Post, title: ""))` in a test.
676impl<M: Model> From<Form> for Changeset<M> {
677    fn from(form: Form) -> Self {
678        Params::from(form).into()
679    }
680}
681
682/// The validation errors of a save that failed, joined with `; `, for
683/// `assert errors_on(saved) =~ "title can't be blank"`.
684///
685/// # Panics
686///
687/// If the record was saved.
688#[track_caller]
689pub fn errors_on<M: Model>(save: Save<M>) -> String {
690    save.unwrap_invalid().messages().join("; ")
691}
692
693/// Inserts a record from `form` as `Model::build` + `save` would, so its
694/// validations and callbacks run. `.unwrap()` the result for the record.
695///
696/// # Panics
697///
698/// On a database error.
699pub async fn insert<M: Model + Default + Clone>(form: Form) -> Save<M> {
700    // Built and saved like any record, so its callbacks run. A test may
701    // set protected columns (`user_id`, `email_verified_at`), which params
702    // never do.
703    let params = Params::from(form);
704    let mut record = M::build(params.clone());
705    record.assign_protected(&params);
706    save_inserted(record).await
707}
708
709/// Inserts a record for `access`, as `Note.for(access).build(…)` would
710/// build it: its owner columns (`org_id`) come from the access, whatever
711/// the factory or the test gave them, and it's saved under the access, so
712/// owned parents are checked to be the tenant's. `insert_for(ada, Note,
713/// title: "…")` in `.glacier`.
714///
715/// # Panics
716///
717/// On a database error.
718pub async fn insert_for<M, A>(access: &A, form: Form) -> Save<M>
719where
720    M: Model + Default + Clone,
721    A: crate::access::Access + Clone,
722{
723    let params = Params::from(form);
724    let mut built = M::build(params.clone());
725    built.assign_protected(&params);
726    let record = M::r#for(access).build_with(|record| *record = built);
727    crate::access::with_access(access.clone(), save_inserted(record)).await
728}
729
730async fn save_inserted<M: Model + Clone>(mut record: M) -> Save<M> {
731    let saved = record
732        .save()
733        .await
734        .unwrap_or_else(|e| panic!("inserting a {}: {e}", std::any::type_name::<M>()));
735    if saved {
736        return Save::Saved(record);
737    }
738    let mut changeset = Changeset::<M>::new();
739    for (column, message) in record.errors() {
740        changeset = changeset.push_error(column, message.clone());
741    }
742    Save::Invalid(changeset)
743}
744
745/// `assert left == right`.
746#[track_caller]
747pub fn assert_equal<L, R>(left: &L, right: &R, source: &str)
748where
749    L: PartialEq<R> + fmt::Debug + ?Sized,
750    R: fmt::Debug + ?Sized,
751{
752    if left != right {
753        panic!("assertion failed: {source}\n  left:  {left:?}\n  right: {right:?}");
754    }
755}
756
757/// `assert left != right`, or `refute left == right`.
758#[track_caller]
759pub fn assert_not_equal<L, R>(left: &L, right: &R, source: &str)
760where
761    L: PartialEq<R> + fmt::Debug + ?Sized,
762    R: fmt::Debug + ?Sized,
763{
764    if left == right {
765        panic!("assertion failed: {source}\n  both sides: {left:?}");
766    }
767}
768
769/// `assert text =~ part`: `text` contains `part`.
770#[track_caller]
771pub fn assert_contains(
772    text: &(impl AsRef<str> + ?Sized),
773    part: &(impl AsRef<str> + ?Sized),
774    source: &str,
775) {
776    let (text, part) = (text.as_ref(), part.as_ref());
777    if !text.contains(part) {
778        panic!(
779            "assertion failed: {source}\n  expected to contain: {part:?}\n  but was: {}",
780            excerpt(text)
781        );
782    }
783}
784
785/// `refute text =~ part`.
786#[track_caller]
787pub fn refute_contains(
788    text: &(impl AsRef<str> + ?Sized),
789    part: &(impl AsRef<str> + ?Sized),
790    source: &str,
791) {
792    let (text, part) = (text.as_ref(), part.as_ref());
793    if text.contains(part) {
794        panic!(
795            "refute failed: {source}\n  expected not to contain: {part:?}\n  but was: {}",
796            excerpt(text)
797        );
798    }
799}
800
801/// `assert condition`.
802#[track_caller]
803pub fn assert_true(condition: bool, source: &str) {
804    if !condition {
805        panic!("assertion failed: {source}");
806    }
807}
808
809/// `refute condition`.
810#[track_caller]
811pub fn refute_true(condition: bool, source: &str) {
812    if condition {
813        panic!("refute failed: {source}");
814    }
815}
816
817/// The start of a long text (a page body, say), debug-quoted.
818fn excerpt(text: &str) -> String {
819    const MAX: usize = 600;
820    match text.char_indices().nth(MAX) {
821        Some((cut, _)) => format!("{:?}… ({} more bytes)", &text[..cut], text.len() - cut),
822        None => format!("{text:?}"),
823    }
824}
825
826#[cfg(test)]
827mod tests {
828    use super::*;
829
830    #[test]
831    fn statuses_compare_by_name_and_number() {
832        let s = Status(StatusCode::SEE_OTHER);
833        assert_eq!(s.name(), "see_other");
834        assert!(s == "see_other");
835        assert!(s == 303);
836        assert!(Status(StatusCode::UNPROCESSABLE_ENTITY) == "unprocessable_entity");
837        assert!(Status(StatusCode::OK) == "ok");
838        assert_eq!(format!("{s:?}"), ":see_other (303)");
839    }
840
841    #[test]
842    #[should_panic(expected = "no HTTP status is called `:se_other`")]
843    fn unknown_status_names_fail() {
844        let _ = Status(StatusCode::OK) == "se_other";
845    }
846
847    #[test]
848    fn forms_replace_fields() {
849        let form = Form::new()
850            .with("title", "a")
851            .with("n", 1)
852            .with("title", "b");
853        assert_eq!(form.get("title"), Some("b"));
854        assert_eq!(form.without("n"), Form::new().with("title", "b"));
855    }
856
857    #[test]
858    fn nested_forms_send_rails_style_keys() {
859        let tags = Form::new().with("0", "a");
860        let form = Form::new().with("post", Form::new().with("title", "Hi").with("tags", tags));
861        assert_eq!(form.get("post[title]"), Some("Hi"));
862        assert_eq!(form.get("post[tags][0]"), Some("a"));
863    }
864
865    #[test]
866    #[should_panic(expected = "assertion failed: res.body =~ \"x\"")]
867    fn contains_explains_itself() {
868        assert_contains("hello", "x", "res.body =~ \"x\"");
869    }
870
871    #[test]
872    fn forms_become_json_objects() {
873        let form = Form::new()
874            .with("post", Form::new().with("title", "Hi").with("n", 3))
875            .with("ids[]", 1)
876            .with("ids[]", 2)
877            .with("q", "x");
878        assert_eq!(
879            form.json_body(),
880            r#"{"post":{"title":"Hi","n":"3"},"ids":["2"],"q":"x"}"#,
881            "setting ids[] again replaces it, as in a form"
882        );
883        assert_eq!("{}".json_body(), "{}");
884    }
885}