From 935ea5555d8955da4c44aaf7578993a012fcb1d9 Mon Sep 17 00:00:00 2001 From: subcrip Date: Sat, 30 Mar 2024 15:30:14 +0800 Subject: [PATCH] fix(db): finish unit test for db::OAuthDatabase::psql_execute and db::OAuthDatabase::psql_query --- src/db.rs | 24 ++++++++++++++++++++---- src/main.rs | 9 +++------ 2 files changed, 23 insertions(+), 10 deletions(-) diff --git a/src/db.rs b/src/db.rs index 431f397..1afd276 100644 --- a/src/db.rs +++ b/src/db.rs @@ -2,6 +2,7 @@ use std::time::Duration; pub struct OAuthDatabase { client: tokio_postgres::Client, + handle: tokio::task::JoinHandle>, } impl OAuthDatabase { @@ -11,8 +12,8 @@ impl OAuthDatabase { } pub async fn new(client: tokio_postgres::Client, connection: tokio_postgres::Connection) -> Result { - let obj = Self { client }; - tokio::spawn(connection); + let handle = tokio::spawn(connection); + let obj = Self { client, handle }; Ok(obj) } @@ -23,6 +24,10 @@ impl OAuthDatabase { async fn psql_query(&mut self, query: &T, params: &[&(dyn tokio_postgres::types::ToSql + Sync)]) -> Result, tokio_postgres::Error> { self.client.query(query, params).await } + + pub fn disconnect(&mut self) { + self.handle.abort(); + } } #[cfg(test)] @@ -30,8 +35,8 @@ pub mod db_tests { use super::*; pub struct DBTestEntryType { - name: String, - age: i32, + pub name: String, + pub age: i32, } impl DBTestEntryType { @@ -55,8 +60,19 @@ pub mod db_tests { Ok(()) } + pub async fn read(&mut self) -> Result, tokio_postgres::Error> { + // TODO: + let v = self.d.psql_query("select * from rust_test", &[]).await?; + let mut res = Vec::new(); + for row in v { + res.push(DBTestEntryType::new(row.get("name"), row.get("age"))); + } + Ok(res) + } + pub async fn destroy(&mut self) -> Result<(), tokio_postgres::Error> { self.d.psql_execute("drop table rust_test", &[]).await?; + self.d.disconnect(); Ok(()) } } diff --git a/src/main.rs b/src/main.rs index af47973..88a89bd 100644 --- a/src/main.rs +++ b/src/main.rs @@ -25,15 +25,12 @@ async fn main() { } #[tokio::test] -async fn test_table_level_operations() { - use db::db_tests; - let _b = db_tests::DBTestComponents::new(db::OAuthDatabase::connect("localhost", 5432, "postgres", "configjson", "myoauth").await.unwrap()).await.unwrap(); -} - -#[tokio::test(flavor = "multi_thread")] async fn test_entry_level_operations() { use db::db_tests; let mut b = db_tests::DBTestComponents::new(db::OAuthDatabase::connect("localhost", 5432, "postgres", "configjson", "myoauth").await.unwrap()).await.unwrap(); assert!(matches!(b.create(db_tests::DBTestEntryType::new("subcrip".to_string(), 19)).await, Ok(()))); + let items = b.read().await.unwrap(); + assert_eq!(items[0].name, "subcrip"); + assert_eq!(items[0].age, 19); let _ = b.destroy().await; }