laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP 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
use std::fmt::Write as _;
use std::future::{Future, IntoFuture};
use std::panic::Location;
use std::pin::Pin;

use serde::Serialize;
use serde_json::{Map, Value};

use crate::Application;
use crate::db::identifier::{is_identifier_path, quote};
use crate::db::sqlx::AssertSqlSafe;
use crate::db::{AnyConnection, DatabaseManager, Driver};
use crate::model::Model;
use crate::numeric::Decimal;

const SHOWN_ROWS: usize = 5;

/// Asserts what a test left in the database, such as the rows a request inserted.
///
/// Each method returns a [`DatabaseAssertion`] to await. The assertion reads the table when you
/// await it, on the writer of the default connection. To read another connection, name it with
/// [`DatabaseAssertion::connection`]:
///
/// ```no_run
/// use laravel::testing::{InteractsWithDatabase, MakesHttpRequests};
/// use serde_json::json;
///
/// # async fn test(app: laravel::Application) {
/// app.post("/imports/7/cancel").await.assert_redirect();
///
/// app.assert_database_has("imports", json!({ "id": 7, "status": "failed", "failed_at": null }))
///     .await;
/// app.assert_database_empty("import_chunks").await;
/// app.assert_database_count("audits", 1).connection("reporting").await;
/// # }
/// ```
///
/// [`assert_model_exists`](Self::assert_model_exists) and
/// [`assert_model_missing`](Self::assert_model_missing) look up a model's row by its key, on the
/// model's own connection:
///
/// ```no_run
/// # use laravel::model::{Faker, IntoCreate, create, factory, model};
/// # use laravel::testing::{InteractsWithDatabase, MakesHttpRequests};
/// # #[model] pub struct Post { pub id: i64, pub title: String }
/// # #[factory(Post)] pub struct PostFactory;
/// # impl PostFactory { fn definition(fake: &mut Faker) -> impl IntoCreate<Post> { create!(Post { title: fake.sentence() }) } }
/// # async fn test(app: laravel::Application) -> laravel::Result<()> {
/// let post = Post::factory().create().await?;
///
/// app.delete(format!("/posts/{}", post.id)).await.assert_redirect();
///
/// app.assert_model_missing(&post).await;
/// # Ok(()) }
/// ```
///
/// The columns to match are a JSON object, or anything that serializes as one. The assertion
/// compares each value with the column's value as the database writes it as text:
///
/// - `null` matches SQL NULL.
/// - A string matches exactly, so write a date or timestamp in the database's own format.
/// - A number matches the same number, so `19.99` matches a decimal column's `19.990`.
/// - `true` matches `true`, `t`, or `1`, and `false` matches `false`, `f`, or `0`.
/// - An array or object matches the same JSON, in any key order and spacing.
///
/// # Panics
///
/// Each method panics when the table or a column name isn't a valid identifier, or when the
/// columns aren't an object. Awaiting the assertion panics when it fails, or when it can't read
/// the connection or the table.
pub trait InteractsWithDatabase {
    /// Run a seeder in the test's transaction, so its rows roll back when the test ends.
    ///
    /// ```no_run
    /// # use laravel::testing::InteractsWithDatabase;
    /// # #[laravel::db::seeder] async fn posts() -> laravel::Result<()> { Ok(()) }
    /// # async fn test(app: laravel::Application) {
    /// app.seed(posts).await;
    /// # }
    /// ```
    ///
    /// The call is a seeding run of its own, so each [`#[seeder]`](macro@crate::db::seeder) that
    /// the seeder calls runs at most once. Seeders that already ran don't run again, whether they
    /// seeded the test's database through
    /// [`seed_once`](crate::foundation::ApplicationBuilder::seed_once) or ran earlier in the test.
    ///
    /// # Panics
    ///
    /// Awaiting the returned future panics when the seeder fails, or when the application doesn't
    /// [refresh the database](crate::foundation::ApplicationBuilder::refresh_database).
    #[track_caller]
    fn seed<S, F>(&self, seeder: S) -> impl Future<Output = ()> + Send + 'static
    where
        S: FnOnce() -> F + Send + 'static,
        F: Future<Output = crate::Result<()>> + Send + 'static;

