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
+29 -5
View File
@@ -1,13 +1,13 @@
use crate::{RolesDetailItemDto, RolesDetailQueryDto};
use lazy_static::lazy_static;
use regex::Regex;
use serde::{Deserialize, Serialize};
use surrealdb::sql::Thing;
use utoipa::ToSchema;
use validator::Validate;
lazy_static! {
static ref PASSWORD_REGEX: Regex = Regex::new(r"^[A-Za-z\d@$!%*?&]{8,}$").unwrap();
static ref PASSWORD_REGEX: regex::Regex =
regex::Regex::new(r"^[A-Za-z\d@$!%*?&]{8,}$").unwrap();
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
@@ -34,7 +34,7 @@ pub struct UsersCreateRequestDto {
message = "Password must have at least 8 characters"
))]
#[validate(regex(
path = "PASSWORD_REGEX",
path = "*PASSWORD_REGEX",
message = "Password must include uppercase, lowercase, number, and special character"
))]
pub password: String,
@@ -62,6 +62,7 @@ pub struct UsersUpdateRequestDto {
min = 8,
message = "Password must have at least 8 characters"
))]
pub password: String,
#[validate(length(min = 2, message = "Fullname at least have 2 character"))]
pub fullname: String,
#[validate(length(
@@ -103,7 +104,7 @@ impl UsersDetailItemDto {
email: dto.email.clone(),
avatar: dto.avatar.clone(),
phone_number: dto.phone_number.clone(),
is_active: dto.is_active.clone(),
is_active: dto.is_active,
gender: dto.gender.clone(),
birthdate: dto.birthdate.clone(),
created_at: dto.created_at.clone(),
@@ -169,18 +170,20 @@ pub struct UsersDetailQueryDto {
pub role: RolesDetailQueryDto,
pub created_at: String,
pub updated_at: String,
pub mentor_id: Option<Thing>,
}
impl UsersDetailQueryDto {
pub fn from(&self) -> Self {
Self {
id: self.id.clone(),
role: RolesDetailQueryDto::from(self.role.clone()),
role: self.role.clone(),
fullname: self.fullname.clone(),
email: self.email.clone(),
avatar: self.avatar.clone(),
phone_number: self.phone_number.clone(),
is_active: self.is_active,
mentor_id: self.mentor_id.clone(),
gender: self.gender.clone(),
is_deleted: self.is_deleted,
password: self.password.clone(),
@@ -190,3 +193,24 @@ impl UsersDetailQueryDto {
}
}
}
impl From<&UsersDetailItemDto> for UsersDetailQueryDto {
fn from(dto: &UsersDetailItemDto) -> Self {
Self {
id: crate::make_thing(&imphnen_libs::ResourceEnum::Users.to_string(), &dto.id),
fullname: dto.fullname.clone(),
email: dto.email.clone(),
avatar: dto.avatar.clone(),
phone_number: dto.phone_number.clone(),
is_active: dto.is_active,
is_deleted: false,
gender: dto.gender.clone(),
birthdate: dto.birthdate.clone(),
password: String::new(),
role: RolesDetailQueryDto::default(),
created_at: dto.created_at.clone(),
updated_at: dto.updated_at.clone(),
mentor_id: None,
}
}
}
+77 -9
View File
@@ -2,10 +2,16 @@ use super::{UsersDetailQueryDto, UsersListItemDto, UsersListQueryDto, UsersSchem
use crate::{
AppState, MetaRequestDto, ResourceEnum, ResponseListSuccessDto, get_id, make_thing,
};
use surrealdb::sql::Thing;
use anyhow::{Result, bail};
use imphnen_utils::{DetailQueryBuilder, QueryListBuilder};
use serde_json;
use std::time::Instant;
use surrealdb::{Surreal, engine::remote::ws::Client};
pub struct UsersRepository<'a> {
state: &'a AppState,
}
@@ -30,10 +36,12 @@ impl<'a> UsersRepository<'a> {
Self { state }
}
pub async fn query_user_list(
&self,
meta: MetaRequestDto,
) -> Result<ResponseListSuccessDto<Vec<UsersListItemDto>>> {
let now = Instant::now();
let result: ResponseListSuccessDto<Vec<UsersListQueryDto>> =
QueryListBuilder::new(
&self.state.surrealdb_ws,
@@ -46,6 +54,14 @@ impl<'a> UsersRepository<'a> {
.fetch_fields(vec!["role", "role.permissions"])
.build()
.await?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!("Query 'query_user_list' took: {elapsed:.2?}");
}
let data = result
.data
.into_iter()
@@ -57,70 +73,103 @@ impl<'a> UsersRepository<'a> {
})
}
pub async fn query_user_by_email(
&self,
email: String,
) -> Result<UsersDetailQueryDto> {
let now = Instant::now();
let db = &self.state.surrealdb_ws;
let builder = DetailQueryBuilder::new(ResourceEnum::Users.to_string())
.with_where("email")
.where_value(email.clone())
.with_where("email", Some(email.clone()))
.with_select_fields(vec!["*"])
.with_fetch("role")
.with_fetch("role.permissions");
let sql = builder.build();
let user_opt: Option<UsersDetailQueryDto> =
builder.apply_bindings(db.query(sql)).await?.take(0)?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!("Query 'query_user_by_email' took: {elapsed:.2?}");
}
let Some(user) = user_opt else {
bail!("User not found");
};
if user.is_deleted {
bail!("User not found");
}
if user.role.is_deleted {
if user.role.updated_at.is_none() || user.role.is_deleted {
bail!("User not found");
}
Ok(UsersDetailQueryDto::from(&user))
}
pub async fn query_user_by_id(&self, id: String) -> Result<UsersDetailQueryDto> {
pub async fn query_user_by_id(&self, id: &Thing) -> Result<UsersDetailQueryDto> {
let now = Instant::now();
let db = &self.state.surrealdb_ws;
let builder = DetailQueryBuilder::new(ResourceEnum::Users.to_string())
.with_id(&id)
.with_id(&id.id.to_raw())
.with_select_fields(vec!["*"])
.with_fetch("role")
.with_fetch("role.permissions");
let sql = builder.build();
let result: Option<UsersDetailQueryDto> =
builder.apply_bindings(db.query(sql)).await?.take(0)?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!("Query 'query_user_by_id' took: {elapsed:.2?}");
}
let Some(user) = result else {
bail!("User not found");
bail!("User not found in database");
};
if user.is_deleted {
bail!("User not found");
}
if user.role.is_deleted {
bail!("User not found");
bail!("User's role has been deleted");
}
Ok(UsersDetailQueryDto::from(&user))
}
pub async fn query_create_user(&self, data: UsersSchema) -> Result<String> {
let now = Instant::now();
let db = &self.state.surrealdb_ws;
let record: Option<UsersSchema> = db
.create(ResourceEnum::Users.to_string())
.content(data)
.await?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!("Query 'query_create_user' took: {elapsed:.2?}");
}
match record {
Some(_) => Ok("Success create user".into()),
None => bail!("Failed to create user"),
}
}
pub async fn query_update_user(&self, data: UsersSchema) -> Result<String> {
let now = Instant::now();
let db = &self.state.surrealdb_ws;
let record_key = get_id(&data.id)?;
let existing = self.query_user_by_id(data.id.id.to_raw()).await?;
let existing = self.query_user_by_id(&data.id).await?;
if existing.is_deleted {
bail!("User already deleted");
}
@@ -136,15 +185,25 @@ impl<'a> UsersRepository<'a> {
..data.clone()
};
let record: Option<UsersSchema> = db.update(record_key).merge(merged).await?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!("Query 'query_update_user' took: {elapsed:.2?}");
}
match record {
Some(_) => Ok("Success update user".into()),
None => bail!("Failed to update user"),
}
}
pub async fn query_delete_user(&self, id: String) -> Result<String> {
let now = Instant::now();
let db = &self.state.surrealdb_ws;
let user = self.query_user_by_id(id).await?;
let user = self.query_user_by_id(&make_thing(&ResourceEnum::Users.to_string(), &id)).await?;
if user.is_deleted {
bail!("User not found");
}
@@ -153,9 +212,18 @@ impl<'a> UsersRepository<'a> {
.update(record_key)
.merge(serde_json::json!({ "is_deleted": true }))
.await?;
let elapsed = now.elapsed();
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
== "development"
{
println!("Query 'query_delete_user' took: {elapsed:.2?}");
}
match record {
Some(_) => Ok("Success delete user".into()),
None => bail!("Failed to delete user"),
}
}
}
+33 -1
View File
@@ -1,5 +1,6 @@
use super::{UsersCreateRequestDto, UsersDetailQueryDto, UsersUpdateRequestDto};
use imphnen_libs::{ResourceEnum, hash_password};
use imphnen_utils::extract_id;
use imphnen_utils::{get_iso_date, make_thing};
use serde::{Deserialize, Serialize};
use surrealdb::{Uuid, sql::Thing};
@@ -10,11 +11,16 @@ pub struct UsersSchema {
pub fullname: String,
pub email: String,
pub password: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub avatar: Option<String>,
pub phone_number: String,
pub is_active: bool,
pub is_deleted: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub mentor_id: Option<Thing>,
#[serde(skip_serializing_if = "Option::is_none")]
pub gender: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub birthdate: Option<String>,
pub role: Thing,
pub created_at: String,
@@ -35,6 +41,10 @@ impl Default for UsersSchema {
phone_number: String::new(),
is_active: false,
is_deleted: false,
mentor_id: Some(make_thing(
&ResourceEnum::Users.to_string(),
&Uuid::new_v4().to_string(),
)),
gender: None,
birthdate: None,
role: make_thing(
@@ -57,12 +67,18 @@ impl UsersSchema {
phone_number: dto.phone_number,
is_active: dto.is_active,
is_deleted: dto.is_deleted,
mentor_id: Some(dto.mentor_id.unwrap_or_else(|| {
make_thing(
&ResourceEnum::Users.to_string(),
&Uuid::new_v4().to_string(),
)
})),
gender: dto.gender,
birthdate: dto.birthdate,
password: dto.password,
created_at: dto.created_at,
updated_at: dto.updated_at,
role: make_thing(&ResourceEnum::Roles.to_string(), &dto.role.id.id.to_raw()),
role: make_thing(&ResourceEnum::Roles.to_string(), &extract_id(&dto.role.id)),
}
}
@@ -95,6 +111,10 @@ impl UsersSchema {
password,
phone_number: user.phone_number,
is_active: false,
mentor_id: Some(make_thing(
&ResourceEnum::Users.to_string(),
&Uuid::new_v4().to_string(),
)),
gender: None,
birthdate: None,
avatar: None,
@@ -112,4 +132,16 @@ impl UsersSchema {
..Self::from(dto)
}
}
pub fn update_mentor_id(mut self, mentor_id: Option<String>) -> Self {
self.mentor_id = match mentor_id {
Some(id) => Some(make_thing(&ResourceEnum::Users.to_string(), &id)),
None => Some(make_thing(
&ResourceEnum::Users.to_string(),
&Uuid::new_v4().to_string(),
)),
};
self.updated_at = get_iso_date();
self
}
}
+39 -7
View File
@@ -6,12 +6,15 @@ use crate::{
AppState, MetaRequestDto, ResponseListSuccessDto, UsersRepository, UsersSchema,
};
use crate::{
ResourceEnum, ResponseSuccessDto, common_response, extract_email, make_thing,
success_list_response, success_response, validate_request,
ResponseSuccessDto, common_response, extract_email, success_list_response,
success_response, validate_request,
};
use axum::http::HeaderMap;
use axum::{http::StatusCode, response::Response};
use imphnen_libs::{hash_password, verify_password};
use imphnen_libs::{ResourceEnum, hash_password, verify_password};
use imphnen_utils::make_thing;
use uuid::Uuid;
pub struct UsersService;
@@ -31,8 +34,12 @@ impl UsersService {
}
pub async fn get_user_by_id(state: &AppState, id: String) -> Response {
if Uuid::parse_str(&id).is_err() {
return common_response(StatusCode::BAD_REQUEST, "Invalid User ID format");
}
let repo = UsersRepository::new(state);
match repo.query_user_by_id(id).await {
let thing_id = make_thing(&ResourceEnum::Users.to_string(), &id);
match repo.query_user_by_id(&thing_id).await {
Ok(user) if !user.is_deleted => success_response(ResponseSuccessDto {
data: UsersDetailItemDto::from(&user),
}),
@@ -84,6 +91,9 @@ impl UsersService {
id: String,
user: UsersUpdateRequestDto,
) -> Response {
if Uuid::parse_str(&id).is_err() {
return common_response(StatusCode::BAD_REQUEST, "Invalid User ID format");
}
let repo = UsersRepository::new(state);
if let Err((status, message)) = validate_request(&user) {
return common_response(status, &message);
@@ -124,9 +134,12 @@ impl UsersService {
id: String,
payload: UsersActiveInactiveRequestDto,
) -> Response {
if Uuid::parse_str(&id).is_err() {
return common_response(StatusCode::BAD_REQUEST, "Invalid User ID format");
}
let repo = UsersRepository::new(state);
let thing_id = make_thing(&ResourceEnum::Users.to_string(), &id);
match repo.query_user_by_id(thing_id.id.to_raw()).await {
match repo.query_user_by_id(&thing_id).await {
Ok(user) if !user.is_deleted => {
let patch = UsersSchema {
id: user.id.clone(),
@@ -186,9 +199,28 @@ impl UsersService {
}
}
pub async fn delete_user(state: &AppState, id: String) -> Response {
pub async fn get_user_by_mentor_id(
state: &AppState,
mentor_id: String,
) -> Response {
let repo = UsersRepository::new(state);
if repo.query_user_by_id(id.clone()).await.is_err() {
let thing_id = make_thing(&ResourceEnum::Mentors.to_string(), &mentor_id);
match repo.query_user_by_id(&thing_id).await {
Ok(user) if !user.is_deleted => success_response(ResponseSuccessDto {
data: UsersDetailItemDto::from(&user),
}),
Ok(_) => common_response(StatusCode::NOT_FOUND, "User not found"),
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
}
}
pub async fn delete_user(state: &AppState, id: String) -> Response {
if Uuid::parse_str(&id).is_err() {
return common_response(StatusCode::BAD_REQUEST, "Invalid User ID format");
}
let repo = UsersRepository::new(state);
let thing_id = make_thing(&ResourceEnum::Users.to_string(), &id);
if repo.query_user_by_id(&thing_id).await.is_err() {
return common_response(StatusCode::BAD_REQUEST, "User not found");
}
match repo.query_delete_user(id).await {