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:
@@ -91,3 +91,32 @@ pub async fn post_execute_gacha_roll(
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
path = "/v1/gacha/rolls/delete/{id}",
|
||||
security(
|
||||
("Bearer" = [])
|
||||
),
|
||||
params(("id" = String, Path, description = "Gacha Roll ID")),
|
||||
responses(
|
||||
(status = 200, description = "Delete Gacha Roll (soft delete)", body = MessageResponseDto)
|
||||
),
|
||||
tag = "Gacha"
|
||||
)]
|
||||
pub async fn delete_gacha_roll(
|
||||
headers: HeaderMap,
|
||||
Extension(state): Extension<AppState>,
|
||||
Path(id): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
match permissions_guard(
|
||||
&headers,
|
||||
state.clone(),
|
||||
vec![PermissionsEnum::DeleteGachaRolls],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => GachaRollService::soft_delete_gacha_roll(&state, id).await,
|
||||
Err(response) => response,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ impl GachaRollItemDto {
|
||||
Self {
|
||||
id: dto.id.id.to_raw(),
|
||||
item: GachaItemDto::from(dto.item.clone()),
|
||||
weight: dto.weight.clone(),
|
||||
weight: dto.weight,
|
||||
quantity: dto.quantity,
|
||||
is_deleted: dto.is_deleted,
|
||||
created_at: dto.created_at.clone(),
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
use super::GachaRollQueryDto;
|
||||
use super::GachaRollSchema;
|
||||
use crate::{AppState, DetailQueryBuilder, ResourceEnum};
|
||||
use crate::{AppState, DetailQueryBuilder, ResourceEnum, get_id, make_thing};
|
||||
use anyhow::{Result, bail};
|
||||
use imphnen_iam::ListQueryBuilder;
|
||||
|
||||
use rand::prelude::*;
|
||||
use rand::rng;
|
||||
|
||||
use imphnen_utils::get_iso_date;
|
||||
use rand_distr::weighted::WeightedIndex;
|
||||
use serde_json::{Map, Value};
|
||||
use std::time::Instant;
|
||||
use tracing::instrument;
|
||||
|
||||
pub struct GachaRollRepository<'a> {
|
||||
state: &'a AppState,
|
||||
@@ -16,46 +20,70 @@ impl<'a> GachaRollRepository<'a> {
|
||||
Self { state }
|
||||
}
|
||||
|
||||
#[instrument(skip(self, id), err)]
|
||||
pub async fn query_gacha_roll_by_id(
|
||||
&self,
|
||||
id: String,
|
||||
) -> Result<GachaRollQueryDto> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let builder = DetailQueryBuilder::new(ResourceEnum::GachaRolls.to_string())
|
||||
.with_id(id.clone())
|
||||
.with_condition("is_deleted = false")
|
||||
.with_select_fields(vec!["*"])
|
||||
.with_fetch("item");
|
||||
let sql = builder.build();
|
||||
let result: Option<GachaRollQueryDto> =
|
||||
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_gacha_roll_by_id' took: {elapsed:.2?}");
|
||||
}
|
||||
match result {
|
||||
Some(roll) if !roll.is_deleted => Ok(roll),
|
||||
_ => bail!("Gacha Roll not found"),
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(skip(self, data), err)]
|
||||
pub async fn query_create_gacha_roll(
|
||||
&self,
|
||||
data: GachaRollSchema,
|
||||
) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let record: Option<GachaRollSchema> = db
|
||||
.create(ResourceEnum::GachaRolls.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_gacha_roll' took: {elapsed:.2?}");
|
||||
}
|
||||
match record {
|
||||
Some(_) => Ok("Success create Gacha Roll".into()),
|
||||
None => bail!("Failed to create Gacha Roll"),
|
||||
}
|
||||
}
|
||||
|
||||
#[instrument(skip(self), err)]
|
||||
pub async fn query_all_active_rolls(&self) -> Result<Vec<GachaRollQueryDto>> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let builder = ListQueryBuilder::new(ResourceEnum::GachaRolls.to_string())
|
||||
.with_select_fields(vec!["*"])
|
||||
.with_fetch(Some(vec!["item"]));
|
||||
let sql = builder.build();
|
||||
let table_name = ResourceEnum::GachaRolls.to_string();
|
||||
let sql =
|
||||
format!("SELECT * FROM {table_name} WHERE is_deleted = false FETCH item");
|
||||
let result: Vec<GachaRollQueryDto> = 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_all_active_rolls' took: {elapsed:.2?}");
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
@@ -72,8 +100,36 @@ impl<'a> GachaRollRepository<'a> {
|
||||
return None;
|
||||
}
|
||||
let dist = WeightedIndex::new(&weights).ok()?;
|
||||
let mut rng = rng();
|
||||
let mut rng = rand::rngs::ThreadRng::default();
|
||||
let index = dist.sample(&mut rng);
|
||||
Some(filtered[index].clone())
|
||||
}
|
||||
|
||||
#[instrument(skip(self, id), err)]
|
||||
pub async fn query_soft_delete_gacha_roll(&self, id: String) -> Result<String> {
|
||||
let now = Instant::now();
|
||||
let db = &self.state.surrealdb_ws;
|
||||
let roll_id_thing = make_thing(&ResourceEnum::GachaRolls.to_string(), &id);
|
||||
let roll = self.query_gacha_roll_by_id(id.clone()).await?;
|
||||
if roll.is_deleted {
|
||||
bail!("Gacha Roll already deleted");
|
||||
}
|
||||
let record_key = get_id(&roll_id_thing)?;
|
||||
|
||||
let mut patch = Map::new();
|
||||
patch.insert("is_deleted".to_string(), Value::Bool(true));
|
||||
patch.insert("updated_at".to_string(), Value::String(get_iso_date()));
|
||||
|
||||
let record: Option<GachaRollSchema> = db.update(record_key).merge(patch).await?;
|
||||
let elapsed = now.elapsed();
|
||||
if std::env::var("RUST_ENV").unwrap_or_else(|_| "development".to_string())
|
||||
== "development"
|
||||
{
|
||||
println!("Query 'query_soft_delete_gacha_roll' took: {elapsed:.2?}");
|
||||
}
|
||||
match record {
|
||||
Some(_) => Ok("Success soft delete Gacha Roll".into()),
|
||||
None => bail!("Failed to soft delete Gacha Roll"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,4 +63,12 @@ impl GachaRollService {
|
||||
Err(e) => common_response(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn soft_delete_gacha_roll(state: &AppState, id: String) -> Response {
|
||||
let repo = GachaRollRepository::new(state);
|
||||
match repo.query_soft_delete_gacha_roll(id).await {
|
||||
Ok(msg) => common_response(StatusCode::OK, &msg),
|
||||
Err(e) => common_response(StatusCode::NOT_FOUND, &e.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user