    /// Assert that the table has a row whose columns have the given values.
    #[track_caller]
    fn assert_database_has(&self, table: &str, columns: impl Serialize) -> DatabaseAssertion;

    /// Assert that the table has no row whose columns have the given values.
    #[track_caller]
    fn assert_database_missing(&self, table: &str, columns: impl Serialize) -> DatabaseAssertion;

    /// Assert that the table has exactly `count` rows.
    #[track_caller]
    fn assert_database_count(&self, table: &str, count: u64) -> DatabaseAssertion;

    /// Assert that the table has no rows.
    #[track_caller]
    fn assert_database_empty(&self, table: &str) -> DatabaseAssertion {
        self.assert_database_count(table, 0)
    }

    /// Assert that the model's table, on the model's connection, has a row with the model's key.
    #[track_caller]
    fn assert_model_exists<M: Model>(&self, model: &M) -> DatabaseAssertion;

    /// Assert that the model's table, on the model's connection, has no row with the model's key.
    #[track_caller]
    fn assert_model_missing<M: Model>(&self, model: &M) -> DatabaseAssertion;
}

impl InteractsWithDatabase for Application {
    #[track_caller]
    fn seed<S, F>(&self, seeder: S) -> impl Future<Output = ()> + Send + 'static
    where
        S: FnOnce() -> F + Send + 'static,
        F: Future<Output = crate::Result<()>> + Send + 'static,
    {
        let application = self.clone();
        let location = Location::caller();
        async move {
            let seeded = application
                .scope(async move || crate::db::seeders::seed_test(&crate::db::manager(), Box::pin(seeder())).await)
                .await;
            if let Err(error) = seeded {
                panic!("seeding the test's database failed: {error:#}\n\nat {location}");
            }
        }
    }

    #[track_caller]
    fn assert_database_has(&self, table: &str, columns: impl Serialize) -> DatabaseAssertion {
        DatabaseAssertion::new(self, table, Expectation::Has(column_values(columns)))
    }

    #[track_caller]
    fn assert_database_missing(&self, table: &str, columns: impl Serialize) -> DatabaseAssertion {
        DatabaseAssertion::new(self, table, Expectation::Missing(column_values(columns)))
    }

    #[track_caller]
    fn assert_database_count(&self, table: &str, count: u64) -> DatabaseAssertion {
        DatabaseAssertion::new(self, table, Expectation::Count(count))
    }

    #[track_caller]
    fn assert_model_exists<M: Model>(&self, model: &M) -> DatabaseAssertion {
        DatabaseAssertion::of_model(self, model, Expectation::Has)
    }

    #[track_caller]
    fn assert_model_missing<M: Model>(&self, model: &M) -> DatabaseAssertion {
        DatabaseAssertion::of_model(self, model, Expectation::Missing)
    }
}

/// A database assertion, from [`InteractsWithDatabase`].
///
/// Await the assertion to read the table and check it.
///
/// # Panics
///
/// Awaiting the assertion panics when it fails, with a message that shows what the table has.
/// It also panics when it can't read the connection or the table.
#[derive(Debug)]
#[must_use = "a database assertion does nothing unless awaited"]
pub struct DatabaseAssertion {
    application: Application,
    connection: Option<String>,
    table: String,
    expectation: Expectation,
    location: &'static Location<'static>,
}

#[derive(Debug)]
enum Expectation {
    Has(Map<String, Value>),
    Missing(Map<String, Value>),
    Count(u64),
}

type Row = Vec<Option<String>>;

impl DatabaseAssertion {
    #[track_caller]
    fn new(application: &Application, table: &str, expectation: Expectation) -> Self {
        assert!(
            is_identifier_path(table),
            "`{table}` isn't a table name; use letters, digits and underscores, optionally after a schema, as in `reporting.users`"
        );

        Self {
            application: application.clone(),
            connection: None,
            table: table.to_owned(),
            expectation,
            location: Location::caller(),
        }
    }

