From 7eee16961eef0e81c7e81c067086a4254f3f4b38 Mon Sep 17 00:00:00 2001 From: projectmoon Date: Wed, 19 May 2021 21:16:39 +0000 Subject: [PATCH] Add tests for dbstate. --- src/db/sqlite/state.rs | 63 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/src/db/sqlite/state.rs b/src/db/sqlite/state.rs index 2830df4..0d831cb 100644 --- a/src/db/sqlite/state.rs +++ b/src/db/sqlite/state.rs @@ -13,6 +13,13 @@ impl DbState for Database { } async fn set_device_id(&self, device_id: &str) -> Result<(), DataError> { + // This will have to be updated if we ever add another column + // to this table! + sqlx::query("DELETE FROM bot_state") + .execute(&self.conn) + .await + .ok(); + sqlx::query( r#"INSERT INTO bot_state (device_id) @@ -25,3 +32,59 @@ impl DbState for Database { Ok(()) } } + +#[cfg(test)] +mod tests { + use super::super::DbState; + use super::*; + + async fn create_db() -> Database { + let db_path = tempfile::NamedTempFile::new_in(".").unwrap(); + crate::db::sqlite::migrator::migrate(db_path.path().to_str().unwrap()) + .await + .unwrap(); + + Database::new(db_path.path().to_str().unwrap()) + .await + .unwrap() + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 1)] + async fn set_and_get_device_id() { + let db = create_db().await; + + db.set_device_id("device_id") + .await + .expect("Could not set device ID"); + + let device_id = db.get_device_id().await.expect("Could not get device ID"); + + assert!(device_id.is_some()); + assert_eq!(device_id.unwrap(), "device_id"); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 1)] + async fn no_device_id_set_returns_none() { + let db = create_db().await; + let device_id = db.get_device_id().await.expect("Could not get device ID"); + assert!(device_id.is_none()); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 1)] + async fn can_update_device_id() { + let db = create_db().await; + + db.set_device_id("device_id") + .await + .expect("Could not set device ID"); + + db.set_device_id("device_id2") + .await + .expect("Could not set device ID"); + + let device_id = db.get_device_id().await.expect("Could not get device ID"); + + assert!(device_id.is_some()); + assert_eq!(device_id.unwrap(), "device_id2"); + } +}