Skip to main content

loco_rs/testing/
db.rs

1#[cfg(feature = "db-postgres")]
2use crate::hash;
3use crate::{
4    app::{AppContext, Hooks},
5    db, Error, Result,
6};
7#[cfg(feature = "db-postgres")]
8use sqlx::{AssertSqlSafe, Pool, Postgres};
9use std::future::Future;
10use std::path::PathBuf;
11use std::pin::Pin;
12use tree_fs::TreeBuilder;
13#[cfg(feature = "db-postgres")]
14use url::Url;
15
16/// Seeds data into the database.
17///
18///
19/// # Errors
20/// When seed fails
21///
22/// # Example
23///
24/// The provided example demonstrates how to boot the test case and run seed
25/// data.
26///
27/// ```rust,ignore
28/// use myapp::app::App;
29/// use loco_rs::testing::prelude::*;
30///
31/// #[tokio::test]
32/// async fn test_create_user() {
33///     let boot = boot_test::<App>().await;
34///     seed::<App>(&boot.app_context).await.unwrap();
35///
36///     /// .....
37///     assert!(false)
38/// }
39/// ```
40pub async fn seed<H: Hooks>(ctx: &AppContext) -> Result<()> {
41    let path = std::path::Path::new("src/fixtures");
42    H::seed(ctx, path).await
43}
44
45/// Initializes a test database connection.
46///
47/// # Errors
48/// Returns an error if could not create a new test db.
49pub fn init_test_db_creation(conn_str: &str) -> Result<Box<dyn TestSupport>> {
50    #[cfg(feature = "db-postgres")]
51    if conn_str.starts_with("postgres://") {
52        return PostgresTest::new(conn_str).map(|test| Box::new(test) as Box<dyn TestSupport>);
53    }
54    if conn_str.starts_with("sqlite://") {
55        SqliteTest::new(conn_str).map(|test| Box::new(test) as Box<dyn TestSupport>)
56    } else {
57        Ok(Box::new(Any::new(conn_str)))
58    }
59}
60
61pub trait TestSupport: Send + Sync {
62    /// Initializes the database.
63    fn init_db<'a>(&'a self) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>>;
64    /// Returns the connection string.
65    fn get_connection_str(&self) -> &str;
66    /// Cleans up the database.
67    fn cleanup_db(&self);
68}
69
70#[cfg(feature = "db-postgres")]
71pub struct PostgresTest {
72    root_connection_string: String,
73    connection_string: String,
74    schema_name: String,
75}
76
77#[cfg(feature = "db-postgres")]
78impl PostgresTest {
79    /// Creates a new `PostgreSQL` test database.
80    ///
81    /// # Errors
82    /// Returns an error if could not create DB schema.
83    pub fn new(conn_str: &str) -> Result<Self> {
84        // Validate that a db name is present in the connection string, matching
85        // prior behavior. The name itself is not used for string replacement
86        // below (see the `Url`-based rewrite), only the connection string's
87        // parsed `path` is.
88        let _db_name = db::extract_db_name(conn_str)?;
89
90        let current_timestamp = chrono::Utc::now().timestamp();
91        let test_schema_name: String = hash::random_string(10).to_lowercase();
92        let test_schema_name = format!("_loco_test_{test_schema_name}_{current_timestamp}");
93
94        // Rewrite only the URI path (the db name) via `url::Url`, rather than a
95        // naive whole-string `.replace(db_name, ..)`, which would corrupt the
96        // URI whenever the db name is also a substring of the host or
97        // credentials (e.g. db "loco" with user/host containing "loco").
98        let mut root_url = Url::parse(conn_str).map_err(|err| {
99            Error::string(&format!(
100                "could not parse Postgres connection string: {err}"
101            ))
102        })?;
103        root_url.set_path("/postgres");
104
105        let mut test_url = Url::parse(conn_str).map_err(|err| {
106            Error::string(&format!(
107                "could not parse Postgres connection string: {err}"
108            ))
109        })?;
110        test_url.set_path(&format!("/{test_schema_name}"));
111
112        Ok(Self {
113            root_connection_string: root_url.to_string(),
114            connection_string: test_url.to_string(),
115            schema_name: test_schema_name,
116        })
117    }
118}
119
120#[cfg(feature = "db-postgres")]
121impl TestSupport for PostgresTest {
122    fn get_connection_str(&self) -> &str {
123        &self.connection_string
124    }
125
126    fn init_db<'a>(&'a self) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
127        Box::pin(async move {
128            let pool = Pool::<Postgres>::connect(&self.root_connection_string)
129                .await
130                .expect("db connection should success");
131            let query = format!("CREATE DATABASE {};", self.schema_name);
132
133            sqlx::query(AssertSqlSafe(query))
134                .execute(&pool)
135                .await
136                .expect("create DB schema");
137        })
138    }
139
140    fn cleanup_db(&self) {
141        let connection_string = self.root_connection_string.clone();
142        let table_name = self.schema_name.clone();
143
144        // Run the drop on a dedicated OS thread with its own runtime (not
145        // `tokio::task::spawn_blocking`, which schedules onto the ambient
146        // runtime and cannot be awaited from a sync/Drop context) and `.join()`
147        // it so cleanup fully completes before `cleanup_db` returns. This is
148        // safe to call from `Drop::drop` since nothing here is `.await`ed on
149        // the caller's runtime.
150        std::thread::spawn(move || {
151            let rt = tokio::runtime::Builder::new_current_thread()
152                .enable_all()
153                .build()
154                .expect("create cleanup runtime");
155
156            rt.block_on(async {
157                let pool = Pool::<Postgres>::connect(&connection_string)
158                    .await
159                    .expect("db connection should success");
160                let query = format!("drop database if exists {table_name};");
161                sqlx::query(AssertSqlSafe(query))
162                    .execute(&pool)
163                    .await
164                    .expect("Drop database");
165            });
166        })
167        .join()
168        .expect("db cleanup thread panicked");
169    }
170}
171
172pub struct SqliteTest {
173    connection_string: String,
174    db_folder: PathBuf,
175    _tree: tree_fs::Tree, // Keep the tree alive while the test runs
176}
177
178impl SqliteTest {
179    /// Prepare new `SQLite` connection string.
180    ///
181    /// # Errors
182    /// Returns an error if could not prepare the connection string
183    pub fn new(conn_str: &str) -> Result<Self> {
184        let db_name = db::extract_db_name(conn_str)?;
185
186        let tree = TreeBuilder::default()
187            .add_empty_file("test.sqlite")
188            .create()
189            .map_err(|err| {
190                Error::string(&format!(
191                    "could not create test database directory. err: {err}"
192                ))
193            })?;
194
195        Ok(Self {
196            connection_string: conn_str.replace(
197                db_name,
198                &tree.root.join("test.sqlite").display().to_string(),
199            ),
200            db_folder: tree.root.clone(),
201            _tree: tree,
202        })
203    }
204}
205
206impl TestSupport for SqliteTest {
207    fn get_connection_str(&self) -> &str {
208        &self.connection_string
209    }
210    fn init_db<'a>(&'a self) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
211        Box::pin(async move {})
212    }
213
214    fn cleanup_db(&self) {
215        std::fs::remove_dir_all(&self.db_folder).expect("Could not delete sqlite test db");
216    }
217}
218
219pub struct Any {
220    connection_string: String,
221}
222impl Any {
223    #[must_use]
224    pub fn new(conn_str: &str) -> Self {
225        Self {
226            connection_string: conn_str.to_string(),
227        }
228    }
229}
230
231impl TestSupport for Any {
232    fn get_connection_str(&self) -> &str {
233        &self.connection_string
234    }
235    fn init_db<'a>(&'a self) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
236        Box::pin(async move {})
237    }
238
239    fn cleanup_db(&self) {}
240}
241
242#[cfg(test)]
243mod tests {
244
245    use super::*;
246    use sqlx::Row;
247
248    async fn schema_exists(pool: &sqlx::PgPool, schema_name: &str) -> bool {
249        let row =
250            sqlx::query("SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_database  WHERE datname = $1)")
251                .bind(schema_name)
252                .fetch_one(pool)
253                .await
254                .expect("check if table exists");
255
256        println!("schema_name: {row:#?}");
257        row.get(0)
258    }
259
260    #[tokio::test]
261    async fn sqlite_test_support() {
262        let conn = "sqlite://test.sqlite?mode=rwc";
263        let sqlite = SqliteTest::new(conn).expect("create Sqlite test support");
264
265        sqlite.init_db().await;
266
267        assert!(sqlite.db_folder.exists());
268        sqlite.cleanup_db();
269        assert!(!sqlite.db_folder.exists());
270    }
271
272    #[tokio::test]
273    async fn postgres_test_support() {
274        let (conn, _container) = crate::tests_cfg::postgres::setup_postgres_container().await;
275        let pg: PostgresTest = PostgresTest::new(&conn).expect("create Postgres test support");
276
277        pg.init_db().await;
278
279        let pool = Pool::<Postgres>::connect(&conn)
280            .await
281            .expect("db connection should success");
282
283        assert!(schema_exists(&pool, &pg.schema_name).await);
284
285        pg.cleanup_db();
286
287        // `cleanup_db` joins its cleanup thread before returning, so the drop
288        // is guaranteed complete here with no sleep needed.
289        assert!(!schema_exists(&pool, &pg.schema_name).await);
290    }
291
292    #[test]
293    fn postgres_test_new_does_not_corrupt_host_or_user_when_db_name_is_substring() {
294        // The db name "loco" is also a substring of the user ("loco") and the
295        // host ("loco-db.host"). A naive `conn_str.replace(db_name, ..)` would
296        // corrupt those occurrences too. Assert only the path changes.
297        let conn_str = "postgres://loco:pass@loco-db.host:5432/loco";
298
299        let pg = PostgresTest::new(conn_str).expect("create Postgres test support");
300
301        let root =
302            Url::parse(&pg.root_connection_string).expect("root connection string is a valid URL");
303        assert_eq!(root.path(), "/postgres");
304        assert_eq!(root.username(), "loco");
305        assert_eq!(root.password(), Some("pass"));
306        assert_eq!(root.host_str(), Some("loco-db.host"));
307        assert_eq!(root.port(), Some(5432));
308
309        let test_conn =
310            Url::parse(&pg.connection_string).expect("test connection string is a valid URL");
311        assert_eq!(test_conn.path(), format!("/{}", pg.schema_name));
312        assert_eq!(test_conn.username(), "loco");
313        assert_eq!(test_conn.password(), Some("pass"));
314        assert_eq!(test_conn.host_str(), Some("loco-db.host"));
315        assert_eq!(test_conn.port(), Some(5432));
316    }
317}