Skip to content

Commit fd8bd8c

Browse files
committed
test: add in memory database setup function for handler testing
1 parent e46cb01 commit fd8bd8c

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

mgmtd/src/db.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,26 @@ pub(crate) mod test {
5454
use super::*;
5555
use rusqlite::{Connection, Transaction};
5656

57+
pub(crate) async fn setup_with_test_data() -> Connections {
58+
let conns = Connections::new_in_memory();
59+
60+
conns
61+
.conn(|conn| {
62+
let tx = conn.transaction().unwrap();
63+
sqlite::migrate_schema(&tx, MIGRATIONS).unwrap();
64+
// Setup test data
65+
tx.execute_batch(include_str!("db/schema/test_data.sql"))
66+
.unwrap();
67+
tx.commit().unwrap();
68+
69+
Ok(())
70+
})
71+
.await
72+
.unwrap();
73+
74+
conns
75+
}
76+
5777
/// Sets ups a fresh database instance in memory and fills, with the test data set and provides
5878
/// a transaction handle.
5979
pub(crate) fn with_test_data(op: impl FnOnce(&Transaction)) {

sqlite/src/connection.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use rusqlite::config::DbConfig;
33
use rusqlite::{Connection, Transaction, TransactionBehavior};
44
use std::ops::Deref;
55
use std::path::{Path, PathBuf};
6+
use std::sync::atomic::{AtomicU64, Ordering};
67
use std::sync::{Arc, Mutex};
78
use std::time::Duration;
89

@@ -79,7 +80,12 @@ pub struct InnerConnections {
7980
db_file: PathBuf,
8081
}
8182

83+
/// Increased whenever new_in_memory is called. Makes sure that the test binary can run multiple
84+
/// tests in parallel with distinct in memory db instances (otherwise they would clash)
85+
static MEMORY_COUNTER: AtomicU64 = AtomicU64::new(0);
86+
8287
impl Connections {
88+
/// Create a new db connection pool using the given db file
8389
pub fn new(db_file: impl AsRef<Path>) -> Self {
8490
Self {
8591
inner: Arc::new(InnerConnections {
@@ -89,6 +95,18 @@ impl Connections {
8995
}
9096
}
9197

98+
/// Create a new db connection pool using an in memory db
99+
pub fn new_in_memory() -> Self {
100+
let count = MEMORY_COUNTER.fetch_add(1, Ordering::Relaxed);
101+
102+
Self {
103+
inner: Arc::new(InnerConnections {
104+
conns: Mutex::new(vec![]),
105+
db_file: format!("file:memdb{count}?mode=memory&cache=shared").into(),
106+
}),
107+
}
108+
}
109+
92110
/// Start a new write (immediate) transaction. If doing writes, it is important to use this
93111
/// instead of `.read()` because here the busy timeout / busy handler actually works as it is
94112
/// applied before the transaction starts.

0 commit comments

Comments
 (0)