Skip to content

Commit b3da940

Browse files
authored
fix: test database (#337)
* add handling of TmpDir to prevent premature deletion of temporary database * refactor test function
1 parent 20839ca commit b3da940

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

crates/database/db/src/db.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,10 @@ pub struct Database {
3838
write_lock: Arc<Mutex<()>>,
3939
/// The database metrics.
4040
metrics: DatabaseMetrics,
41+
/// The temporary directory used for testing. We keep it here to ensure it lives as long as the
42+
/// database instance as the temp directory is deleted when [`tempfile::TempDir`] is dropped.
43+
#[cfg(feature = "test-utils")]
44+
tmp_dir: Option<tempfile::TempDir>,
4145
}
4246

4347
impl Database {
@@ -80,8 +84,20 @@ impl Database {
8084
connection: SqlxSqliteConnector::from_sqlx_sqlite_pool(sqlx_pool),
8185
write_lock: Arc::new(Mutex::new(())),
8286
metrics: DatabaseMetrics::default(),
87+
#[cfg(feature = "test-utils")]
88+
tmp_dir: None,
8389
})
8490
}
91+
92+
/// Creates a new [`Database`] instance for testing purposes, using the provided temporary
93+
/// directory to store the database files.
94+
#[cfg(feature = "test-utils")]
95+
pub async fn test(dir: tempfile::TempDir) -> Result<Self, DatabaseError> {
96+
let path = dir.path().join("test.db");
97+
let mut db = Self::new(path.to_str().unwrap()).await?;
98+
db.tmp_dir = Some(dir);
99+
Ok(db)
100+
}
85101
}
86102

87103
#[async_trait::async_trait]
@@ -132,6 +148,8 @@ impl From<DatabaseConnection> for Database {
132148
connection,
133149
write_lock: Arc::new(Mutex::new(())),
134150
metrics: DatabaseMetrics::default(),
151+
#[cfg(feature = "test-utils")]
152+
tmp_dir: None,
135153
}
136154
}
137155
}

crates/database/db/src/test_utils.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,16 @@ use crate::DatabaseConnectionProvider;
44

55
use super::Database;
66
use scroll_migration::{Migrator, MigratorTrait, ScrollDevMigrationInfo};
7-
use tempfile::NamedTempFile;
87

98
/// Instantiates a new in-memory database and runs the migrations
109
/// to set up the schema.
1110
pub async fn setup_test_db() -> Database {
12-
let tmp = NamedTempFile::new().unwrap();
13-
let db = Database::new(tmp.path().to_str().unwrap()).await.unwrap();
11+
let dir = tempfile::Builder::new()
12+
.prefix("scroll-test-")
13+
.rand_bytes(8)
14+
.tempdir()
15+
.expect("failed to create temp dir");
16+
let db = Database::test(dir).await.unwrap();
1417
Migrator::<ScrollDevMigrationInfo>::up(db.get_connection(), None).await.unwrap();
1518
db
1619
}

0 commit comments

Comments
 (0)