larust_testing/transaction.rs
1use larust_core::AppError;
2use sqlx::any::{AnyConnectOptions, AnyPoolOptions};
3use sqlx::AnyPool;
4use std::future::Future;
5use std::path::Path;
6use std::str::FromStr;
7
8/// Laravel's `RefreshDatabase` (not `DatabaseTransactions` - see below):
9/// runs `body` against a brand-new, freshly migrated, fully isolated
10/// SQLite database that nothing else ever touches. Unlike `test_db()`
11/// (additive, one shared database across every `#[tokio::test]` fn in the
12/// same test binary), each `test_transaction()` call gets its own
13/// dedicated database file and doesn't need the "one test per file"
14/// workaround every other process-wide mechanism in this crate relies on
15/// - see the last paragraph below.
16///
17/// `body` receives the isolated pool directly (the same shape `test_db()`
18/// already returns one for - pass it to `TestClient::new(router, &pool)`/
19/// `Router::with_sessions(&pool, ..)` when the test needs a real router,
20/// or query it directly to assert on rows). Every `#[derive(Model)]`
21/// method and `QueryBuilder` call `body` makes also resolves to this same
22/// isolated pool automatically, via `larust_orm::pool()`'s task-local
23/// override (`larust_orm::with_pool_override`) - no parameter threading
24/// needed anywhere in generated code.
25///
26/// **Why this is `RefreshDatabase`-shaped, not real transaction rollback**
27/// (a real `BEGIN`-before/`ROLLBACK`-after design was tried first, and
28/// abandoned - worth recording why, not just what shipped): wrapping
29/// `body` in a raw SQL transaction (bypassing sqlx's own transaction
30/// bookkeeping, to avoid `larust_orm::pool()`'s return type ever having to
31/// change) works fine for direct `Model`/`QueryBuilder` calls, but breaks
32/// the moment anything *else* on the same connection tries to open a
33/// **real** `sqlx::Transaction` - which `tower-sessions-sqlx-store`
34/// (already a real dependency, used for every session-backed route) does
35/// internally on every session save. Since sqlx's own transaction
36/// tracking has no idea a raw `BEGIN` already opened one, its `pool.
37/// begin()` call issues a second, literal `BEGIN` on the same connection -
38/// SQLite rejects nested `BEGIN`s outright ("cannot start a transaction
39/// within a transaction"), so *any* test using a real router with
40/// sessions (`TestClient` against CSRF/auth-gated routes - the single
41/// most common, most valuable kind of test in this codebase) broke
42/// immediately. A fresh, dedicated database per call has no shared
43/// transaction state for anything else to collide with, so it works
44/// unconditionally - at the cost of paying a real migration run per call
45/// instead of reusing one already-migrated schema and undoing only the
46/// data, which is what a true `DatabaseTransactions`-style design would
47/// save. For this codebase's migration counts, that cost is small; see
48/// `docs/ARCHITECTURE.md`'s Testing section for the full comparison.
49///
50/// **Why this doesn't need "one test per file"**: `tokio::task_local!` is
51/// scoped per-*task*, not process-wide - unlike `larust_orm::connect()`,
52/// the event-listener registry, `larust_mail::fake()`'s recorder, or any
53/// table-bootstrap `OnceCell` in this codebase, nothing here is a
54/// process-wide `OnceLock`/`OnceCell` that a second call could collide
55/// with. Multiple independent `#[tokio::test]` fns - even in the same
56/// file, even running concurrently - each get their own dedicated
57/// database and task-local scope. `body` also has no `Send`/`'static`
58/// bound of any kind (there's no `tokio::spawn` anywhere in this
59/// implementation), matching every other `larust-testing` helper's
60/// ergonomics exactly - a real router (`larust_http::Router` stores its
61/// middleware as `Vec<Box<dyn Fn(..) -> ..>>` with no `+ Send` bound) can
62/// be built directly inside `body`.
63///
64/// **A real, known gap this design doesn't close**: `larust-cache` and
65/// `larust-queue` each lazily self-bootstrap their own table
66/// (`cache_items`; `jobs`/`failed_jobs`) behind their *own*
67/// process-wide `tokio::sync::OnceCell<()>`, memoized once per process -
68/// not once per pool. If one `test_transaction()` call exercises code
69/// that touches Cache or Queue, its bootstrap fires (correctly, against
70/// that call's own isolated pool, via the same task-local override this
71/// function relies on) and then never fires again for the rest of the
72/// process - so a *second*, independent `test_transaction()` call that
73/// also touches Cache/Queue hits "no such table," since its own fresh
74/// pool never got the table created. Hit directly while building this
75/// feature's own demo test (`demo/tests/transaction_test.rs` was
76/// originally written against `PostController::store`, which calls
77/// `cache::forget(...)`, before being rewritten to avoid it for exactly
78/// this reason). Out of scope to fix here - it would mean changing how
79/// `larust-cache`/`larust-queue` track "is my table ready" from
80/// per-process to per-pool, a real change to two other crates' own
81/// designs, not something `test_transaction()` can paper over from the
82/// outside. Tests combining `test_transaction()` with Cache/Queue in the
83/// same process should stick to a single call, or avoid exercising
84/// those two crates' bootstrap path more than once.
85pub async fn test_transaction<F, Fut, T>(migrations_dir: &Path, body: F) -> T
86where
87 F: FnOnce(AnyPool) -> Fut,
88 Fut: Future<Output = T>,
89{
90 // Returns `T` directly and `.expect()`s on setup failure, unlike
91 // `test_db()`'s `Result<AnyPool, AppError>` - deliberate, not an
92 // oversight: `T` is frequently not itself a `Result` (most bodies
93 // just assert and return `()`), so a `Result`-wrapping return here
94 // would force every caller to unwrap two independent failure layers
95 // (this function's own setup, and whatever `body` returns) instead of
96 // one. An isolated test database that fails to even connect/migrate
97 // is an unrecoverable test-infra problem, the same class of failure
98 // `.expect()`/`.unwrap()` is reserved for throughout this codebase's
99 // test helpers.
100 let (pool, backend) = connect_isolated(migrations_dir)
101 .await
102 .expect("failed to set up an isolated test-transaction database");
103
104 // `(*pool).clone()`, not `pool.clone()` - `pool` is `&'static
105 // AnyPool`, and `&T`'s own blanket `Clone` impl would otherwise be
106 // found first, "cloning" the reference itself rather than producing
107 // the owned `AnyPool` `body` expects (cheap either way -
108 // `AnyPool` is `Arc`-backed internally).
109 let scoped_pool = (*pool).clone();
110 larust_orm::with_pool_override(pool, backend, body(scoped_pool)).await
111}
112
113/// A dedicated, freshly migrated pool - deliberately *not* registered
114/// with `larust_orm::connect()`'s process-wide `OnceLock` (that's
115/// `test_db()`'s job; this function needs its own, separate pool object
116/// per call, not a shared global one). Leaked via `Box::leak` to get a
117/// genuine `&'static AnyPool` - an `Arc`-backed pool handle (and its
118/// temp directory) per `test_transaction()` call, in a short-lived test
119/// process, the same "acceptable, deliberate leak in test-only code"
120/// reasoning `test_db()`'s own `.keep()`'d tempdir already relies on -
121/// though not quite the same *scale*: `test_db()` leaks once per test
122/// *binary* (memoized behind its own `OnceCell`), while this leaks once
123/// per *call*, so a test suite making many `test_transaction()` calls in
124/// one binary accumulates that many permanently-open connection pools
125/// and temp files for the life of the process. Still bounded and
126/// reclaimed at process exit, just a faster growth rate - worth knowing
127/// if a test suite built on this one ever grows large.
128async fn connect_isolated(
129 migrations_dir: &Path,
130) -> Result<(&'static AnyPool, larust_orm::Backend), AppError> {
131 sqlx::any::install_default_drivers();
132 let dir = tempfile::tempdir()
133 .map_err(|source| AppError::Internal(Box::new(source)))?
134 .keep();
135 let database_url = format!("sqlite://{}/test.sqlite", dir.display());
136
137 // Sets `larust_orm::backend()`'s process-wide fallback without
138 // touching the process-wide `larust_orm::pool()` singleton (see
139 // `ensure_backend`'s own doc comment) - the returned value is also
140 // what gets scoped as the task-local override below, so every
141 // framework crate's own bootstrap SQL (which branches on `backend()`)
142 // resolves correctly for `fut` regardless of what any other
143 // `connect()`/`with_pool_override` call elsewhere in the process set.
144 let backend = larust_orm::ensure_backend(&database_url)?;
145 let database_url = larust_orm::normalize_sqlite_url(&database_url);
146 let connect_url = if database_url.contains('?') {
147 format!("{database_url}&mode=rwc")
148 } else {
149 format!("{database_url}?mode=rwc")
150 };
151
152 let options = AnyConnectOptions::from_str(&connect_url)
153 .map_err(|source| AppError::Config(Box::new(source)))?;
154 let pool = AnyPoolOptions::new()
155 .connect_with(options)
156 .await
157 .map_err(|source| AppError::Internal(Box::new(source)))?;
158 let pool: &'static AnyPool = Box::leak(Box::new(pool));
159
160 larust_orm::with_pool_override(pool, backend, larust_orm::migrate(migrations_dir)).await?;
161
162 Ok((pool, backend))
163}