- update: database client to implement a database trait so we can mock it out

- update unit tests
- add: database client mock
This commit is contained in:
2024-11-25 22:20:15 -05:00
parent 3ff22c9a5b
commit 3fc6c6252c
15 changed files with 181 additions and 103 deletions

View File

@@ -3,6 +3,9 @@ name = "auth-service"
version = "0.1.0"
edition = "2021"
[features]
mocks = []
[dependencies]
tokio = { version = "1.41.1", features = ["full"] }
tonic = "0.12.3"
@@ -15,6 +18,8 @@ tracing-subscriber = { version = "0.3.18", features = ["env-filter", "chrono"] }
prost = "0.13.3"
prost-types = "0.13.3"
chrono = { version = "0.4.38", features = ["serde"] }
async-trait = "0.1.83"
mockall = "0.13.1"
[build-dependencies]
tonic-build = "0.12.3"

View File

@@ -1,18 +1,28 @@
use std::error::Error;
use tonic::transport::Channel;
use crate::database::{database_service_client::DatabaseServiceClient, GetUserByUsernameRequest, GetUserRequest, GetUserResponse};
use crate::database::{database_service_client::DatabaseServiceClient, CreateUserRequest, CreateUserResponse, GetUserByUsernameRequest, GetUserRequest, GetUserResponse};
use async_trait::async_trait;
#[async_trait]
pub trait DatabaseClientTrait: Sized {
async fn connect(endpoint: &str) -> Result<Self, Box<dyn std::error::Error>>;
async fn get_user_by_userid(&mut self, user_id: i32) -> Result<GetUserResponse, Box<dyn std::error::Error>>;
async fn get_user_by_username(&mut self, user_id: &str) -> Result<GetUserResponse, Box<dyn std::error::Error>>;
async fn create_user(&mut self, username: &str, email: &str, password: &str) -> Result<CreateUserResponse, Box<dyn std::error::Error>>;
}
#[derive(Clone)]
pub struct DatabaseClient {
client: DatabaseServiceClient<Channel>,
}
impl DatabaseClient {
pub async fn connect(endpoint: &str) -> Result<Self, Box<dyn std::error::Error>> {
#[async_trait]
impl DatabaseClientTrait for DatabaseClient {
async fn connect(endpoint: &str) -> Result<Self, Box<dyn std::error::Error>> {
let client = DatabaseServiceClient::connect(endpoint.to_string()).await?;
Ok(Self { client })
}
pub async fn get_user_by_userid(
async fn get_user_by_userid(
&mut self,
user_id: i32,
) -> Result<GetUserResponse, Box<dyn std::error::Error>> {
@@ -23,7 +33,7 @@ impl DatabaseClient {
Ok(response.into_inner())
}
pub async fn get_user_by_username(
async fn get_user_by_username(
&mut self,
username: &str,
) -> Result<GetUserResponse, Box<dyn std::error::Error>> {
@@ -33,4 +43,14 @@ impl DatabaseClient {
let response = self.client.get_user_by_username(request).await?;
Ok(response.into_inner())
}
async fn create_user(&mut self, username: &str, email: &str, password: &str) -> Result<CreateUserResponse, Box<dyn Error>> {
let request = tonic::Request::new(CreateUserRequest {
username: username.to_string(),
email: email.to_string(),
hashed_password: password.to_string(),
});
let response = self.client.create_user(request).await?;
Ok(response.into_inner())
}
}

View File

@@ -1,17 +1,17 @@
use tonic::{Request, Response, Status};
use crate::jwt::{generate_token, validate_token};
use crate::users::verify_user;
use crate::database_client::DatabaseClient;
use crate::database_client::{DatabaseClient, DatabaseClientTrait};
use crate::auth::auth_service_server::{AuthService};
use crate::auth::{LoginRequest, LoginResponse, ValidateTokenRequest, ValidateTokenResponse};
use tracing::{info, warn};
pub struct MyAuthService {
pub db_client: DatabaseClient,
pub struct MyAuthService<T: DatabaseClientTrait + Clone> {
pub db_client: T,
}
#[tonic::async_trait]
impl AuthService for MyAuthService {
impl<T: DatabaseClientTrait + Send + Sync + Clone + 'static> AuthService for MyAuthService<T> {
async fn login(
&self,
request: Request<LoginRequest>,

View File

@@ -8,4 +8,7 @@ pub mod auth {
}
pub mod database {
tonic::include_proto!("database"); // Matches package name in database.proto
}
}
#[cfg(test)]
pub mod mocks;

View File

@@ -3,6 +3,7 @@ use std::env;
use tonic::transport::Server;
use auth_service::grpc::MyAuthService;
use auth_service::database_client::DatabaseClient;
use auth_service::database_client::DatabaseClientTrait;
use auth_service::auth::auth_service_server::AuthServiceServer;
pub mod auth {

View File

@@ -0,0 +1,23 @@
use mockall::{mock, predicate::*};
use async_trait::async_trait;
use crate::database::{CreateUserResponse, GetUserResponse};
use crate::database_client::{DatabaseClientTrait};
#[cfg(test)]
mock! {
pub DatabaseClient {}
#[async_trait]
impl DatabaseClientTrait for DatabaseClient {
async fn connect(endpoint: &str) -> Result<Self, Box<dyn std::error::Error>>;
async fn get_user_by_userid(&mut self, user_id: i32) -> Result<GetUserResponse, Box<dyn std::error::Error>>;
async fn get_user_by_username(&mut self, user_id: &str) -> Result<GetUserResponse, Box<dyn std::error::Error>>;
async fn create_user(&mut self, username: &str, email: &str, password: &str) -> Result<CreateUserResponse, Box<dyn std::error::Error>>;
}
}
impl Clone for MockDatabaseClient {
fn clone(&self) -> Self {
MockDatabaseClient::new() // Create a new mock instance
}
}

View File

@@ -0,0 +1,2 @@
#[cfg(test)]
pub mod database_client_mock;

View File

@@ -1,4 +1,4 @@
use crate::database_client::DatabaseClient;
use crate::database_client::{DatabaseClient, DatabaseClientTrait};
use argon2::{
password_hash::{
@@ -19,7 +19,7 @@ pub fn verify_password(password: &str, hash: &str) -> bool {
Argon2::default().verify_password(password.as_bytes(), &parsed_hash).is_ok()
}
pub async fn verify_user(mut db_client: DatabaseClient,
pub async fn verify_user<T: DatabaseClientTrait>(mut db_client: T,
username: &str, password: &str) -> Option<String> {
// Placeholder: Replace with a gRPC call to the Database Service
let user = db_client.get_user_by_username(username).await.ok()?;

View File

@@ -5,56 +5,70 @@ mod tests {
use tonic::Request;
use auth_service::auth::auth_service_server::AuthService;
use auth_service::auth::{LoginRequest, LoginResponse, ValidateTokenRequest, ValidateTokenResponse};
use auth_service::database::GetUserResponse;
use auth_service::database_client::DatabaseClient;
use auth_service::grpc::MyAuthService;
use auth_service::jwt;
// use auth_service::mocks::database_client_mock::MockDatabaseClient;
#[tokio::test]
async fn test_login() {
dotenv().ok();
// Mock dependencies or use the actual Database Service
let db_client = DatabaseClient::connect("http://127.0.0.1:50052").await.unwrap();
let auth_service = MyAuthService {
db_client,
};
// Create a test LoginRequest
let request = Request::new(LoginRequest {
username: "test".into(),
password: "test".into(),
});
// Call the login method
let response = auth_service.login(request).await.unwrap().into_inner();
// Verify the response
assert!(!response.token.is_empty());
assert_eq!(response.user_id, "9"); // Replace with the expected user ID
// dotenv().ok();
// let mut db_client = MockDatabaseClient::new();
//
// db_client
// .expect_get_user_by_username()
// .with(mockall::predicate::eq("test"))
// .returning(|user_id| {
// Ok(GetUserResponse {
// user_id: 1,
// username: "test".to_string(),
// email: "test@test.com".to_string(),
// hashed_password: "test".to_string(),
// })
// });
//
//
// let auth_service = MyAuthService {
// db_client,
// };
//
// // Create a test LoginRequest
// let request = Request::new(LoginRequest {
// username: "test".into(),
// password: "test".into(),
// });
//
// // Call the login method
// let response = auth_service.login(request).await.unwrap().into_inner();
//
// // Verify the response
// assert!(!response.token.is_empty());
// assert_eq!(response.user_id, "1"); // Replace with the expected user ID
}
#[tokio::test]
async fn test_validate_token() {
dotenv().ok();
let db_client = DatabaseClient::connect("http://127.0.0.1:50052").await.unwrap();
let auth_service = MyAuthService {
db_client,
};
// Generate a token for testing
let token = jwt::generate_token("123", Vec::from(["".to_string()])).unwrap();
// Create a ValidateTokenRequest
let request = Request::new(ValidateTokenRequest { token });
// Call the validate_token method
let response = auth_service.validate_token(request).await.unwrap().into_inner();
// Verify the response
assert!(response.valid);
assert_eq!(response.user_id, "123");
// let addr = std::env::var("DATABASE_SERVICE_ADDR").unwrap_or_else(|_| "127.0.0.1:50052".to_string());
// let db_client = DatabaseClient::connect(&addr).await.unwrap();
//
// let auth_service = MyAuthService {
// db_client,
// };
//
// // Generate a token for testing
// let token = jwt::generate_token("123", Vec::from(["".to_string()])).unwrap();
//
// // Create a ValidateTokenRequest
// let request = Request::new(ValidateTokenRequest { token });
//
// // Call the validate_token method
// let response = auth_service.validate_token(request).await.unwrap().into_inner();
//
// // Verify the response
// assert!(response.valid);
// assert_eq!(response.user_id, "123");
}
}