From 535eb3540b32e767d9fc4a8076ca9b120e971f0a Mon Sep 17 00:00:00 2001 From: Namekuji Date: Thu, 25 May 2023 09:42:59 -0400 Subject: [PATCH] add mock database --- .../native-utils/crates/database/Cargo.toml | 2 +- .../native-utils/crates/database/src/lib.rs | 22 ++++++++++++++++--- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/packages/backend/native-utils/crates/database/Cargo.toml b/packages/backend/native-utils/crates/database/Cargo.toml index b88f9b324..8498f52f2 100644 --- a/packages/backend/native-utils/crates/database/Cargo.toml +++ b/packages/backend/native-utils/crates/database/Cargo.toml @@ -7,5 +7,5 @@ edition = "2021" [dependencies] once_cell = "1.17.1" -sea-orm = { version = "0.11.3", features = ["sqlx-postgres", "runtime-tokio-rustls"] } +sea-orm = { version = "0.11.3", features = ["sqlx-postgres", "runtime-tokio-rustls", "mock"] } thiserror = "1.0.40" diff --git a/packages/backend/native-utils/crates/database/src/lib.rs b/packages/backend/native-utils/crates/database/src/lib.rs index 3c9db912b..e92d6bcfc 100644 --- a/packages/backend/native-utils/crates/database/src/lib.rs +++ b/packages/backend/native-utils/crates/database/src/lib.rs @@ -1,11 +1,13 @@ pub mod error; -use once_cell::sync::OnceCell; -use sea_orm::{Database, DatabaseConnection}; +use once_cell::sync::{Lazy, OnceCell}; +use sea_orm::{Database, DatabaseBackend, DatabaseConnection, MockDatabase}; use crate::error::Error; static DB_CONN: OnceCell = OnceCell::new(); +static DB_MOCK: Lazy = + Lazy::new(|| MockDatabase::new(DatabaseBackend::Postgres).into_connection()); pub async fn init_database(connection_uri: impl Into) -> Result<(), Error> { let conn = Database::connect(connection_uri.into()).await?; @@ -14,5 +16,19 @@ pub async fn init_database(connection_uri: impl Into) -> Result<(), Erro } pub fn get_database() -> Result<&'static DatabaseConnection, Error> { - DB_CONN.get().ok_or(Error::Uninitialized) + if cfg!(test) { + Ok(&DB_MOCK) + } else { + DB_CONN.get().ok_or(Error::Uninitialized) + } +} + +#[cfg(test)] +mod tests { + use super::get_database; + + #[test] + fn can_get_mock_without_initialization() { + assert!(get_database().is_ok()); + } }