Skip to main content

rok_db_core/
testing.rs

1//! Test support: a fresh, isolated database per test (feature `testing`).
2//!
3//! Most tests use the [`#[rok_db::test]`](https://docs.rs/rok-db/latest/rok_db/attr.test.html)
4//! attribute, which builds on [`TestDb`].
5
6use std::str::FromStr;
7use std::sync::atomic::{AtomicU32, Ordering};
8
9use sqlx::Connection;
10use sqlx::postgres::{PgConnectOptions, PgConnection};
11
12use crate::{Db, Result};
13
14static COUNTER: AtomicU32 = AtomicU32::new(0);
15
16/// A temporary database created on the server named by `DATABASE_URL`
17/// and dropped (with `DROP DATABASE … WITH (FORCE)`, PostgreSQL 13+) when
18/// this value is dropped — also when the test panics.
19///
20/// The `DATABASE_URL` user needs the `CREATEDB` privilege.
21pub struct TestDb {
22    db: Option<Db>,
23    name: String,
24    admin: PgConnectOptions,
25}
26
27impl TestDb {
28    /// Create a database, or `None` when `DATABASE_URL` is not set.
29    pub async fn create() -> Result<Option<Self>> {
30        let Ok(url) = std::env::var("DATABASE_URL") else {
31            return Ok(None);
32        };
33        let admin = PgConnectOptions::from_str(&url)?;
34        let nanos = std::time::SystemTime::now()
35            .duration_since(std::time::UNIX_EPOCH)
36            .map_or(0, |d| d.subsec_nanos());
37        let name = format!(
38            "rok_test_{}_{}_{nanos}",
39            std::process::id(),
40            COUNTER.fetch_add(1, Ordering::Relaxed)
41        );
42        let mut conn = PgConnection::connect_with(&admin).await?;
43        sqlx::query(&format!(r#"CREATE DATABASE "{name}""#))
44            .execute(&mut conn)
45            .await?;
46        conn.close().await?;
47        let db = Db::builder()
48            .max_connections(5)
49            .connect_with(admin.clone().database(&name))
50            .await?;
51        Ok(Some(Self {
52            db: Some(db),
53            name,
54            admin,
55        }))
56    }
57
58    /// The connection pool of the test database.
59    pub fn db(&self) -> &Db {
60        self.db.as_ref().expect("test database is alive")
61    }
62
63    /// The generated database name.
64    pub fn name(&self) -> &str {
65        &self.name
66    }
67
68    /// Run the migrations in `dir` (requires the `migrate` feature).
69    #[cfg(feature = "migrate")]
70    pub async fn migrate(&self, dir: impl AsRef<std::path::Path>) -> Result<()> {
71        self.db().migrate(dir).await
72    }
73}
74
75impl Drop for TestDb {
76    fn drop(&mut self) {
77        // Dropping the pool without awaiting `close` avoids depending on the
78        // test's runtime; `WITH (FORCE)` terminates any leftover connections.
79        drop(self.db.take());
80        let name = std::mem::take(&mut self.name);
81        let admin = self.admin.clone();
82        let cleanup = std::thread::spawn(move || {
83            let runtime = tokio::runtime::Builder::new_current_thread()
84                .enable_all()
85                .build()?;
86            runtime.block_on(async move {
87                let mut conn = PgConnection::connect_with(&admin).await?;
88                sqlx::query(&format!(r#"DROP DATABASE IF EXISTS "{name}" WITH (FORCE)"#))
89                    .execute(&mut conn)
90                    .await?;
91                conn.close().await?;
92                Ok::<_, Box<dyn std::error::Error + Send + Sync>>(())
93            })
94        });
95        match cleanup.join() {
96            Ok(Ok(())) => {}
97            Ok(Err(e)) => eprintln!("rok-db: failed to drop test database: {e}"),
98            Err(_) => eprintln!("rok-db: test database cleanup panicked"),
99        }
100    }
101}
102
103impl std::fmt::Debug for TestDb {
104    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
105        f.debug_struct("TestDb").field("name", &self.name).finish()
106    }
107}