add mock database
This commit is contained in:
parent
d453eaf4ae
commit
535eb3540b
|
@ -7,5 +7,5 @@ edition = "2021"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
once_cell = "1.17.1"
|
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"
|
thiserror = "1.0.40"
|
||||||
|
|
|
@ -1,11 +1,13 @@
|
||||||
pub mod error;
|
pub mod error;
|
||||||
|
|
||||||
use once_cell::sync::OnceCell;
|
use once_cell::sync::{Lazy, OnceCell};
|
||||||
use sea_orm::{Database, DatabaseConnection};
|
use sea_orm::{Database, DatabaseBackend, DatabaseConnection, MockDatabase};
|
||||||
|
|
||||||
use crate::error::Error;
|
use crate::error::Error;
|
||||||
|
|
||||||
static DB_CONN: OnceCell<DatabaseConnection> = OnceCell::new();
|
static DB_CONN: OnceCell<DatabaseConnection> = OnceCell::new();
|
||||||
|
static DB_MOCK: Lazy<DatabaseConnection> =
|
||||||
|
Lazy::new(|| MockDatabase::new(DatabaseBackend::Postgres).into_connection());
|
||||||
|
|
||||||
pub async fn init_database(connection_uri: impl Into<String>) -> Result<(), Error> {
|
pub async fn init_database(connection_uri: impl Into<String>) -> Result<(), Error> {
|
||||||
let conn = Database::connect(connection_uri.into()).await?;
|
let conn = Database::connect(connection_uri.into()).await?;
|
||||||
|
@ -14,5 +16,19 @@ pub async fn init_database(connection_uri: impl Into<String>) -> Result<(), Erro
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_database() -> Result<&'static DatabaseConnection, Error> {
|
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());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue