Add comprehensive tests for mentor repository and authentication

- Implemented tests for creating, retrieving, updating, and deleting mentors in `mentor_repository_test.rs`.
- Added tests for user authentication, including successful login, invalid email formats, and inactive users in `auth_login_tests.rs`.
- Created a mock test environment setup in `mock_test.rs` to facilitate database operations during tests.
- Updated module structure to include new test files for mentors and authentication.
- Ensured cleanup of the database after tests to maintain isolation and prevent side effects.
This commit is contained in:
MythEclipse
2025-07-21 21:29:04 +07:00
parent e66f1f1634
commit 1a2e0c58b6
103 changed files with 7851 additions and 1509 deletions
+379
View File
@@ -0,0 +1,379 @@
#[cfg(test)]
mod auth_login_tests {
use crate::generate_unique_email;
use crate::hash_password;
use crate::mock_test::setup_all_test_environment;
use axum::http::StatusCode;
use imphnen_iam::{
v1::auth::{AuthLoginRequestDto, AuthService},
AppState, UsersRepository, UsersSchema,
};
use serde_json::Value; // Import the new setup function
async fn setup_test_environment() -> AppState {
setup_all_test_environment().await
}
async fn create_test_user_with_role(
state: &AppState,
email: &str,
password: &str,
role_name: &str,
is_active: bool,
) -> UsersSchema {
let role_repo = imphnen_iam::RolesRepository::new(state);
let role = match role_repo.query_role_by_name(role_name.to_string()).await {
Ok(role) => role,
Err(_) => {
let _ = role_repo
.query_create_role(imphnen_iam::RolesRequestCreateDto {
name: role_name.to_string(),
permissions: vec![],
})
.await
.unwrap();
role_repo
.query_role_by_name(role_name.to_string())
.await
.unwrap_or_else(|_| {
panic!("Failed to create {role_name} role");
})
}
};
let user = UsersSchema {
id: crate::make_thing("app_users", &uuid::Uuid::new_v4().to_string()),
email: email.to_string(),
fullname: "Test User".to_string(),
password: hash_password(password).unwrap(),
is_deleted: false,
avatar: None,
phone_number: "081234567890".to_string(),
is_active,
gender: None,
birthdate: None,
role: crate::make_thing("app_roles", &role.id),
mentor_id: None,
created_at: imphnen_utils::get_iso_date(),
updated_at: imphnen_utils::get_iso_date(),
};
let user_repo = UsersRepository::new(state);
user_repo
.query_create_user(user.clone())
.await
.expect("Failed to create test user");
user
}
#[tokio::test]
async fn test_successful_login_with_valid_credentials() {
let state = setup_test_environment().await;
let email = generate_unique_email("test_login_success");
let password = "TestPass123!";
create_test_user_with_role(&state, &email, password, "User", true).await;
let login_dto = AuthLoginRequestDto {
email: email.clone(),
password: password.to_string(),
};
let response = AuthService::mutation_login(login_dto, &state).await;
let (parts, body) = response.into_parts();
assert_eq!(parts.status, StatusCode::OK);
let body_bytes = axum::body::to_bytes(body, usize::MAX).await.unwrap();
let response_json: Value = serde_json::from_slice(&body_bytes).unwrap();
assert!(response_json.get("data").is_some());
assert!(response_json["data"].get("token").is_some());
assert!(response_json["data"]["token"].get("access_token").is_some());
assert!(response_json["data"]["token"]
.get("refresh_token")
.is_some());
assert!(response_json["data"].get("user").is_some());
assert_eq!(response_json["data"]["user"]["email"], email);
}
#[tokio::test]
async fn test_login_with_invalid_email_format() {
let state = setup_test_environment().await;
let login_dto = AuthLoginRequestDto {
email: "invalid-email".to_string(),
password: "TestPass123!".to_string(),
};
let response = AuthService::mutation_login(login_dto, &state).await;
let (parts, body) = response.into_parts();
assert_eq!(parts.status, StatusCode::BAD_REQUEST);
let body_bytes = axum::body::to_bytes(body, usize::MAX).await.unwrap();
let response_json: Value = serde_json::from_slice(&body_bytes).unwrap();
assert_eq!(response_json["message"], "Email not valid");
}
#[tokio::test]
async fn test_login_with_empty_email() {
let state = setup_test_environment().await;
let login_dto = AuthLoginRequestDto {
email: "".to_string(),
password: "TestPass123!".to_string(),
};
let response = AuthService::mutation_login(login_dto, &state).await;
let (parts, body) = response.into_parts();
assert_eq!(parts.status, StatusCode::BAD_REQUEST);
let body_bytes = axum::body::to_bytes(body, usize::MAX).await.unwrap();
let response_json: Value = serde_json::from_slice(&body_bytes).unwrap();
let message = response_json["message"].as_str().unwrap();
assert!(message.contains("Email cannot be empty"));
assert!(message.contains("Email not valid"));
}
#[tokio::test]
async fn test_login_with_empty_password() {
let state = setup_test_environment().await;
let login_dto = AuthLoginRequestDto {
email: generate_unique_email("test_empty_pass"),
password: "".to_string(),
};
let response = AuthService::mutation_login(login_dto, &state).await;
let (parts, body) = response.into_parts();
assert_eq!(parts.status, StatusCode::BAD_REQUEST);
let body_bytes = axum::body::to_bytes(body, usize::MAX).await.unwrap();
let response_json: Value = serde_json::from_slice(&body_bytes).unwrap();
assert_eq!(response_json["message"], "Password cannot be empty");
}
#[tokio::test]
async fn test_login_with_wrong_password() {
let state = setup_test_environment().await;
let email = generate_unique_email("test_wrong_pass");
let correct_password = "TestPass123!";
create_test_user_with_role(&state, &email, correct_password, "User", true).await;
let login_dto = AuthLoginRequestDto {
email: email.clone(),
password: "WrongPassword123!".to_string(),
};
let response = AuthService::mutation_login(login_dto, &state).await;
let (parts, body) = response.into_parts();
assert_eq!(parts.status, StatusCode::BAD_REQUEST);
let body_bytes = axum::body::to_bytes(body, usize::MAX).await.unwrap();
let response_json: Value = serde_json::from_slice(&body_bytes).unwrap();
assert_eq!(response_json["message"], "Email or password not correct");
}
#[tokio::test]
async fn test_login_with_nonexistent_user() {
let state = setup_test_environment().await;
let login_dto = AuthLoginRequestDto {
email: generate_unique_email("nonexistent"),
password: "TestPass123!".to_string(),
};
let response = AuthService::mutation_login(login_dto, &state).await;
let (parts, body) = response.into_parts();
assert_eq!(parts.status, StatusCode::UNAUTHORIZED);
let body_bytes = axum::body::to_bytes(body, usize::MAX).await.unwrap();
let response_json: Value = serde_json::from_slice(&body_bytes).unwrap();
assert!(response_json["message"]
.to_string()
.contains("User not found"));
}
#[tokio::test]
async fn test_login_with_inactive_user() {
let state = setup_test_environment().await;
let email = generate_unique_email("test_inactive");
let password = "TestPass123!";
create_test_user_with_role(&state, &email, password, "User", false).await;
let login_dto = AuthLoginRequestDto {
email: email.clone(),
password: password.to_string(),
};
let response = AuthService::mutation_login(login_dto, &state).await;
let (parts, body) = response.into_parts();
assert_eq!(parts.status, StatusCode::BAD_REQUEST);
let body_bytes = axum::body::to_bytes(body, usize::MAX).await.unwrap();
let response_json: Value = serde_json::from_slice(&body_bytes).unwrap();
assert_eq!(
response_json["message"],
"Account not active, please verify your email"
);
}
#[tokio::test]
async fn test_successful_mentor_login() {
let state = setup_test_environment().await;
let email = generate_unique_email("test_mentor_login");
let password = "TestPass123!";
create_test_user_with_role(&state, &email, password, "Mentor", true).await;
let login_dto = AuthLoginRequestDto {
email: email.clone(),
password: password.to_string(),
};
let response = AuthService::mutation_mentor_login(login_dto, &state).await;
let (parts, body) = response.into_parts();
assert_eq!(parts.status, StatusCode::OK);
let body_bytes = axum::body::to_bytes(body, usize::MAX).await.unwrap();
let response_json: Value = serde_json::from_slice(&body_bytes).unwrap();
assert!(response_json.get("data").is_some());
assert_eq!(response_json["data"]["user"]["role"]["name"], "Mentor");
}
#[tokio::test]
async fn test_mentor_login_with_non_mentor_user() {
let state = setup_test_environment().await;
let email = generate_unique_email("test_user_not_mentor");
let password = "TestPass123!";
create_test_user_with_role(&state, &email, password, "User", true).await;
let login_dto = AuthLoginRequestDto {
email: email.clone(),
password: password.to_string(),
};
let response = AuthService::mutation_mentor_login(login_dto, &state).await;
let (parts, body) = response.into_parts();
assert_eq!(parts.status, StatusCode::FORBIDDEN);
let body_bytes = axum::body::to_bytes(body, usize::MAX).await.unwrap();
let response_json: Value = serde_json::from_slice(&body_bytes).unwrap();
assert_eq!(
response_json["message"],
"User does not have mentor privileges"
);
}
#[tokio::test]
async fn test_mentor_login_with_inactive_mentor() {
let state = setup_test_environment().await;
let email = generate_unique_email("test_inactive_mentor");
let password = "TestPass123!";
create_test_user_with_role(&state, &email, password, "Mentor", false).await;
let login_dto = AuthLoginRequestDto {
email: email.clone(),
password: password.to_string(),
};
let response = AuthService::mutation_mentor_login(login_dto, &state).await;
let (parts, body) = response.into_parts();
assert_eq!(parts.status, StatusCode::BAD_REQUEST);
let body_bytes = axum::body::to_bytes(body, usize::MAX).await.unwrap();
let response_json: Value = serde_json::from_slice(&body_bytes).unwrap();
assert_eq!(
response_json["message"],
"Account not active, please verify your email"
);
}
#[tokio::test]
async fn test_login_creates_user_cache() {
let state = setup_test_environment().await;
let email = generate_unique_email("test_cache");
let password = "TestPass123!";
create_test_user_with_role(&state, &email, password, "User", true).await;
let login_dto = AuthLoginRequestDto {
email: email.clone(),
password: password.to_string(),
};
let response = AuthService::mutation_login(login_dto, &state).await;
let (parts, _) = response.into_parts();
assert_eq!(parts.status, StatusCode::OK);
// Verify user was cached
let auth_repo = imphnen_iam::AuthRepository::new(&state);
let cached_user = auth_repo.query_get_stored_user(email.clone()).await;
assert!(cached_user.is_ok());
assert_eq!(cached_user.unwrap().email, email);
}
#[tokio::test]
async fn test_login_with_special_characters_in_email() {
let state = setup_test_environment().await;
let email = generate_unique_email("test+special");
let password = "TestPass123!";
create_test_user_with_role(&state, &email, password, "User", true).await;
let login_dto = AuthLoginRequestDto {
email: email.clone(),
password: password.to_string(),
};
let response = AuthService::mutation_login(login_dto, &state).await;
let (parts, _) = response.into_parts();
assert_eq!(parts.status, StatusCode::OK);
}
#[tokio::test]
async fn test_login_with_case_sensitive_email() {
let state = setup_test_environment().await;
let email = generate_unique_email("test_case");
let password = "TestPass123!";
create_test_user_with_role(&state, &email, password, "User", true).await;
let login_dto = AuthLoginRequestDto {
email: email.to_uppercase(),
password: password.to_string(),
};
let response = AuthService::mutation_login(login_dto, &state).await;
let (parts, body) = response.into_parts();
// Email should be case-sensitive
assert_eq!(parts.status, StatusCode::UNAUTHORIZED);
let body_bytes = axum::body::to_bytes(body, usize::MAX).await.unwrap();
let response_json: Value = serde_json::from_slice(&body_bytes).unwrap();
assert!(response_json["message"]
.to_string()
.contains("User not found"));
}
}
+93 -53
View File
@@ -1,9 +1,16 @@
#[cfg(test)]
mod auth_repository_test {
use crate::{
AuthOtpSchema, AuthRepository, ResourceEnum, UsersRepository, UsersSchema,
create_mock_app_state, generate_unique_email, get_iso_date, get_role_id,
generate_unique_email,
get_iso_date,
get_role_id,
make_thing,
setup_all_test_environment, // Import the new setup function
AuthOtpSchema,
AuthRepository,
ResourceEnum,
UsersRepository,
UsersSchema,
};
use chrono::{Duration, Utc};
use imphnen_iam::{AppState, RolesDetailQueryDto, UsersDetailQueryDto};
@@ -22,6 +29,7 @@ mod auth_repository_test {
gender: None,
birthdate: None,
role: make_thing("app_roles", &get_role_id(state).await),
mentor_id: None,
created_at: get_iso_date(),
updated_at: get_iso_date(),
}
@@ -29,27 +37,35 @@ mod auth_repository_test {
#[tokio::test]
async fn test_store_and_get_user() {
let app_state = create_mock_app_state().await;
let app_state = setup_all_test_environment().await; // Use the new setup function
let repo = AuthRepository::new(&app_state);
let email = generate_unique_email("forgot");
let user = create_mock_user(&app_state, &email).await;
let mut user = create_mock_user(&app_state, &email).await;
user.role = make_thing("app_roles", &get_role_id(&app_state).await);
let user_repo = UsersRepository::new(&app_state);
let create_user = user_repo.query_create_user(user.clone()).await;
assert!(create_user.is_ok());
let user_data = user_repo
.query_user_by_email(email.to_string())
.await
.unwrap();
let user_data = user_repo.query_user_by_email(email).await;
assert!(
user_data.is_ok(),
"Failed to get user by email: {:?}",
user_data.err()
);
let user_data = user_data.unwrap();
let store = repo.query_store_user(user_data.clone()).await;
assert!(store.is_ok());
assert!(store.is_ok(), "Failed to store user: {:?}", store.err());
let fetched = repo.query_get_stored_user(user.email.clone()).await;
assert!(fetched.is_ok());
assert!(
fetched.is_ok(),
"Failed to fetch stored user: {:?}",
fetched.err()
);
assert_eq!(fetched.unwrap().email, user.email);
}
#[tokio::test]
async fn test_delete_stored_user() {
let state = create_mock_app_state().await;
let state = setup_all_test_environment().await; // Use the new setup function
let auth_repo = AuthRepository::new(&state);
let email = "delete_me@example.com".to_string();
let mock_user = UsersDetailQueryDto {
@@ -71,15 +87,20 @@ mod auth_repository_test {
},
is_deleted: false,
password: "".into(),
mentor_id: None,
created_at: get_iso_date(),
updated_at: get_iso_date(),
};
let _: Option<UsersDetailQueryDto> = state
let created: Result<Option<UsersDetailQueryDto>, surrealdb::Error> = state
.surrealdb_mem
.create((ResourceEnum::UsersCache.to_string(), email.clone()))
.content(mock_user)
.await
.unwrap();
.await;
assert!(
created.is_ok(),
"Failed to create mock user: {:?}",
created.err()
);
let result = auth_repo.query_delete_stored_user(email.clone()).await;
assert!(
result.is_ok(),
@@ -91,101 +112,120 @@ mod auth_repository_test {
#[tokio::test]
async fn test_store_and_get_otp() {
let app_state = create_mock_app_state().await;
let app_state = setup_all_test_environment().await; // Use the new setup function
let repo = AuthRepository::new(&app_state);
let email = "otp_user@example.com".to_string();
let otp = 123456;
let stored = repo.query_store_otp(email.clone(), otp).await;
assert!(stored.is_ok());
assert!(stored.is_ok(), "Failed to store OTP: {:?}", stored.err());
let fetched = repo.query_get_stored_otp(email.clone()).await;
assert!(fetched.is_ok());
assert!(fetched.is_ok(), "Failed to fetch OTP: {:?}", fetched.err());
assert_eq!(fetched.unwrap(), otp);
}
#[tokio::test]
async fn test_delete_stored_otp() {
let app_state = create_mock_app_state().await;
let app_state = setup_all_test_environment().await; // Use the new setup function
let repo = AuthRepository::new(&app_state);
let email = "otp_del@example.com".to_string();
let otp = 654321;
repo.query_store_otp(email.clone(), otp).await.unwrap();
let store_res = repo.query_store_otp(email.clone(), otp).await;
assert!(
store_res.is_ok(),
"Failed to store OTP: {:?}",
store_res.err()
);
let deleted = repo.query_delete_stored_otp(email.clone()).await;
assert!(deleted.is_ok());
assert!(deleted.is_ok(), "Failed to delete OTP: {:?}", deleted.err());
let fetched = repo.query_get_stored_otp(email.clone()).await;
assert!(fetched.is_err());
assert!(
fetched.is_err(),
"OTP should be deleted, but got: {fetched:?}"
);
}
#[tokio::test]
async fn test_expired_otp() {
let app_state = create_mock_app_state().await;
let app_state = setup_all_test_environment().await; // Use the new setup function
let repo = AuthRepository::new(&app_state);
let email = "expired_otp@example.com".to_string();
let otp = 789012;
let table = ResourceEnum::OtpCache.to_string();
let expires_at = Utc::now() - Duration::seconds(1);
let _: Option<AuthOtpSchema> = repo
let created: Result<Option<AuthOtpSchema>, surrealdb::Error> = repo
.state
.surrealdb_mem
.create((table.clone(), email.as_str()))
.content(AuthOtpSchema { otp, expires_at })
.await
.unwrap();
.await;
assert!(
created.is_ok(),
"Failed to create expired OTP: {:?}",
created.err()
);
let result = repo.query_get_stored_otp(email.clone()).await;
assert!(result.is_err());
assert!(
result.is_err(),
"Expired OTP should not be retrievable, got: {result:?}"
);
if let Some(err) = result.err() {
assert!(
err.to_string().contains("OTP expired"),
"Expected 'OTP expired' error, got: {err}"
);
}
}
#[tokio::test]
async fn test_get_non_existent_stored_user_should_fail() {
let app_state = create_mock_app_state().await;
let app_state = setup_all_test_environment().await; // Use the new setup function
let repo = AuthRepository::new(&app_state);
let result = repo
.query_get_stored_user("not_found@example.com".into())
.await;
assert!(result.is_err());
if let Some(err) = result.err() {
assert!(
err.to_string().contains("No stored user data found"),
"Expected 'No stored user data found' error, got: {err}"
);
}
}
#[tokio::test]
async fn test_delete_non_existent_user_should_fail() {
let app_state = create_mock_app_state().await;
let app_state = setup_all_test_environment().await; // Use the new setup function
let repo = AuthRepository::new(&app_state);
let result = repo
.query_delete_stored_user("ghost@example.com".into())
.await;
assert!(result.is_err());
}
#[tokio::test]
async fn test_get_expired_otp_should_fail() {
use chrono::Duration;
let app_state = create_mock_app_state().await;
let repo = AuthRepository::new(&app_state);
let email = "expired_otp@example.com";
let expired_time = chrono::Utc::now() - Duration::seconds(10);
let otp = 123456;
let _: Option<AuthOtpSchema> = repo
.state
.surrealdb_mem
.create((ResourceEnum::OtpCache.to_string(), email))
.content(AuthOtpSchema {
otp,
expires_at: expired_time,
})
.await
.unwrap();
let result = repo.query_get_stored_otp(email.into()).await;
assert!(result.is_err());
if let Some(err) = result.err() {
assert!(
err.to_string().contains("Failed delete stored user"),
"Expected 'Failed delete stored user' error, got: {err}"
);
}
}
#[tokio::test]
async fn test_store_and_get_valid_otp() {
let app_state = create_mock_app_state().await;
let app_state = setup_all_test_environment().await; // Use the new setup function
let repo = AuthRepository::new(&app_state);
let email = "valid_otp@example.com";
let otp = 654321;
let store_result = repo.query_store_otp(email.into(), otp).await;
assert!(store_result.is_ok());
assert!(
store_result.is_ok(),
"Failed to store valid OTP: {:?}",
store_result.err()
);
let get_result = repo.query_get_stored_otp(email.into()).await;
assert!(
get_result.is_ok(),
"Failed to get valid OTP: {:?}",
get_result.err()
);
assert_eq!(get_result.unwrap(), otp);
}
}
+2
View File
@@ -1,2 +1,4 @@
#[cfg(test)]
pub mod auth_login_tests;
#[cfg(test)]
pub mod auth_repository_test;