Skip to main content

doido_model/
testing.rs

1use crate::sea_orm_migration::MigratorTrait;
2use doido_core::Result;
3use sea_orm::{Database, DatabaseConnection};
4
5pub struct TestDb {
6    conn: DatabaseConnection,
7}
8
9impl TestDb {
10    pub async fn new() -> Result<Self> {
11        let conn = Database::connect("sqlite::memory:")
12            .await
13            .map_err(|e| doido_core::anyhow::anyhow!("TestDb connect failed: {e}"))?;
14        Ok(Self { conn })
15    }
16
17    pub fn conn(&self) -> &DatabaseConnection {
18        &self.conn
19    }
20
21    /// Run all of `M`'s migrations against this database (test convenience for
22    /// the spec's `testing::run_migrations()`).
23    pub async fn run_migrations<M: MigratorTrait>(&self) -> Result<()> {
24        M::up(&self.conn, None)
25            .await
26            .map_err(|e| doido_core::anyhow::anyhow!("run_migrations failed: {e}"))
27    }
28
29    /// Run a seed routine against this database (test convenience for the spec's
30    /// `testing::seed()`). Delegates to [`crate::seeds::run_seeds`].
31    pub async fn seed(
32        &self,
33        seeder: impl AsyncFnOnce(&DatabaseConnection) -> Result<()>,
34    ) -> Result<()> {
35        crate::seeds::run_seeds(&self.conn, seeder).await
36    }
37}