use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use laravel::Application;
use laravel::config::Env;
use laravel::db::{AnyConnection, DatabaseManager, Migrations};
use laravel::event::Event;
use laravel::foundation::StartupError;
use laravel::model::{Created, create, model};
use crate::migrations::{audits, users};
use crate::support::TempDir;
fn application(url: &str, migrations: Migrations) -> Application {
configure(url).with_migrations(migrations).refresh_database().create()
}
fn configure(url: &str) -> laravel::foundation::ApplicationBuilder {
Application::configure().replace_env(Env::from_iter([
("APP_ENV", "testing"),
("DB_CONNECTION", "primary"),
("DATABASE_URL", url),
]))
}
fn test<T>(work: impl AsyncFnOnce() -> laravel::Result<T>) -> laravel::Result<T> {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?
.block_on(async { tokio::time::timeout(Duration::from_secs(30), work()).await })
.expect("the test shouldn't wait for another")
}
async fn database(app: &Application) -> laravel::Result<AnyConnection> {
app.resolve::<DatabaseManager>().await.default_connection()
}
async fn count(app: &Application, sql: &'static str) -> laravel::Result<i64> {
Ok(database(app).await?.query(sql).scalar::<i64>().await?.unwrap_or(0))
}
fn sqlite(root: &TempDir) -> String {
format!("sqlite://{}", root.join("database.sqlite").display())
}
fn files(root: &TempDir) -> Vec<String> {
let mut files: Vec<_> = std::fs::read_dir(&**root)
.expect("the directory should be readable")
.map(|entry| {
entry
.expect("the entry should be readable")
.file_name()
.to_string_lossy()
.into_owned()
})
.filter(|name| name.ends_with(".sqlite"))
.collect();
files.sort();
files
}
#[test]
fn tests_that_run_one_after_another_reuse_one_migrated_database() -> laravel::Result<()> {
let root = TempDir::new("refresh-sequential");
let url = sqlite(&root);
for _ in 0..2 {
test(async || {
let app = application(&url, users());
assert_eq!(count(&app, "SELECT COUNT(*) FROM users").await?, 0);
database(&app)
.await?
.query("INSERT INTO users (email) VALUES ('taylor@laravel.com')")
.insert()
.await?;
assert_eq!(count(&app, "SELECT COUNT(*) FROM users").await?, 1);
assert_eq!(count(&app, "SELECT COUNT(*) FROM migrations").await?, 2);
Ok(())
})?;
}
assert_eq!(files(&root), ["database_unit_1.sqlite"]);
Ok(())
}
#[test]
fn tests_that_run_at_the_same_time_get_databases_of_their_own() -> laravel::Result<()> {
let root = TempDir::new("refresh-concurrent");
let url = sqlite(&root);
test(async || {
let first = application(&url, users());
let second = application(&url, users());
let insert = "INSERT INTO users (email) VALUES ('taylor@laravel.com')";
database(&first).await?.query(insert).insert().await?;
tokio::time::timeout(Duration::from_secs(1), database(&second).await?.query(insert).insert())
.await
.expect("the second test shouldn't wait for the first")?;
assert_eq!(count(&first, "SELECT COUNT(*) FROM users").await?, 1);
assert_eq!(count(&second, "SELECT COUNT(*) FROM users").await?, 1);
Ok(())
})?;
assert_eq!(files(&root), ["database_unit_1.sqlite", "database_unit_2.sqlite"]);
Ok(())
}
#[test]
fn a_database_that_a_test_committed_to_is_rebuilt_for_the_next_test() -> laravel::Result<()> {
let root = TempDir::new("refresh-committed");
let url = sqlite(&root);
test(async || {
let app = application(&url, users());
let connection = database(&app).await?;
connection
.query("INSERT INTO users (email) VALUES ('taylor@laravel.com')")
.insert()
.await?;
let mut native = connection.typed::<laravel::db::sqlx::Sqlite>()?.acquire().await?;
laravel::db::sqlx::raw_sql("COMMIT").execute(&mut *native).await?;
Ok(())
})?;
test(async || {
let app = application(&url, users());
assert_eq!(count(&app, "SELECT COUNT(*) FROM users").await?, 0);
Ok(())
})
}
#[test]
fn a_new_build_of_the_migrations_rebuilds_the_database() -> laravel::Result<()> {
let root = TempDir::new("refresh-changed");
let url = sqlite(&root);
let tables = "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name IN ('users', 'audits')";
test(async || {
let app = application(&url, users());
assert_eq!(count(&app, tables).await?, 1);
Ok(())
})?;
test(async || {
let app = application(&url, audits());
assert_eq!(count(&app, tables).await?, 1);
assert_eq!(count(&app, "SELECT COUNT(*) FROM audits").await?, 0);
Ok(())
})
}
#[tokio::test]
async fn application_transactions_commit_into_the_tests_transaction_and_run_after_commit_callbacks()
-> laravel::Result<()> {
let root = TempDir::new("refresh-transactions");
let app = application(&sqlite(&root), users());
let connection = database(&app).await?;
let committed = Arc::new(AtomicBool::new(false));
let flag = Arc::clone(&committed);
connection
.transaction(async |tx| {
assert_eq!(tx.level(), 1);
tx.query("INSERT INTO users (email) VALUES ('a@laravel.com')")
.insert()
.await?;
tx.after_commit(move || async move {
flag.store(true, Ordering::SeqCst);
Ok(())
})
.await
})
.await?;
assert!(committed.load(Ordering::SeqCst));
let failed = connection
.transaction(async |tx| {
tx.query("INSERT INTO users (email) VALUES ('b@laravel.com')")
.insert()
.await?;
Err::<(), _>(laravel::abort_with(500, "rolled back"))
})
.await;
assert!(failed.is_err());
assert_eq!(count(&app, "SELECT COUNT(*) FROM users").await?, 1);
Ok(())
}
#[model]
pub struct User {
pub id: i64,
pub email: String,
}
#[tokio::test]
async fn model_listeners_run_in_the_tests_transaction_and_wait_for_the_applications_commit() -> laravel::Result<()> {
let root = TempDir::new("refresh-events");
let welcomed = Arc::new(Mutex::new(Vec::new()));
let app = configure(&sqlite(&root))
.with_migrations(users())
.refresh_database()
.with_events({
let welcomed = Arc::clone(&welcomed);
move |events, _| {
events.listen(move |event: Event<Created<User>>| {
let welcomed = Arc::clone(&welcomed);
async move { welcomed.lock().unwrap().push(event.model.email.clone()) }
});
}
})
.create();
app.scope(async || {
create!(User {
email: "taylor@laravel.com"
})
.await?;
assert_eq!(*welcomed.lock().unwrap(), ["taylor@laravel.com"]);
laravel::db::transaction(async |_| {
create!(User {
email: "abigail@laravel.com"
})
.await?;
assert_eq!(*welcomed.lock().unwrap(), ["taylor@laravel.com"]);
Ok(())
})
.await?;
assert_eq!(*welcomed.lock().unwrap(), ["taylor@laravel.com", "abigail@laravel.com"]);
Ok(())
})
.await
}
#[tokio::test]
async fn an_in_memory_database_is_migrated_for_each_test() -> laravel::Result<()> {
for _ in 0..2 {
let app = application("sqlite::memory:", users());
database(&app)
.await?
.query("INSERT INTO users (email) VALUES ('a@laravel.com')")
.insert()
.await?;
assert_eq!(count(&app, "SELECT COUNT(*) FROM users").await?, 1);
}
Ok(())
}
#[test]
fn refreshing_outside_the_testing_environment_stops_the_application() {
let error = Application::configure()
.replace_env(Env::from_iter([("APP_ENV", "local")]))
.refresh_database()
.try_create()
.expect_err("refreshing outside testing should be a startup error");
assert_eq!(error, StartupError::RefreshDatabase("local".into()));
}
#[cfg(any(feature = "database-postgres", feature = "database-mysql"))]
fn disposable(url: &str, purpose: &str) -> (String, String) {
let (server, _) = url.rsplit_once('/').expect("the URL should name a database");
(
server.to_owned(),
format!("laravel_refresh_{purpose}_{}", std::process::id()),
)
}
#[cfg(feature = "database-postgres")]
fn drop_postgres_slots(server: &str, name: &str) -> laravel::Result<()> {
test(async || {
let admin = configure(&format!("{server}/postgres")).create();
for slot in [1, 2] {
let sql = format!("DROP DATABASE IF EXISTS {name}_{slot} WITH (FORCE)");
database(&admin)
.await?
.query(laravel::db::sqlx::AssertSqlSafe(sql))
.statement()
.await?;
}
Ok(())
})
}
#[cfg(feature = "database-postgres")]
#[test]
#[ignore = "requires LARAVEL_TEST_POSTGRES_URL pointing to a disposable database"]
fn postgres_creates_a_database_for_each_concurrent_test_and_survives_failed_queries() -> laravel::Result<()> {
let (server, name) = disposable(&std::env::var("LARAVEL_TEST_POSTGRES_URL")?, "concurrent");
let url = format!("{server}/{name}");
let unique = "CREATE UNIQUE INDEX users_email_unique ON users (email)";
let insert = "INSERT INTO users (email) VALUES ('taylor@laravel.com')";
let ran = test(async || {
let first = application(&url, users());
let second = application(&url, users());
for app in [&first, &second] {
database(app).await?.query(unique).statement().await?;
}
database(&first).await?.query(insert).insert().await?;
tokio::time::timeout(Duration::from_secs(1), database(&second).await?.query(insert).insert())
.await
.expect("the second test shouldn't wait for the first")?;
assert!(database(&first).await?.query(insert).insert().await.is_err());
assert_eq!(count(&first, "SELECT COUNT(*) FROM users").await?, 1);
Ok(())
})
.and_then(|()| {
test(async || {
let app = application(&url, users());
assert_eq!(count(&app, "SELECT COUNT(*) FROM users").await?, 0);
Ok(())
})
});
drop_postgres_slots(&server, &name)?;
ran
}
#[cfg(feature = "database-postgres")]
#[test]
#[ignore = "requires LARAVEL_TEST_POSTGRES_URL pointing to a disposable database"]
fn postgres_cache_and_its_locks_work_inside_an_application_transaction() -> laravel::Result<()> {
let (server, name) = disposable(&std::env::var("LARAVEL_TEST_POSTGRES_URL")?, "stores");
let mut migrations = users();
migrations.add(laravel::db::migrations!("tests/fixtures/migrations/cache"));
let ran = test(async || {
let app = configure(&format!("{server}/{name}"))
.with_env("CACHE_STORE", "database")
.with_migrations(migrations)
.refresh_database()
.create();
app.scope(async || {
database(&app)
.await?
.transaction(async |tx| {
tx.query("INSERT INTO users (email) VALUES ('taylor@laravel.com')")
.insert()
.await?;
laravel::cache::put("greeting", "Hello", Duration::from_secs(60)).await?;
let lock = laravel::cache::lock("reports", Duration::from_secs(60))?;
let acquired = tokio::time::timeout(Duration::from_secs(2), lock.acquire())
.await
.expect("the lock shouldn't wait for the transaction")?;
assert!(acquired);
Ok(())
})
.await?;
assert_eq!(
laravel::cache::get::<String>("greeting").await?.as_deref(),
Some("Hello")
);
Ok(())
})
.await
});
drop_postgres_slots(&server, &name)?;
ran
}
#[cfg(feature = "database-mysql")]
#[test]
#[ignore = "requires LARAVEL_TEST_MYSQL_URL pointing to a disposable database"]
fn mysql_rebuilds_a_database_after_ddl_commits_a_tests_transaction() -> laravel::Result<()> {
let url = std::env::var("LARAVEL_TEST_MYSQL_URL")?;
let (server, name) = disposable(&url, "ddl");
let configured = format!("{server}/{name}");
let ran = test(async || {
let app = application(&configured, users());
let connection = database(&app).await?;
connection
.query("INSERT INTO users (id, email) VALUES (1, 'taylor@laravel.com')")
.insert()
.await?;
connection.query("CREATE TABLE leftovers (id INT)").statement().await?;
Ok(())
})
.and_then(|()| {
test(async || {
let app = application(&configured, users());
assert_eq!(count(&app, "SELECT COUNT(*) FROM users").await?, 0);
let leftovers = "SELECT COUNT(*) FROM information_schema.tables \
WHERE table_schema = DATABASE() AND table_name = 'leftovers'";
assert_eq!(count(&app, leftovers).await?, 0);
Ok(())
})
});
test(async || {
let admin = configure(&url).create();
for number in [1, 2] {
let sql = format!("DROP DATABASE IF EXISTS `{name}_{number}`");
database(&admin)
.await?
.query(laravel::db::sqlx::AssertSqlSafe(sql))
.statement()
.await?;
}
Ok(())
})?;
ran
}
#[test]
fn on_sqlite_writes_outside_the_transaction_join_the_tests_transaction() -> laravel::Result<()> {
let root = TempDir::new("refresh-outside");
let url = sqlite(&root);
test(async || {
let app = application(&url, users());
let outside = database(&app).await?.outside_transaction();
tokio::time::timeout(
Duration::from_secs(2),
outside
.query("INSERT INTO users (email) VALUES ('taylor@laravel.com')")
.insert(),
)
.await
.expect("the write shouldn't wait for the test's transaction")?;
assert_eq!(count(&app, "SELECT COUNT(*) FROM users").await?, 1);
Ok(())
})?;
test(async || {
let app = application(&url, users());
assert_eq!(count(&app, "SELECT COUNT(*) FROM users").await?, 0);
Ok(())
})
}