Add tests for dbstate.

This commit is contained in:
projectmoon 2021-05-19 21:16:39 +00:00
parent 43d8f9574f
commit 7eee16961e
1 changed files with 63 additions and 0 deletions

View File

@ -13,6 +13,13 @@ impl DbState for Database {
} }
async fn set_device_id(&self, device_id: &str) -> Result<(), DataError> { 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( sqlx::query(
r#"INSERT INTO bot_state r#"INSERT INTO bot_state
(device_id) (device_id)
@ -25,3 +32,59 @@ impl DbState for Database {
Ok(()) 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");
}
}