Skip to content

Commit

Permalink
add unit test for redis connection
Browse files Browse the repository at this point in the history
  • Loading branch information
tthogho1 committed Oct 15, 2024
1 parent e6690ef commit 3fcbe3c
Show file tree
Hide file tree
Showing 3 changed files with 137 additions and 2 deletions.
77 changes: 77 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,5 @@ bb8 = "0.8"
bb8-redis = "0.17.0"
serde = { version = "1.0.210", features = ["derive"] }
serde_json = "1.0.128"
once_cell = "1.20.2"
once_cell = "1.20.2"
mockall = "0.13.0"
59 changes: 58 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,4 +100,61 @@ pub async fn create_pool(redis_url: &str) -> Result<bb8::Pool<RedisConnectionMan
pub async fn get_connection(pool: &bb8::Pool<RedisConnectionManager>) -> Result<bb8::PooledConnection<'_, RedisConnectionManager>, Box<dyn std::error::Error>> {
let conn = pool.get().await?;
Ok(conn)
}
}

#[cfg(test)]
mod tests {
use super::*;
use mockall::predicate::*;
use mockall::mock;
use dotenv::dotenv;
use std::env;

mock! {
RedisConnectionManager {}
impl Clone for RedisConnectionManager {
fn clone(&self) -> Self;
}
}

mock! {
Pool<RedisConnectionManager> {}
}

#[tokio::test]
async fn test_create_pool_success() {
dotenv().ok();
let redis_url = env::var("REDIS_URL").expect("REDIS_URL must be set in .env file");

let result = create_pool(&redis_url).await;

// 結果を検証
assert!(result.is_ok());

let pool = result.unwrap();
let result_con = get_connection(&pool).await;

assert!(result_con.is_ok());

let _con = result_con.unwrap();

let state = pool.state();
let count = state.connections;

// 結果を検証
assert_eq!(count, 1);
}

#[tokio::test]
async fn test_create_pool_failure() {
let redis_url = "invalid_url";

// テスト実行
let result = create_pool(redis_url).await;

assert!(result.is_err());
}
}



0 comments on commit 3fcbe3c

Please sign in to comment.