use std::future::IntoFuture;
use std::panic::AssertUnwindSafe;
use futures_util::FutureExt;
use laravel::Application;
use laravel::config::Env;
use laravel::config::database::ConnectionConfig;
use laravel::db::{self, Driver};
use laravel::model::model;
use laravel::testing::{DatabaseAssertion, InteractsWithDatabase};
use serde_json::json;
fn memory() -> ConnectionConfig {
let mut config = ConnectionConfig::new("sqlite::memory:");
config.max_connections = 1;
config.idle_timeout = None;
config.max_lifetime = None;
config
}
fn application(connection: ConnectionConfig) -> Application {
Application::configure()
.replace_env(Env::default())
.with_config(move |config, _| {
config.database.default = "primary".into();
config.database.add_connection("primary", connection);
config.database.add_connection("reporting", memory());
})
.create()
}
fn sqlite() -> Application {
application(memory())
}
#[cfg(feature = "database-postgres")]
fn postgres() -> Application {
let url = std::env::var("LARAVEL_TEST_POSTGRES_URL").expect("LARAVEL_TEST_POSTGRES_URL");
application(ConnectionConfig::new(url))
}
#[cfg(feature = "database-mysql")]
fn mysql() -> Application {
let url = std::env::var("LARAVEL_TEST_MYSQL_URL").expect("LARAVEL_TEST_MYSQL_URL");
application(ConnectionConfig::new(url))
}
async fn panic_message(assertion: DatabaseAssertion) -> String {
let panic = AssertUnwindSafe(assertion.into_future())
.catch_unwind()
.await
.expect_err("the assertion should fail");
panic.downcast_ref::<String>().cloned().unwrap_or_default()
}
async fn failure(assertion: DatabaseAssertion) -> String {
let message = panic_message(assertion).await;
let (message, _) = message.rsplit_once("\n\nat ").expect("the failure names its location");
message.to_owned()
}
async fn statement(sql: String) -> laravel::Result<()> {
db::default_connection()?
.query(db::sqlx::AssertSqlSafe(sql))
.statement()
.await?;
Ok(())
}
async fn seed(table: &str) -> laravel::Result<()> {
let (decimal, json) = match db::default_connection()?.driver() {
Driver::Postgres => ("NUMERIC(10, 3)", "JSON"),
Driver::MySql | Driver::MariaDb => ("DECIMAL(10, 3)", "JSON"),
Driver::Sqlite => ("NUMERIC", "TEXT"),
};
statement(format!("DROP TABLE IF EXISTS {table}")).await?;
statement(format!(
"CREATE TABLE {table} (id BIGINT NOT NULL, status VARCHAR(255) NOT NULL, active BOOLEAN NOT NULL, \
total {decimal} NOT NULL, failed_at TIMESTAMP NULL, settings {json} NULL)"
))
.await?;
statement(format!(
"INSERT INTO {table} VALUES \
(7, 'failed', TRUE, 19.990, '2026-10-23 12:00:00', '{{\"theme\": \"dark\", \"notifications\": true}}'), \
(8, 'pending', FALSE, 5, NULL, NULL), \
(9, 'pending', TRUE, 0.5, NULL, '[1, 2]')"
))
.await
}
async fn contract(app: &Application, table: &str) -> laravel::Result<()> {
seed(table).await?;
let empty = format!("{table}_empty");
statement(format!("DROP TABLE IF EXISTS {empty}")).await?;
statement(format!("CREATE TABLE {empty} (id BIGINT NOT NULL)")).await?;
app.assert_database_has(table, json!({ "id": 7, "status": "failed" }))
.await;
app.assert_database_missing(table, json!({ "id": 7, "status": "pending" }))
.await;
app.assert_database_has(table, json!({ "id": 8, "failed_at": null }))
.await;
app.assert_database_missing(table, json!({ "id": 7, "failed_at": null }))
.await;
app.assert_database_has(table, json!({ "id": 7, "active": true })).await;
app.assert_database_has(table, json!({ "id": 8, "active": false }))
.await;
app.assert_database_missing(table, json!({ "id": 7, "active": false }))
.await;
app.assert_database_has(table, json!({ "id": 7, "total": 19.99 })).await;
app.assert_database_has(table, json!({ "id": 8, "total": 5 })).await;
app.assert_database_missing(table, json!({ "total": 19.9 })).await;
app.assert_database_missing(table, json!({ "status": "Failed" })).await;
app.assert_database_has(table, json!({ "settings": { "notifications": true, "theme": "dark" } }))
.await;
app.assert_database_has(table, json!({ "settings": [1, 2] })).await;
app.assert_database_missing(table, json!({ "settings": [2, 1] })).await;
app.assert_database_missing(table, json!({ "settings": { "theme": "dark" } }))
.await;
app.assert_database_has(table, json!({})).await;
app.assert_database_count(table, 3).await;
app.assert_database_empty(&empty).await;
app.assert_database_missing(&empty, json!({})).await;
assert_eq!(
failure(app.assert_database_has(table, json!({ "id": 8, "status": "failed", "active": false }))).await,
format!(
"expected the `{table}` table to have a row matching {{\"id\":8,\"status\":\"failed\",\"active\":false}}, \
but it has 3 rows, closest first:\n\
{{\"id\":8,\"status\":\"pending\",\"active\":false}}\n\
{{\"id\":7,\"status\":\"failed\",\"active\":true}}\n\
{{\"id\":9,\"status\":\"pending\",\"active\":true}}"
)
);
assert_eq!(
failure(app.assert_database_has(table, json!({ "id": 7, "settings": { "theme": "light" } })))
.await
.lines()
.nth(1),
Some(r#"{"id":7,"settings":{"theme":"dark","notifications":true}}"#)
);
assert_eq!(
failure(app.assert_database_missing(table, json!({ "status": "pending" }))).await,
format!(
"expected the `{table}` table to have no row matching {{\"status\":\"pending\"}}, but it has 2 rows matching"
)
);
assert_eq!(
failure(app.assert_database_count(table, 1)).await,
format!("expected the `{table}` table to have 1 row, but it has 3 rows")
);
assert_eq!(
failure(app.assert_database_empty(table)).await,
format!("expected the `{table}` table to be empty, but it has 3 rows")
);
assert_eq!(
failure(app.assert_database_has(&empty, json!({ "id": 1 }))).await,
format!("expected the `{empty}` table to have a row matching {{\"id\":1}}, but the table is empty")
);
assert!(
failure(app.assert_database_count("laravel_missing_table", 0))
.await
.starts_with("the `laravel_missing_table` table couldn't be read: ")
);
Ok(())
}
#[laravel::test(app = sqlite)]
async fn sqlite_assertions_compare_each_kind_of_value(app: Application) -> laravel::Result<()> {
contract(&app, "laravel_assertions").await
}
#[cfg(feature = "database-postgres")]
#[laravel::test(app = postgres)]
#[ignore = "requires LARAVEL_TEST_POSTGRES_URL pointing to a disposable database"]
async fn postgres_assertions_compare_each_kind_of_value(app: Application) -> laravel::Result<()> {
contract(&app, "laravel_assertions").await
}
#[cfg(feature = "database-mysql")]
#[laravel::test(app = mysql)]
#[ignore = "requires LARAVEL_TEST_MYSQL_URL pointing to a disposable database"]
async fn mysql_assertions_compare_each_kind_of_value(app: Application) -> laravel::Result<()> {
contract(&app, "laravel_assertions").await
}
#[laravel::test(app = sqlite)]
async fn assertions_read_the_named_connection(app: Application) -> laravel::Result<()> {
let reporting = db::connection("reporting")?;
reporting
.query("CREATE TABLE audits (event TEXT NOT NULL)")
.statement()
.await?;
reporting
.query("INSERT INTO audits VALUES ('imported')")
.statement()
.await?;
app.assert_database_has("audits", json!({ "event": "imported" }))
.connection("reporting")
.await;
app.assert_database_count("audits", 1).connection("reporting").await;
assert_eq!(
failure(app.assert_database_empty("audits").connection("reporting")).await,
"expected the `audits` table on the `reporting` connection to be empty, but it has 1 row"
);
assert!(
failure(app.assert_database_count("audits", 1))
.await
.starts_with("the `audits` table couldn't be read: ")
);
Ok(())
}
#[model]
pub struct Audit {
pub id: i64,
pub event: String,
}
#[laravel::test(app = sqlite)]
async fn model_assertions_read_the_connection_the_model_came_from(app: Application) -> laravel::Result<()> {
for connection in ["primary", "reporting"] {
db::connection(connection)?
.query("CREATE TABLE audits (id BIGINT NOT NULL, event TEXT NOT NULL)")
.statement()
.await?;
}
db::connection("reporting")?
.query("INSERT INTO audits VALUES (1, 'imported')")
.statement()
.await?;
let audit = Audit::query()
.connection("reporting")
.find(1)
.await?
.expect("the reporting connection has audit 1");
app.assert_model_exists(&audit).await;
assert_eq!(
failure(app.assert_model_missing(&audit)).await,
r#"expected the `audits` table on the `reporting` connection to have no row matching {"id":1}, but it has 1 row matching"#
);
Ok(())
}
#[test]
fn table_and_column_names_must_be_identifiers() {
let app = sqlite();
let invalid = |assertion: fn(&Application)| {
let panic = std::panic::catch_unwind(AssertUnwindSafe(|| assertion(&app))).expect_err("it should panic");
panic.downcast_ref::<String>().cloned().unwrap_or_default()
};
assert_eq!(
invalid(|app| drop(app.assert_database_empty("users; DROP TABLE users"))),
"`users; DROP TABLE users` isn't a table name; use letters, digits and underscores, optionally after a schema, as in `reporting.users`"
);
assert_eq!(
invalid(|app| drop(app.assert_database_has("users", json!({ "lower(email)": "a" })))),
"`lower(email)` isn't a column name; use letters, digits and underscores"
);
assert_eq!(
invalid(|app| drop(app.assert_database_missing("users", [("email", "a")]))),
r#"the columns should be an object, such as `json!({ "id": 1 })`, not `[["email","a"]]`"#
);
}
#[laravel::test(app = sqlite)]
async fn awaited_failures_name_the_line_that_made_the_assertion(app: Application) -> laravel::Result<()> {
seed("laravel_locations").await?;
let at = |line: u32| format!("\n\nat {}:{line}:", file!());
let line = line!() + 1;
let message = panic_message(app.assert_database_has("laravel_locations", json!({ "id": 1 }))).await;
assert!(message.contains(&at(line)), "{message}");
let line = line!() + 1;
let message = panic_message(app.assert_database_missing("laravel_locations", json!({ "id": 7 }))).await;
assert!(message.contains(&at(line)), "{message}");
let line = line!() + 1;
let message = panic_message(app.assert_database_empty("laravel_locations").connection("primary")).await;
assert!(message.contains(&at(line)), "{message}");
let line = line!() + 1;
let message = panic_message(app.assert_database_count("laravel_missing_table", 0)).await;
assert!(message.contains(&at(line)), "{message}");
let line = line!() + 1;
let assertion = app.assert_database_count("laravel_locations", 0);
let message = panic_message(assertion.connection("undefined")).await;
assert!(message.contains(&at(line)), "{message}");
Ok(())
}