    /// An assertion on the row of `model`, found by its key.
    #[track_caller]
    fn of_model<M: Model>(
        application: &Application,
        model: &M,
        expectation: fn(Map<String, Value>) -> Expectation,
    ) -> Self {
        let key = serde_json::to_value(M::META.key.get(model)).expect("a model's key serializes");
        let columns = Map::from_iter([(M::META.key.name().to_owned(), key)]);
        let assertion = Self::new(application, M::META.table, expectation(columns));
        match connection_of(model) {
            Some(connection) => assertion.connection(connection),
            None => assertion,
        }
    }

    /// Read the table from the named connection instead of the default one.
    pub fn connection(mut self, name: impl Into<String>) -> Self {
        self.connection = Some(name.into());
        self
    }

    async fn check(self) {
        let manager = self.application.resolve::<DatabaseManager>().await;
        let connection = match &self.connection {
            Some(name) => manager.connection(name),
            None => manager.default_connection(),
        };
        let connection = connection.unwrap_or_else(|error| self.fail(format_args!("{error}")));

        match &self.expectation {
            Expectation::Count(expected) => {
                let actual = self.count(&connection).await;
                if actual != *expected {
                    let wanted = match expected {
                        0 => "to be empty".to_owned(),
                        _ => format!("to have {}", row_count(*expected)),
                    };
                    self.fail(format_args!(
                        "expected {} {wanted}, but it has {}",
                        self.describe(),
                        row_count(actual)
                    ));
                }
            }
            Expectation::Has(columns) => {
                let mut found = self.rows(&connection, columns).await;
                if !found.iter().any(|row| matching(row, columns) == columns.len()) {
                    found.sort_by_key(|row| std::cmp::Reverse(matching(row, columns)));
                    self.fail(format_args!(
                        "expected {} to have a row matching {}, but {}",
                        self.describe(),
                        Value::Object(columns.clone()),
                        closest(&found, columns)
                    ));
                }
            }
            Expectation::Missing(columns) => {
                let found = self.rows(&connection, columns).await;
                let matches = found
                    .iter()
                    .filter(|row| matching(row, columns) == columns.len())
                    .count();
                if matches > 0 {
                    self.fail(format_args!(
                        "expected {} to have no row matching {}, but it has {} matching",
                        self.describe(),
                        Value::Object(columns.clone()),
                        row_count(matches as u64)
                    ));
                }
            }
        }
    }

    async fn count(&self, connection: &AnyConnection) -> u64 {
        connection
            .table(self.table.as_str())
            .use_write_connection()
            .count()
            .await
            .unwrap_or_else(|error| self.unreadable(&error))
    }

    async fn rows(&self, connection: &AnyConnection, columns: &Map<String, Value>) -> Vec<Row> {
        // The builder can't cast a column to text, so this select stays SQL...
        let driver = connection.driver();
        let text = match driver {
            Driver::MySql | Driver::MariaDb => "CHAR",
            _ => "TEXT",
        };
        let selected = match columns.is_empty() {
            true => "1".to_owned(),
            false => columns
                .keys()
                .map(|column| format!("CAST({} AS {text})", quote(driver, column)))
                .collect::<Vec<_>>()
                .join(", "),
        };
        let sql = format!("SELECT {selected} FROM {}", quote(driver, &self.table));

        let found = connection
            .query(AssertSqlSafe(sql))
            .use_write_connection()
            .select()
            .await
            .unwrap_or_else(|error| self.unreadable(&error));

        found
            .iter()
            .map(|row| {
                (0..columns.len())
                    .map(|index| row.try_get::<Option<String>>(index))
                    .collect::<crate::Result<Row>>()
                    .unwrap_or_else(|error| self.unreadable(&error))
            })
            .collect()
    }

    fn describe(&self) -> String {
        match &self.connection {
            Some(connection) => format!("the `{}` table on the `{connection}` connection", self.table),
            None => format!("the `{}` table", self.table),
        }
    }

    fn unreadable(&self, error: &crate::Error) -> ! {
        self.fail(format_args!("{} couldn't be read: {error}", self.describe()))
    }

    fn fail(&self, message: std::fmt::Arguments<'_>) -> ! {
        panic!("{message}\n\nat {}", self.location)
    }
}

impl IntoFuture for DatabaseAssertion {
    type Output = ();
    type IntoFuture = Pin<Box<dyn Future<Output = ()> + Send>>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(self.check())
    }
}

#[track_caller]
fn column_values(columns: impl Serialize) -> Map<String, Value> {
    let columns = match serde_json::to_value(columns) {
        Ok(Value::Object(columns)) => columns,
        Ok(other) => panic!("the columns should be an object, such as `json!({{ \"id\": 1 }})`, not `{other}`"),
        Err(error) => panic!("the columns couldn't be serialized: {error}"),
    };
    for column in columns.keys() {
        assert!(
            is_identifier_path(column) && !column.contains('.'),
            "`{column}` isn't a column name; use letters, digits and underscores"
        );
    }

    columns
}

/// The connection that `model` was read from, or else the one its `#[model]` names. The model's
/// own writes use the same connection.
fn connection_of<M: Model>(model: &M) -> Option<String> {
    model.__connection().name().or(M::META.connection).map(str::to_owned)
}

fn matching(row: &[Option<String>], columns: &Map<String, Value>) -> usize {
    columns
        .values()
        .zip(row)
        .filter(|(expected, actual)| equals(expected, actual.as_deref()))
        .count()
}

fn equals(expected: &Value, actual: Option<&str>) -> bool {
    let Some(actual) = actual else {
        return expected.is_null();
    };

    match expected {
        Value::Null => false,
        Value::String(expected) => expected == actual,
        Value::Bool(expected) => boolean(actual) == Some(*expected),
        Value::Number(expected) => {
            let expected = expected.to_string().parse::<Decimal>();
            let actual = actual.parse::<Decimal>();
            matches!((expected, actual), (Ok(expected), Ok(actual)) if expected == actual)
        }
        Value::Array(_) | Value::Object(_) => {
            serde_json::from_str::<Value>(actual).is_ok_and(|actual| actual == *expected)
        }
    }
}

fn boolean(text: &str) -> Option<bool> {
    match text {
        "1" | "t" | "true" => Some(true),
        "0" | "f" | "false" => Some(false),
        _ => None,
    }
}

fn closest(found: &[Row], columns: &Map<String, Value>) -> String {
    if found.is_empty() {
        return "the table is empty".to_owned();
    }

    let mut description = match found.len() {
        1 => "its only row is:".to_owned(),
        count => format!("it has {count} rows, closest first:"),
    };
    for row in found.iter().take(SHOWN_ROWS) {
        let shown: Map<String, Value> = columns
            .iter()
            .zip(row)
            .map(|((column, expected), actual)| (column.clone(), shown(expected, actual.as_deref())))
            .collect();
        let _ = write!(description, "\n{}", Value::Object(shown));
    }
    if found.len() > SHOWN_ROWS {
        let _ = write!(
            description,
            "\nand {} more",
            row_count((found.len() - SHOWN_ROWS) as u64)
        );
    }

    description
}

fn shown(expected: &Value, actual: Option<&str>) -> Value {
    let Some(actual) = actual else {
        return Value::Null;
    };

    let typed = match expected {
        Value::Number(_) => serde_json::from_str::<serde_json::Number>(actual)
            .ok()
            .map(Value::Number),
        Value::Bool(_) => boolean(actual).map(Value::Bool),
        Value::Array(_) | Value::Object(_) => serde_json::from_str(actual).ok(),
        Value::Null | Value::String(_) => None,
    };

    typed.unwrap_or_else(|| Value::String(actual.to_owned()))
}

fn row_count(count: u64) -> String {
    match count {
        1 => "1 row".to_owned(),
        count => format!("{count} rows"),
    }
}