Skip to main content

larust_testing/
db.rs

1use larust_core::AppError;
2use sqlx::AnyPool;
3use std::path::Path;
4use tokio::sync::OnceCell;
5
6static TEST_DB: OnceCell<AnyPool> = OnceCell::const_new();
7
8/// Connects to a fresh, migrated SQLite database for tests (Rust's own
9/// natural test-isolation boundary: `cargo test` already compiles each
10/// `tests/*.rs` file as a separate process, so this is one database per
11/// test *file*, not per test function - every `#[tokio::test]` fn in the
12/// same file shares it).
13///
14/// Idempotent within a process: the first call creates the database and
15/// runs migrations; every later call in the same test binary (i.e. every
16/// other `#[tokio::test]` fn in that file) just returns a clone of the
17/// already-connected pool, sidestepping `larust_support::orm::connect`'s
18/// documented "second call errors" behavior entirely.
19///
20/// Backed by an on-disk `tempfile` database, not `sqlite::memory:` - a
21/// pooled in-memory SQLite database would give each connection its own
22/// private, empty database unless opened with SQLite's shared-cache URI
23/// mode, which has its own real multi-connection subtleties not worth
24/// risking here. The temp directory is intentionally leaked (kept alive
25/// for the process's lifetime, not tied to any single test function's
26/// stack frame) rather than cleaned up - the OS reclaims temp directories
27/// over time, and no test function is a safe place to drop the guard
28/// without deleting the database out from under a *different* test
29/// function that runs afterward and shares the same pool.
30///
31/// This is an additive, no-isolation-between-tests tradeoff, not
32/// Laravel's `DatabaseTransactions` (a per-test rollback sandbox): every
33/// generated `#[derive(Model)]` method and `QueryBuilder` call goes
34/// through `larust_orm`'s single process-wide pool directly, with no
35/// injectable executor to route a test through its own transaction.
36/// Write assertions scoped to the specific rows a test creates, not broad
37/// counts across the whole table.
38pub async fn test_db(migrations_dir: &Path) -> Result<AnyPool, AppError> {
39    let pool = TEST_DB
40        .get_or_try_init(|| async {
41            let dir = tempfile::tempdir()
42                .map_err(|source| AppError::Internal(Box::new(source)))?
43                .keep();
44            let database_url = format!("sqlite://{}/test.sqlite", dir.display());
45
46            larust_support::orm::connect(&database_url).await?;
47            larust_support::orm::migrate(migrations_dir).await?;
48
49            larust_support::orm::pool().cloned()
50        })
51        .await?;
52
53    Ok(pool.clone())
54}