use mongodb::{bson::oid::ObjectId, options::DropDatabaseOptions, Client, Collection, Database};
use serde::{Deserialize, Serialize};
use std::future::Future;
pub mod assert_document;
pub mod assert_model;
pub mod test_error;
pub struct TestDB {
pub id: String,
pub db: Database,
}
impl TestDB {
pub fn new(client: &Client) -> Self {
let id = ObjectId::new().to_string();
let db = client.database(&id);
Self { id, db }
}
pub async fn drop(&self, options: Option<DropDatabaseOptions>) {
self.db
.drop()
.with_options(options)
.await
.unwrap_or_else(|_| {
panic!(
"Could not drop TestDB with ID: {}, please manually drop this db to clear the space.",
self.id
)
});
}
pub fn collection<D>(&self, name: &str) -> Collection<D>
where
D: Serialize + for<'a> Deserialize<'a> + Send + Sync + Unpin,
{
self.db.collection(name)
}
pub async fn run_test<T, Fut>(
self,
test: T,
drop_options: Option<DropDatabaseOptions>,
) -> Result<(), Box<dyn std::error::Error>>
where
T: FnOnce() -> Fut,
Fut: Future<Output = Result<(), Box<dyn std::error::Error>>>,
{
let result = test().await;
self.drop(drop_options).await;
result
}
}