diff --git a/crates/avored-core/src/core/application/use_cases/api_key_use_case.rs b/crates/avored-core/src/core/application/use_cases/api_key_use_case.rs index bd5f848e..0590d3de 100644 --- a/crates/avored-core/src/core/application/use_cases/api_key_use_case.rs +++ b/crates/avored-core/src/core/application/use_cases/api_key_use_case.rs @@ -86,3 +86,92 @@ impl ApiKeyUseCase { self.repo.delete(id).await } } + +#[cfg(test)] +mod tests { + use super::*; + use async_trait::async_trait; + + #[derive(Clone, Default)] + struct MockApiKeyRepository; + + #[async_trait] + impl ApiKeyRepository for MockApiKeyRepository { + async fn create(&self, storable: StorableApiKey) -> Result { + Ok(ApiKeyModel { + id: "api-key-1".to_string(), + key_prefix: storable.key_prefix, + key_hash: storable.key_hash, + permissions: storable.permissions, + created_at: "2026-01-01T00:00:00Z".to_string(), + created_by: storable.created_by.clone(), + updated_at: "2026-01-01T00:00:00Z".to_string(), + updated_by: storable.created_by, + name: storable.name, + }) + } + + async fn find_by_id(&self, id: &str) -> Result { + Ok(ApiKeyModel { + id: id.to_string(), + name: "Billing API".to_string(), + key_prefix: "avr_ab12c".to_string(), + key_hash: "hash".to_string(), + permissions: vec![ApiKeyPermission { + endpoint: "/api/v1/entities".to_string(), + method: "GET".to_string(), + }], + created_at: "2026-01-01T00:00:00Z".to_string(), + created_by: "admin".to_string(), + updated_at: "2026-01-01T00:00:00Z".to_string(), + updated_by: "admin".to_string(), + }) + } + + async fn find_by_hash(&self, _key_hash: &str) -> Result> { + Ok(None) + } + + async fn list(&self, _page: u64, _limit: u64) -> Result<(Vec, u64)> { + Ok((vec![], 0)) + } + + async fn update(&self, id: &str, updatable: UpdatableApiKey) -> Result { + Ok(ApiKeyModel { + id: id.to_string(), + name: updatable.name, + key_prefix: "avr_ab12c".to_string(), + key_hash: "updated-hash".to_string(), + permissions: updatable.permissions, + created_at: "2026-01-01T00:00:00Z".to_string(), + created_by: "admin".to_string(), + updated_at: "2026-01-02T00:00:00Z".to_string(), + updated_by: updatable.updated_by, + }) + } + + async fn delete(&self, _id: &str) -> Result { + Ok(true) + } + } + + #[tokio::test] + async fn create_generates_plain_secret_and_hash() { + let use_case = ApiKeyUseCase::new(MockApiKeyRepository); + let permissions = vec![ApiKeyPermission { + endpoint: "/api/v1/entities".to_string(), + method: "GET".to_string(), + }]; + + let (model, plain_secret) = use_case + .create("Billing API".to_string(), permissions, "admin".to_string()) + .await + .expect("api key creation should succeed"); + + assert!(plain_secret.starts_with("avr_")); + assert_eq!(model.name, "Billing API"); + assert_eq!(model.created_by, "admin"); + assert_eq!(model.key_prefix, plain_secret.chars().take(8).collect::()); + assert!(!model.key_hash.is_empty()); + } +} diff --git a/crates/avored-core/src/core/application/use_cases/auth_use_case.rs b/crates/avored-core/src/core/application/use_cases/auth_use_case.rs index 26405852..10f88e21 100644 --- a/crates/avored-core/src/core/application/use_cases/auth_use_case.rs +++ b/crates/avored-core/src/core/application/use_cases/auth_use_case.rs @@ -118,3 +118,127 @@ where self.repository.update_password(user_id, &new_hash).await } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::core::{ + application::dtos::{ChangePasswordCommand, LoginCommand, UpdateProfileCommand}, + domain::{entities::UserModel, extensions::string_extension::StringExtension}, + }; + use async_trait::async_trait; + use surrealdb::types::Datetime; + + #[derive(Clone, Default)] + struct MockAuthRepository { + user: UserModel, + } + + impl MockAuthRepository { + fn new() -> Self { + let mut user = UserModel::default(); + user.id = "user-1".to_string(); + user.name = "Alice".to_string(); + user.email = "alice@example.com".to_string(); + user.password = "password123".to_string().get_password_hash("test-salt").unwrap(); + user.created_at = Datetime::default(); + user.updated_at = Datetime::default(); + Self { user } + } + } + + #[async_trait] + impl AuthRepository for MockAuthRepository { + async fn authenticate(&self, email: &str) -> Result { + if email == self.user.email { + Ok(self.user.clone()) + } else { + Err(crate::error::Error::Authentication) + } + } + + async fn fetch_by_id(&self, id: &str) -> Result { + if id == self.user.id { + Ok(self.user.clone()) + } else { + Err(crate::error::Error::NotFound(id.to_string())) + } + } + + async fn update_profile(&self, id: &str, name: &str, email: &str) -> Result { + if id != self.user.id { + return Err(crate::error::Error::NotFound(id.to_string())); + } + + let mut user = self.user.clone(); + user.name = name.to_string(); + user.email = email.to_string(); + Ok(user) + } + + async fn update_password(&self, id: &str, password_hash: &str) -> Result { + if id != self.user.id { + return Err(crate::error::Error::NotFound(id.to_string())); + } + assert!(!password_hash.is_empty()); + Ok(true) + } + } + + #[tokio::test] + async fn auth_returns_token_for_valid_credentials() { + let repository = MockAuthRepository::new(); + let use_case = AuthUseCase::new(repository); + + let result = use_case + .auth( + LoginCommand { + email: "alice@example.com".to_string(), + password: "password123".to_string(), + }, + "secret-key".to_string(), + ) + .await + .expect("valid credentials should authenticate"); + + assert!(result.authenticated); + assert_eq!(result.user.email, "alice@example.com"); + assert!(!result.token.trim().is_empty()); + } + + #[tokio::test] + async fn update_profile_rejects_empty_name() { + let use_case = AuthUseCase::new(MockAuthRepository::new()); + + let result = use_case + .update_profile( + "user-1", + UpdateProfileCommand { + name: " ".to_string(), + email: "updated@example.com".to_string(), + }, + ) + .await; + + assert!(matches!(result, Err(crate::error::Error::Generic(message)) if message == "Name is required")); + } + + #[tokio::test] + async fn change_password_requires_matching_confirmation() { + let use_case = AuthUseCase::new(MockAuthRepository::new()); + + let result = use_case + .change_password( + "user-1", + ChangePasswordCommand { + current_password: "password123".to_string(), + new_password: "new-password".to_string(), + confirm_password: "different-password".to_string(), + }, + "test-salt", + ) + .await; + + assert!(matches!(result, Err(crate::error::Error::Generic(message)) if message == "New password and confirm password do not match")); + } +} diff --git a/crates/avored-core/src/core/application/use_cases/workflow_use_case.rs b/crates/avored-core/src/core/application/use_cases/workflow_use_case.rs index 21dc07c7..eeaead40 100644 --- a/crates/avored-core/src/core/application/use_cases/workflow_use_case.rs +++ b/crates/avored-core/src/core/application/use_cases/workflow_use_case.rs @@ -225,3 +225,196 @@ fn validate_actions(actions: &[crate::core::domain::entities::WorkflowAction]) - } Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::core::{ + application::dtos::CreateWorkflowCommand, + domain::entities::{ + WorkflowAction, WorkflowEvent, WorkflowExecutionModel, WorkflowExecutionStatus, + WorkflowModel, WorkflowTrigger, + }, + }; + use async_trait::async_trait; + use serde_json::json; + use surrealdb::types::Datetime; + + #[derive(Clone, Default)] + struct MockWorkflowRepository; + + #[async_trait] + impl WorkflowRepository for MockWorkflowRepository { + async fn create( + &self, + name: String, + trigger: WorkflowTrigger, + is_active: bool, + actions: Vec, + ) -> Result { + Ok(WorkflowModel { + id: "workflow-1".to_string(), + name, + trigger, + is_active, + actions, + created_at: Datetime::default(), + updated_at: Datetime::default(), + }) + } + + async fn find_all(&self, _page: u64, _page_size: u64) -> Result<(Vec, u64)> { + Ok((vec![], 0)) + } + + async fn find_by_id(&self, id: &str) -> Result { + Ok(WorkflowModel { + id: id.to_string(), + name: "Example workflow".to_string(), + trigger: WorkflowTrigger { + entity_type: "user".to_string(), + event: WorkflowEvent::Created, + }, + is_active: true, + actions: vec![WorkflowAction::Webhook { + url: "https://example.com/webhook".to_string(), + }], + created_at: Datetime::default(), + updated_at: Datetime::default(), + }) + } + + async fn find_active_by_trigger( + &self, + _entity_type: &str, + _event: WorkflowEvent, + ) -> Result> { + Ok(vec![]) + } + + async fn update( + &self, + id: &str, + name: String, + trigger: WorkflowTrigger, + is_active: bool, + actions: Vec, + ) -> Result { + Ok(WorkflowModel { + id: id.to_string(), + name, + trigger, + is_active, + actions, + created_at: Datetime::default(), + updated_at: Datetime::default(), + }) + } + + async fn set_active(&self, id: &str, is_active: bool) -> Result { + Ok(WorkflowModel { + id: id.to_string(), + name: "Example workflow".to_string(), + trigger: WorkflowTrigger { + entity_type: "user".to_string(), + event: WorkflowEvent::Created, + }, + is_active, + actions: vec![WorkflowAction::Webhook { + url: "https://example.com/webhook".to_string(), + }], + created_at: Datetime::default(), + updated_at: Datetime::default(), + }) + } + + async fn delete(&self, _id: &str) -> Result<()> { + Ok(()) + } + + async fn create_execution( + &self, + workflow_id: &str, + payload: serde_json::Value, + ) -> Result { + Ok(WorkflowExecutionModel { + id: "execution-1".to_string(), + workflow_id: workflow_id.to_string(), + status: WorkflowExecutionStatus::Running, + payload, + error_message: None, + created_at: Datetime::default(), + updated_at: Datetime::default(), + }) + } + + async fn update_execution_status( + &self, + id: &str, + status: WorkflowExecutionStatus, + error_message: Option, + ) -> Result { + Ok(WorkflowExecutionModel { + id: id.to_string(), + workflow_id: "workflow-1".to_string(), + status, + payload: json!({}), + error_message, + created_at: Datetime::default(), + updated_at: Datetime::default(), + }) + } + + async fn find_executions( + &self, + _workflow_id: &str, + _page: u64, + _page_size: u64, + ) -> Result<(Vec, u64)> { + Ok((vec![], 0)) + } + } + + #[tokio::test] + async fn create_rejects_empty_name_or_entity_type() { + let use_case = WorkflowUseCase::new(MockWorkflowRepository); + let result = use_case + .create(CreateWorkflowCommand { + name: " ".to_string(), + trigger: WorkflowTrigger { + entity_type: " ".to_string(), + event: WorkflowEvent::Created, + }, + is_active: Some(true), + actions: vec![WorkflowAction::Webhook { + url: "https://example.com/webhook".to_string(), + }], + }) + .await; + + assert!(matches!(result, Err(Error::BadRequest(_)))); + } + + #[tokio::test] + async fn create_accepts_valid_workflow() { + let use_case = WorkflowUseCase::new(MockWorkflowRepository); + let result = use_case + .create(CreateWorkflowCommand { + name: "User onboarding".to_string(), + trigger: WorkflowTrigger { + entity_type: "user".to_string(), + event: WorkflowEvent::Created, + }, + is_active: Some(true), + actions: vec![WorkflowAction::Webhook { + url: "https://example.com/webhook".to_string(), + }], + }) + .await + .expect("valid workflow should be accepted"); + + assert_eq!(result.name, "User onboarding"); + assert!(result.is_active); + assert_eq!(result.trigger.entity_type, "user"); + } +}