diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index cefa4e6..b0f69c1 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -7,19 +7,48 @@ on: env: CARGO_TERM_COLOR: always - TEST_DATABASE_URL: "sqlite::memory:" jobs: - test: + # Label of the container job + container-job: + # Containers must run in Linux based operating systems runs-on: ubuntu-latest + # Docker Hub image that `container-job` executes in + container: rust + + # Service containers to run with `container-job` + services: + # Label used to access the service container + postgres: + # Docker Hub image + image: postgres + ports: + - 5432:5432 + # Provide the password and db name for postgres + env: + POSTGRES_PASSWORD: 1234 + POSTGRES_DB: ecdar_api + # Set health checks to wait until postgres has started + options: >- + --health-cmd pg_isready + --health-interval 10s + --health-timeout 5s + --health-retries 5 + steps: - - uses: actions/checkout@v3 + - name: Check out repository code + uses: actions/checkout@v4 with: - submodules: true - - name: Install Protoc + submodules: 'true' + + - name: Install dependencies uses: arduino/setup-protoc@v2 + - uses: Swatinem/rust-cache@v2 with: cache-on-failure: true + - name: Run tests - run: cargo test --verbose + env: + TEST_DATABASE_URL: "postgresql://postgres:1234@postgres:5432/ecdar_api" + run: cargo test -- --test-threads=1 diff --git a/src/api/context_collection.rs b/src/api/context_collection.rs new file mode 100644 index 0000000..7e76c20 --- /dev/null +++ b/src/api/context_collection.rs @@ -0,0 +1,21 @@ +use crate::api::hashing_context::HashingContextTrait; +use crate::api::server::server::ecdar_backend_server::EcdarBackend; +use crate::database::access_context::AccessContextTrait; +use crate::database::in_use_context::InUseContextTrait; +use crate::database::model_context::ModelContextTrait; +use crate::database::query_context::QueryContextTrait; +use crate::database::session_context::SessionContextTrait; +use crate::database::user_context::UserContextTrait; +use std::sync::Arc; + +#[derive(Clone)] +pub struct ContextCollection { + pub(crate) access_context: Arc, + pub(crate) in_use_context: Arc, + pub(crate) model_context: Arc, + pub(crate) query_context: Arc, + pub(crate) session_context: Arc, + pub(crate) user_context: Arc, + pub(crate) reveaal_context: Arc, + pub(crate) hashing_context: Arc, +} diff --git a/src/api/ecdar_api.rs b/src/api/ecdar_api.rs index 978cb36..85e77ab 100644 --- a/src/api/ecdar_api.rs +++ b/src/api/ecdar_api.rs @@ -1,16 +1,11 @@ -use bcrypt::hash; -use chrono::Local; +use crate::api::context_collection::ContextCollection; use regex::Regex; use sea_orm::SqlErr; use std::sync::Arc; use tonic::{Code, Request, Response, Status}; use crate::api::auth::{RequestExt, Token, TokenType}; -use crate::database::{ - access_context::AccessContextTrait, in_use_context::InUseContextTrait, - model_context::ModelContextTrait, query_context::QueryContextTrait, - session_context::SessionContextTrait, user_context::UserContextTrait, -}; +use crate::database::{session_context::SessionContextTrait, user_context::UserContextTrait}; use super::server::server::DeleteModelRequest; use super::server::server::{ @@ -23,28 +18,20 @@ use super::server::server::{ SimulationStartRequest, SimulationStepRequest, SimulationStepResponse, UpdateAccessRequest, UpdateQueryRequest, UpdateUserRequest, UserTokenResponse, }; -use crate::entities::{access, model, query, session, user}; +use crate::entities::{access, query, session, user}; #[derive(Clone)] pub struct ConcreteEcdarApi { - access_context: Arc, - in_use_context: Arc, - model_context: Arc, - query_context: Arc, - session_context: Arc, - user_context: Arc, - reveaal_context: Arc, + contexts: ContextCollection, } -const HASH_COST: u32 = 12; - /// Updates or creates a session in the database for a given user. /// /// /// # Errors /// This function will return an error if the database context returns an error /// or if a session is not found when trying to update an existing one. -async fn handle_session( +pub async fn handle_session( session_context: Arc, request: &Request, is_new_session: bool, @@ -53,16 +40,19 @@ async fn handle_session( uid: String, ) -> Result<(), Status> { if is_new_session { - session_context + let res = session_context .create(session::Model { id: Default::default(), access_token: access_token.clone(), refresh_token: refresh_token.clone(), - updated_at: Local::now().naive_local(), + updated_at: Default::default(), user_id: uid.parse().unwrap(), }) - .await - .unwrap(); + .await; + return match res { + Ok(_) => Ok(()), + Err(e) => Err(Status::new(Code::Internal, e.to_string())), + }; } else { let mut session = match session_context .get_by_refresh_token(request.token_string().unwrap()) @@ -102,24 +92,8 @@ fn is_valid_username(username: &str) -> bool { } impl ConcreteEcdarApi { - pub fn new( - access_context: Arc, - in_use_context: Arc, - model_context: Arc, - query_context: Arc, - session_context: Arc, - user_context: Arc, - reveaal_context: Arc, - ) -> Self { - ConcreteEcdarApi { - access_context, - in_use_context, - model_context, - query_context, - session_context, - user_context, - reveaal_context, - } + pub fn new(contexts: ContextCollection) -> Self { + ConcreteEcdarApi { contexts } } } @@ -151,7 +125,7 @@ impl EcdarApi for ConcreteEcdarApi { .ok_or(Status::internal("Could not get uid from request metadata"))?; let model_id = request.get_ref().id; - let model = match self.model_context.get_by_id(model_id).await { + let model = match self.contexts.model_context.get_by_id(model_id).await { Ok(Some(model)) => model, Ok(None) => return Err(Status::new(Code::NotFound, "No model found with given id")), Err(err) => return Err(Status::new(Code::Internal, err.to_string())), @@ -165,7 +139,7 @@ impl EcdarApi for ConcreteEcdarApi { )); } - match self.model_context.delete(model_id).await { + match self.contexts.model_context.delete(model_id).await { Ok(_) => Ok(Response::new(())), Err(error) => match error { sea_orm::DbErr::RecordNotFound(message) => { @@ -196,7 +170,7 @@ impl EcdarApi for ConcreteEcdarApi { user_id: access.user_id, }; - match self.access_context.create(access).await { + match self.contexts.access_context.create(access).await { Ok(_) => Ok(Response::new(())), Err(error) => Err(Status::new(Code::Internal, error.to_string())), } @@ -222,7 +196,7 @@ impl EcdarApi for ConcreteEcdarApi { user_id: Default::default(), }; - match self.access_context.update(access).await { + match self.contexts.access_context.update(access).await { Ok(_) => Ok(Response::new(())), Err(error) => Err(Status::new(Code::Internal, error.to_string())), } @@ -236,7 +210,12 @@ impl EcdarApi for ConcreteEcdarApi { &self, request: Request, ) -> Result, Status> { - match self.access_context.delete(request.get_ref().id).await { + match self + .contexts + .access_context + .delete(request.get_ref().id) + .await + { Ok(_) => Ok(Response::new(())), Err(error) => match error { sea_orm::DbErr::RecordNotFound(message) => { @@ -263,6 +242,7 @@ impl EcdarApi for ConcreteEcdarApi { // Get user from database let user = self + .contexts .user_context .get_by_id(uid) .await @@ -271,7 +251,7 @@ impl EcdarApi for ConcreteEcdarApi { // Record to be inserted in database let new_user = user::Model { - id: Default::default(), + id: uid, username: match message.clone().username { Some(username) => { if is_valid_username(username.as_str()) { @@ -293,13 +273,13 @@ impl EcdarApi for ConcreteEcdarApi { None => user.email, }, password: match message.clone().password { - Some(password) => hash(password, HASH_COST).unwrap(), + Some(password) => self.contexts.hashing_context.hash_password(password), None => user.password, }, }; // Update user in database - match self.user_context.update(new_user).await { + match self.contexts.user_context.update(new_user).await { Ok(_) => Ok(Response::new(())), Err(error) => Err(Status::new(Code::Internal, error.to_string())), } @@ -315,7 +295,7 @@ impl EcdarApi for ConcreteEcdarApi { .ok_or(Status::internal("Could not get uid from request metadata"))?; // Delete user from database - match self.user_context.delete(uid).await { + match self.contexts.user_context.delete(uid).await { Ok(_) => Ok(Response::new(())), Err(error) => Err(Status::new(Code::Internal, error.to_string())), } @@ -337,7 +317,7 @@ impl EcdarApi for ConcreteEcdarApi { model_id: query_request.model_id, }; - match self.query_context.create(query).await { + match self.contexts.query_context.create(query).await { Ok(_) => Ok(Response::new(())), Err(error) => Err(Status::new(Code::Internal, error.to_string())), } @@ -355,6 +335,7 @@ impl EcdarApi for ConcreteEcdarApi { let message = request.get_ref().clone(); let old_query_res = self + .contexts .query_context .get_by_id(message.id) .await @@ -373,7 +354,7 @@ impl EcdarApi for ConcreteEcdarApi { outdated: old_query.outdated, }; - match self.query_context.update(query).await { + match self.contexts.query_context.update(query).await { Ok(_) => Ok(Response::new(())), Err(error) => Err(Status::new(Code::Internal, error.to_string())), } @@ -386,7 +367,12 @@ impl EcdarApi for ConcreteEcdarApi { &self, request: Request, ) -> Result, Status> { - match self.query_context.delete(request.get_ref().id).await { + match self + .contexts + .query_context + .delete(request.get_ref().id) + .await + { Ok(_) => Ok(Response::new(())), Err(error) => match error { sea_orm::DbErr::RecordNotFound(message) => { @@ -443,8 +429,11 @@ impl EcdarApiAuth for ConcreteEcdarApi { // Get user from credentials if let Some(user_credentials) = message.user_credentials { let input_password = user_credentials.password.clone(); - user_from_db = - get_auth_find_user_helper(Arc::clone(&self.user_context), user_credentials).await?; + user_from_db = get_auth_find_user_helper( + Arc::clone(&self.contexts.user_context), + user_credentials, + ) + .await?; // Check if password in request matches users password if input_password != user_from_db.password { @@ -476,7 +465,7 @@ impl EcdarApiAuth for ConcreteEcdarApi { // Update or create session in database handle_session( - self.session_context.clone(), + self.contexts.session_context.clone(), &request, is_new_session, access_token.clone(), @@ -512,7 +501,7 @@ impl EcdarApiAuth for ConcreteEcdarApi { email: message.clone().email, }; - match self.user_context.create(user).await { + match self.contexts.user_context.create(user).await { Ok(_) => Ok(Response::new(())), Err(e) => match e.sql_err() { Some(SqlErr::UniqueConstraintViolation(e)) => { @@ -536,37 +525,48 @@ impl EcdarBackend for ConcreteEcdarApi { &self, _request: Request<()>, ) -> Result, Status> { - self.reveaal_context.get_user_token(_request).await + self.contexts.reveaal_context.get_user_token(_request).await } async fn send_query( &self, request: Request, ) -> Result, Status> { - self.reveaal_context.send_query(request).await + self.contexts.reveaal_context.send_query(request).await } async fn start_simulation( &self, request: Request, ) -> Result, Status> { - self.reveaal_context.start_simulation(request).await + self.contexts + .reveaal_context + .start_simulation(request) + .await } async fn take_simulation_step( &self, request: Request, ) -> Result, Status> { - self.reveaal_context.take_simulation_step(request).await + self.contexts + .reveaal_context + .take_simulation_step(request) + .await } } +#[cfg(test)] +#[path = "../tests/api/query_logic.rs"] +mod query_logic_tests; + #[cfg(test)] #[path = "../tests/api/access_logic.rs"] -mod access_logic; +mod access_logic_tests; + #[cfg(test)] -#[path = "../tests/api/ecdar_api.rs"] -mod tests; +#[path = "../tests/api/user_logic.rs"] +mod user_logic_tests; #[cfg(test)] #[path = "../tests/api/query_logic.rs"] @@ -575,3 +575,6 @@ mod query_logic; #[cfg(test)] #[path = "../tests/api/model_logic.rs"] mod model_logic; + +#[path = "../tests/api/session_logic.rs"] +mod session_logic_tests; diff --git a/src/api/hashing_context.rs b/src/api/hashing_context.rs new file mode 100644 index 0000000..a4cd7b5 --- /dev/null +++ b/src/api/hashing_context.rs @@ -0,0 +1,18 @@ +use bcrypt::{hash, verify, DEFAULT_COST}; + +pub trait HashingContextTrait: Send + Sync { + fn hash_password(&self, password: String) -> String; + fn verify_password(&self, password: String, hash: &str) -> bool; +} + +pub struct HashingContext; + +impl HashingContextTrait for HashingContext { + fn hash_password(&self, password: String) -> String { + hash(password, DEFAULT_COST).unwrap() + } + + fn verify_password(&self, password: String, hash: &str) -> bool { + verify(password, hash).unwrap() + } +} diff --git a/src/api/mod.rs b/src/api/mod.rs index eae1c43..3e8aa2c 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -1,4 +1,6 @@ pub mod auth; +pub mod context_collection; pub mod ecdar_api; +pub mod hashing_context; pub mod reveaal_context; pub mod server; diff --git a/src/api/server.rs b/src/api/server.rs index 4923a2a..edfdfb9 100644 --- a/src/api/server.rs +++ b/src/api/server.rs @@ -1,32 +1,20 @@ use std::env; -use std::sync::Arc; use tonic::transport::Server; use crate::api::auth; +use crate::api::context_collection::ContextCollection; use crate::api::ecdar_api::ConcreteEcdarApi; use crate::api::server::server::ecdar_api_auth_server::EcdarApiAuthServer; use crate::api::server::server::ecdar_api_server::EcdarApiServer; -use crate::api::server::server::ecdar_backend_server::{EcdarBackend, EcdarBackendServer}; -use crate::database::access_context::AccessContextTrait; -use crate::database::in_use_context::InUseContextTrait; -use crate::database::model_context::ModelContextTrait; -use crate::database::query_context::QueryContextTrait; -use crate::database::session_context::SessionContextTrait; -use crate::database::user_context::UserContextTrait; +use crate::api::server::server::ecdar_backend_server::EcdarBackendServer; pub mod server { tonic::include_proto!("ecdar_proto_buf"); } pub async fn start_grpc_server( - access_context: Arc, - in_use_context: Arc, - model_context: Arc, - query_context: Arc, - session_context: Arc, - user_context: Arc, - reveaal_context: Arc, + contexts: ContextCollection, ) -> Result<(), Box> { // defining address for our service let addr = env::var("API_ADDRESS") @@ -36,15 +24,7 @@ pub async fn start_grpc_server( println!("Starting grpc server on '{}'", addr); - let svc = ConcreteEcdarApi::new( - access_context, - in_use_context, - model_context, - query_context, - session_context, - user_context, - reveaal_context, - ); + let svc = ConcreteEcdarApi::new(contexts); // adding services to our server. Server::builder() diff --git a/src/database/access_context.rs b/src/database/access_context.rs index 2345861..0165105 100644 --- a/src/database/access_context.rs +++ b/src/database/access_context.rs @@ -110,4 +110,4 @@ impl EntityContextTrait for AccessContext { } #[cfg(test)] #[path = "../tests/database/access_context.rs"] -mod tests; +mod access_context_tests; diff --git a/src/database/in_use_context.rs b/src/database/in_use_context.rs index 547c1db..5b790a8 100644 --- a/src/database/in_use_context.rs +++ b/src/database/in_use_context.rs @@ -70,4 +70,4 @@ impl EntityContextTrait for InUseContext { #[cfg(test)] #[path = "../tests/database/in_use_context.rs"] -mod tests; +mod in_use_context_tests; diff --git a/src/database/model_context.rs b/src/database/model_context.rs index 0afe0c4..931e7c9 100644 --- a/src/database/model_context.rs +++ b/src/database/model_context.rs @@ -127,4 +127,4 @@ impl EntityContextTrait for ModelContext { #[cfg(test)] #[path = "../tests/database/model_context.rs"] -mod tests; +mod model_context_tests; diff --git a/src/database/query_context.rs b/src/database/query_context.rs index 6dc17cd..5c56cb7 100644 --- a/src/database/query_context.rs +++ b/src/database/query_context.rs @@ -124,4 +124,4 @@ impl EntityContextTrait for QueryContext { #[cfg(test)] #[path = "../tests/database/query_context.rs"] -mod tests; +mod query_context_tests; diff --git a/src/database/session_context.rs b/src/database/session_context.rs index 8958069..833b0d6 100644 --- a/src/database/session_context.rs +++ b/src/database/session_context.rs @@ -1,7 +1,7 @@ -use chrono::{Local, Utc}; +use chrono::Local; use sea_orm::prelude::async_trait::async_trait; use sea_orm::ActiveValue::{Set, Unchanged}; -use sea_orm::{ActiveModelTrait, ColumnTrait, DbErr, EntityTrait, QueryFilter}; +use sea_orm::{ActiveModelTrait, ColumnTrait, DbErr, EntityTrait, NotSet, QueryFilter}; use std::sync::Arc; use crate::database::database_context::DatabaseContextTrait; @@ -60,7 +60,7 @@ impl EntityContextTrait for SessionContext { refresh_token: Set(entity.refresh_token), access_token: Set(entity.access_token), user_id: Set(entity.user_id), - updated_at: Set(Utc::now().naive_local()), + updated_at: NotSet, }; session.insert(&self.db_context.get_connection()).await @@ -156,4 +156,4 @@ impl EntityContextTrait for SessionContext { #[cfg(test)] #[path = "../tests/database/session_context.rs"] -mod tests; +mod session_context_tests; diff --git a/src/database/user_context.rs b/src/database/user_context.rs index c79fc15..6a42197 100644 --- a/src/database/user_context.rs +++ b/src/database/user_context.rs @@ -147,4 +147,4 @@ impl EntityContextTrait for UserContext { } #[cfg(test)] #[path = "../tests/database/user_context.rs"] -mod tests; +mod user_context_tests; diff --git a/src/main.rs b/src/main.rs index 189f531..15bbcd4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,6 +3,8 @@ mod database; mod entities; mod tests; +use crate::api::context_collection::ContextCollection; +use crate::api::hashing_context::HashingContext; use crate::api::reveaal_context::ReveaalContext; use crate::database::access_context::AccessContext; use crate::database::database_context::{PostgresDatabaseContext, SQLiteDatabaseContext}; @@ -32,25 +34,18 @@ async fn main() -> Result<(), Box> { _ => panic!("Database protocol not supported"), }; - let model_context = Arc::new(ModelContext::new(db_context.clone())); - let user_context = Arc::new(UserContext::new(db_context.clone())); - let access_context = Arc::new(AccessContext::new(db_context.clone())); - let query_context = Arc::new(QueryContext::new(db_context.clone())); - let session_context = Arc::new(SessionContext::new(db_context.clone())); - let in_use_context = Arc::new(InUseContext::new(db_context.clone())); - let reveaal_context = Arc::new(ReveaalContext); + let contexts = ContextCollection { + access_context: Arc::new(AccessContext::new(db_context.clone())), + in_use_context: Arc::new(InUseContext::new(db_context.clone())), + model_context: Arc::new(ModelContext::new(db_context.clone())), + query_context: Arc::new(QueryContext::new(db_context.clone())), + session_context: Arc::new(SessionContext::new(db_context.clone())), + user_context: Arc::new(UserContext::new(db_context.clone())), + reveaal_context: Arc::new(ReveaalContext), + hashing_context: Arc::new(HashingContext), + }; - start_grpc_server( - access_context, - in_use_context, - model_context, - query_context, - session_context, - user_context, - reveaal_context, - ) - .await - .unwrap(); + start_grpc_server(contexts).await.unwrap(); Ok(()) } diff --git a/src/tests/api/access_logic.rs b/src/tests/api/access_logic.rs index c59e0a3..4515825 100644 --- a/src/tests/api/access_logic.rs +++ b/src/tests/api/access_logic.rs @@ -1,175 +1,170 @@ -#[cfg(test)] -mod access_logic { - use crate::api::server::server::ecdar_api_server::EcdarApi; - use crate::api::server::server::{ - CreateAccessRequest, DeleteAccessRequest, UpdateAccessRequest, +use crate::api::server::server::ecdar_api_server::EcdarApi; +use crate::api::server::server::{CreateAccessRequest, DeleteAccessRequest, UpdateAccessRequest}; +use crate::entities::access; +use crate::tests::api::helpers::{get_mock_concrete_ecdar_api, get_mock_services}; +use mockall::predicate; +use sea_orm::DbErr; +use tonic::{Code, Request}; + +#[tokio::test] +async fn create_invalid_access_returns_err() { + let mut mock_services = get_mock_services(); + + let access = access::Model { + id: Default::default(), + role: "Editor".to_string(), + model_id: 1, + user_id: 1, }; - use crate::entities::access; - use crate::tests::api::helpers::{get_mock_concrete_ecdar_api, get_mock_services}; - use mockall::predicate; - use sea_orm::DbErr; - use tonic::{Code, Request}; - - #[tokio::test] - async fn create_invalid_access_returns_err() { - let mut mock_services = get_mock_services(); - - let access = access::Model { - id: Default::default(), - role: "Editor".to_string(), - model_id: 1, - user_id: 1, - }; - - mock_services - .access_context_mock - .expect_create() - .with(predicate::eq(access.clone())) - .returning(move |_| Err(DbErr::RecordNotInserted)); - - let request = Request::new(CreateAccessRequest { - role: "Editor".to_string(), - model_id: 1, - user_id: 1, - }); - - let api = get_mock_concrete_ecdar_api(mock_services); - - let res = api.create_access(request).await.unwrap_err(); - - assert_eq!(res.code(), Code::Internal); - } - - #[tokio::test] - async fn create_access_returns_ok() { - let mut mock_services = get_mock_services(); - - let access = access::Model { - id: Default::default(), - role: "Editor".to_string(), - model_id: 1, - user_id: 1, - }; - mock_services - .access_context_mock - .expect_create() - .with(predicate::eq(access.clone())) - .returning(move |_| Ok(access.clone())); - - let request = Request::new(CreateAccessRequest { - role: "Editor".to_string(), - model_id: 1, - user_id: 1, - }); - - let api = get_mock_concrete_ecdar_api(mock_services); - - let res = api.create_access(request).await; - - assert!(res.is_ok()); - } + mock_services + .access_context_mock + .expect_create() + .with(predicate::eq(access.clone())) + .returning(move |_| Err(DbErr::RecordNotInserted)); - #[tokio::test] - async fn update_invalid_access_returns_err() { - let mut mock_services = get_mock_services(); - - let access = access::Model { - id: 1, - role: "Editor".to_string(), - model_id: Default::default(), - user_id: Default::default(), - }; - - mock_services - .access_context_mock - .expect_update() - .with(predicate::eq(access.clone())) - .returning(move |_| Err(DbErr::RecordNotUpdated)); - - let request = Request::new(UpdateAccessRequest { - id: 1, - role: "Editor".to_string(), - }); - - let api = get_mock_concrete_ecdar_api(mock_services); - - let res = api.update_access(request).await.unwrap_err(); - - assert_eq!(res.code(), Code::Internal); - } - - #[tokio::test] - async fn update_access_returns_ok() { - let mut mock_services = get_mock_services(); - - let access = access::Model { - id: 1, - role: "Editor".to_string(), - model_id: Default::default(), - user_id: Default::default(), - }; + let request = Request::new(CreateAccessRequest { + role: "Editor".to_string(), + model_id: 1, + user_id: 1, + }); - mock_services - .access_context_mock - .expect_update() - .with(predicate::eq(access.clone())) - .returning(move |_| Ok(access.clone())); + let api = get_mock_concrete_ecdar_api(mock_services); - let request = Request::new(UpdateAccessRequest { - id: 1, - role: "Editor".to_string(), - }); + let res = api.create_access(request).await.unwrap_err(); - let api = get_mock_concrete_ecdar_api(mock_services); + assert_eq!(res.code(), Code::Internal); +} + +#[tokio::test] +async fn create_access_returns_ok() { + let mut mock_services = get_mock_services(); + + let access = access::Model { + id: Default::default(), + role: "Editor".to_string(), + model_id: 1, + user_id: 1, + }; + + mock_services + .access_context_mock + .expect_create() + .with(predicate::eq(access.clone())) + .returning(move |_| Ok(access.clone())); + + let request = Request::new(CreateAccessRequest { + role: "Editor".to_string(), + model_id: 1, + user_id: 1, + }); + + let api = get_mock_concrete_ecdar_api(mock_services); + + let res = api.create_access(request).await; + + assert!(res.is_ok()); +} + +#[tokio::test] +async fn update_invalid_access_returns_err() { + let mut mock_services = get_mock_services(); + + let access = access::Model { + id: 1, + role: "Editor".to_string(), + model_id: Default::default(), + user_id: Default::default(), + }; + + mock_services + .access_context_mock + .expect_update() + .with(predicate::eq(access.clone())) + .returning(move |_| Err(DbErr::RecordNotUpdated)); - let res = api.update_access(request).await; + let request = Request::new(UpdateAccessRequest { + id: 1, + role: "Editor".to_string(), + }); - assert!(res.is_ok()); - } + let api = get_mock_concrete_ecdar_api(mock_services); - #[tokio::test] - async fn delete_invalid_access_returns_err() { - let mut mock_services = get_mock_services(); + let res = api.update_access(request).await.unwrap_err(); - mock_services - .access_context_mock - .expect_delete() - .with(predicate::eq(1)) - .returning(move |_| Err(DbErr::RecordNotFound("".to_string()))); + assert_eq!(res.code(), Code::Internal); +} + +#[tokio::test] +async fn update_access_returns_ok() { + let mut mock_services = get_mock_services(); + + let access = access::Model { + id: 1, + role: "Editor".to_string(), + model_id: Default::default(), + user_id: Default::default(), + }; + + mock_services + .access_context_mock + .expect_update() + .with(predicate::eq(access.clone())) + .returning(move |_| Ok(access.clone())); + + let request = Request::new(UpdateAccessRequest { + id: 1, + role: "Editor".to_string(), + }); + + let api = get_mock_concrete_ecdar_api(mock_services); - let request = Request::new(DeleteAccessRequest { id: 1 }); + let res = api.update_access(request).await; - let api = get_mock_concrete_ecdar_api(mock_services); + assert!(res.is_ok()); +} + +#[tokio::test] +async fn delete_invalid_access_returns_err() { + let mut mock_services = get_mock_services(); - let res = api.delete_access(request).await.unwrap_err(); + mock_services + .access_context_mock + .expect_delete() + .with(predicate::eq(1)) + .returning(move |_| Err(DbErr::RecordNotFound("".to_string()))); - assert_eq!(res.code(), Code::NotFound); - } + let request = Request::new(DeleteAccessRequest { id: 1 }); - #[tokio::test] - async fn delete_access_returns_ok() { - let mut mock_services = get_mock_services(); + let api = get_mock_concrete_ecdar_api(mock_services); - let access = access::Model { - id: 1, - role: "Editor".to_string(), - model_id: Default::default(), - user_id: Default::default(), - }; + let res = api.delete_access(request).await.unwrap_err(); + + assert_eq!(res.code(), Code::NotFound); +} + +#[tokio::test] +async fn delete_access_returns_ok() { + let mut mock_services = get_mock_services(); + + let access = access::Model { + id: 1, + role: "Editor".to_string(), + model_id: Default::default(), + user_id: Default::default(), + }; - mock_services - .access_context_mock - .expect_delete() - .with(predicate::eq(1)) - .returning(move |_| Ok(access.clone())); + mock_services + .access_context_mock + .expect_delete() + .with(predicate::eq(1)) + .returning(move |_| Ok(access.clone())); - let request = Request::new(DeleteAccessRequest { id: 1 }); + let request = Request::new(DeleteAccessRequest { id: 1 }); - let api = get_mock_concrete_ecdar_api(mock_services); + let api = get_mock_concrete_ecdar_api(mock_services); - let res = api.delete_access(request).await; + let res = api.delete_access(request).await; - assert!(res.is_ok()); - } + assert!(res.is_ok()); } diff --git a/src/tests/api/ecdar_api.rs b/src/tests/api/ecdar_api.rs deleted file mode 100644 index f83df4c..0000000 --- a/src/tests/api/ecdar_api.rs +++ /dev/null @@ -1,417 +0,0 @@ -#[cfg(test)] -mod ecdar_api { - - use crate::api::server::server::ecdar_api_server::EcdarApi; - - use futures::SinkExt; - use mockall::predicate; - use sea_orm::DbErr; - use std::str::FromStr; - - use crate::tests::api::helpers::{get_mock_concrete_ecdar_api, get_mock_services}; - use tonic::{metadata, Code, Request}; - - #[tokio::test] - async fn delete_user_nonexistent_user_returns_err() { - let mut mock_services = get_mock_services(); - - mock_services - .user_context_mock - .expect_delete() - .with(predicate::eq(1)) - .returning(|_| Err(DbErr::RecordNotFound("".into()))); - - let api = get_mock_concrete_ecdar_api(mock_services); - - let mut delete_request = Request::new(()); - - // Insert uid into request metadata - delete_request - .metadata_mut() - .insert("uid", metadata::MetadataValue::from_str("1").unwrap()); - - let delete_response = api.delete_user(delete_request).await.unwrap_err(); - let expected_response_code = Code::Internal; - - assert_eq!(delete_response.code(), expected_response_code); - } - - // - // #[tokio::test] - // async fn delete_user_existing_user_returns_ok() { - // let api = get_mock_concrete_ecdar_api().await; - // - // let _ = api - // .user_context - // .create(User { - // id: Default::default(), - // email: "anders21@student.aau.dk".to_string(), - // username: "anders".to_string(), - // password: "123".to_string(), - // }) - // .await - // .unwrap(); - // - // let mut delete_request = Request::new({}); - // - // // Insert uid into request metadata - // delete_request - // .metadata_mut() - // .insert("uid", metadata::MetadataValue::from_str("1").unwrap()); - // - // let delete_response = api.delete_user(delete_request).await; - // - // assert!(delete_response.is_ok()); - // } - // - // #[tokio::test] - // async fn create_user_nonexistent_user_returns_ok() { - // let api = get_mock_concrete_ecdar_api().await; - // - // let create_user_request = Request::new(CreateUserRequest { - // email: "anders21@student.aau.dk".to_string(), - // username: "anders".to_string(), - // password: "123".to_string(), - // }); - // - // let create_user_response = api.create_user(create_user_request).await; - // assert!(create_user_response.is_ok()); - // } - // - // #[tokio::test] - // async fn create_user_nonexistent_user_inserts_user() { - // let api = get_mock_concrete_ecdar_api().await; - // - // let username = "newuser".to_string(); - // - // let create_user_request = Request::new(CreateUserRequest { - // email: "anders21@student.aau.dk".to_string(), - // username: username.clone(), - // password: "123".to_string(), - // }); - // - // let _ = api.create_user(create_user_request).await; - // - // assert!(api - // .user_context - // .get_by_username(username) - // .await - // .unwrap() - // .is_some()); - // } - // - // #[tokio::test] - // async fn test_create_user_duplicate_email_returns_error() { - // let api = get_mock_concrete_ecdar_api().await; - // - // let _ = api - // .user_context - // .create(User { - // id: Default::default(), - // email: "existing@example.com".to_string(), - // username: "newuser1".to_string(), - // password: "123".to_string(), - // }) - // .await; - // - // let create_user_request = Request::new(CreateUserRequest { - // email: "existing@example.com".to_string(), - // username: "newuser2".to_string(), - // password: "123".to_string(), - // }); - // - // let create_user_response = api.create_user(create_user_request).await; - // assert!(create_user_response.is_err()); - // } - // - // #[tokio::test] - // async fn test_create_user_invalid_email_returns_error() { - // let api = get_mock_concrete_ecdar_api().await; - // - // let create_user_request = Request::new(CreateUserRequest { - // email: "invalid-email".to_string(), - // username: "newuser".to_string(), - // password: "123".to_string(), - // }); - // - // let create_user_response = api.create_user(create_user_request).await; - // assert!(create_user_response.is_err()); - // } - // - // #[tokio::test] - // async fn test_create_user_duplicate_username_returns_error() { - // let api = get_mock_concrete_ecdar_api().await; - // - // let _ = api - // .user_context - // .create(User { - // id: Default::default(), - // email: "valid@email.com".to_string(), - // username: "existing".to_string(), - // password: "123".to_string(), - // }) - // .await; - // - // let create_user_request = Request::new(CreateUserRequest { - // email: "valid@email2.com".to_string(), - // username: "existing".to_string(), - // password: "123".to_string(), - // }); - // - // let create_user_response = api.create_user(create_user_request).await; - // assert!(create_user_response.is_err()); - // } - // - // #[tokio::test] - // async fn test_create_user_invalid_username_returns_error() { - // let api = get_mock_concrete_ecdar_api().await; - // - // let create_user_request = Request::new(CreateUserRequest { - // email: "valid@email.com".to_string(), - // username: "invalid username".to_string(), - // password: "123".to_string(), - // }); - // - // let create_user_response = api.create_user(create_user_request).await; - // assert!(create_user_response.is_err()); - // } - // - // #[tokio::test] - // async fn test_create_user_valid_request_returns_ok() { - // let api = get_mock_concrete_ecdar_api().await; - // - // let create_user_request = Request::new(CreateUserRequest { - // email: "newuser@example.com".to_string(), - // username: "newuser".to_string(), - // password: "StrongPassword123".to_string(), - // }); - // - // let create_user_response = api.create_user(create_user_request).await; - // assert!(create_user_response.is_ok()); - // } - // - // #[tokio::test] - // async fn update_user_returns_ok() { - // let api = get_mock_concrete_ecdar_api().await; - // - // let user = User { - // id: 1, - // email: "test@test".to_string(), - // username: "test_user".to_string(), - // password: "test_pass".to_string(), - // }; - // - // api.user_context.create(user.clone()).await.unwrap(); - // - // let mut update_user_request = Request::new(UpdateUserRequest { - // email: Some("new_test@test".to_string()), - // username: Some("new_test_user".to_string()), - // password: Some("new_test_pass".to_string()), - // }); - // - // update_user_request - // .metadata_mut() - // .insert("uid", metadata::MetadataValue::from_str("1").unwrap()); - // - // let update_user_response = api.update_user(update_user_request).await; - // - // assert!(update_user_response.is_ok()) - // } - // - // #[tokio::test] - // async fn update_user_non_existant_user_returns_err() { - // let api = get_mock_concrete_ecdar_api().await; - // - // let mut update_user_request = Request::new(UpdateUserRequest { - // email: Some("new_test@test".to_string()), - // username: Some("new_test_user".to_string()), - // password: Some("new_test_pass".to_string()), - // }); - // - // update_user_request - // .metadata_mut() - // .insert("uid", metadata::MetadataValue::from_str("1").unwrap()); - // - // let update_user_response = api.update_user(update_user_request).await; - // - // assert!(update_user_response.is_err()) - // } - // - // #[tokio::test] - // async fn update_user_single_field_returns_ok() { - // let api = get_mock_concrete_ecdar_api().await; - // - // let user = User { - // id: 1, - // email: "test@test".to_string(), - // username: "test_user".to_string(), - // password: "test_pass".to_string(), - // }; - // - // api.user_context.create(user.clone()).await.unwrap(); - // - // let mut update_user_request = Request::new(UpdateUserRequest { - // email: Some("new_test@test".to_string()), - // username: None, - // password: None, - // }); - // - // update_user_request - // .metadata_mut() - // .insert("uid", metadata::MetadataValue::from_str("1").unwrap()); - // - // let update_user_response = api.update_user(update_user_request).await; - // - // assert!(update_user_response.is_ok()) - // } - // - // #[tokio::test] - // async fn handle_session_updated_session_contains_correct_fields() { - // let api = get_mock_concrete_ecdar_api().await; - // - // let mut get_auth_token_request = Request::new(GetAuthTokenRequest { - // user_credentials: Some(UserCredentials { - // user: Some(user_credentials::User::Email("test@test".to_string())), - // password: "test_password".to_string(), - // }), - // }); - // - // get_auth_token_request.metadata_mut().insert( - // "authorization", - // metadata::MetadataValue::from_str("Bearer test_refresh_token").unwrap(), - // ); - // - // let user = User { - // id: 1, - // email: "test@test".to_string(), - // username: "test_user".to_string(), - // password: "test_pass".to_string(), - // }; - // - // let is_new_session = false; - // - // api.user_context.create(user.clone()).await.unwrap(); - // - // let old_session = api - // .session_context - // .create(Session { - // id: Default::default(), - // refresh_token: "test_refresh_token".to_string(), - // access_token: "test_access_token".to_string(), - // updated_at: Default::default(), - // user_id: 1, - // }) - // .await - // .unwrap(); - // - // handle_session( - // api.session_context.clone(), - // &get_auth_token_request, - // is_new_session, - // "new_access_token".to_string(), - // "new_refresh_token".to_string(), - // user.id.to_string(), - // ) - // .await - // .unwrap(); - // - // let expected_session = Session { - // id: 1, - // refresh_token: "new_refresh_token".to_string(), - // access_token: "new_access_token".to_string(), - // updated_at: Default::default(), - // user_id: 1, - // }; - // - // let updated_session = api.session_context.get_by_id(1).await.unwrap().unwrap(); - // assert_ne!(updated_session, old_session); - // assert_eq!( - // updated_session.refresh_token, - // expected_session.refresh_token - // ); - // assert_eq!(updated_session.access_token, expected_session.access_token); - // assert!(updated_session.updated_at > old_session.updated_at); - // assert_eq!(updated_session.user_id, expected_session.user_id); - // assert_eq!(updated_session.id, expected_session.id); - // } - // - // #[tokio::test] - // async fn handle_session_no_session_exists_creates_session() { - // let api = get_mock_concrete_ecdar_api().await; - // - // let mut get_auth_token_request = Request::new(GetAuthTokenRequest { - // user_credentials: Some(UserCredentials { - // user: Some(user_credentials::User::Email("test@test".to_string())), - // password: "test_password".to_string(), - // }), - // }); - // - // get_auth_token_request.metadata_mut().insert( - // "authorization", - // metadata::MetadataValue::from_str("Bearer test_refresh_token").unwrap(), - // ); - // - // let user = User { - // id: 1, - // email: "test@test".to_string(), - // username: "test_user".to_string(), - // password: "test_pass".to_string(), - // }; - // - // let is_new_session = true; - // - // api.user_context.create(user.clone()).await.unwrap(); - // - // handle_session( - // api.session_context.clone(), - // &get_auth_token_request, - // is_new_session, - // "access_token".to_string(), - // "refresh_token".to_string(), - // user.id.to_string(), - // ) - // .await - // .unwrap(); - // - // assert!(api.session_context.get_by_id(1).await.unwrap().is_some()); - // } - // - // #[tokio::test] - // async fn handle_session_update_non_existing_session_returns_err() { - // let api = get_mock_concrete_ecdar_api(Arc::new(MockEcdarBackend)).await; - // - // let mut get_auth_token_request = Request::new(GetAuthTokenRequest { - // user_credentials: Some(UserCredentials { - // user: Some(user_credentials::User::Email("test@test".to_string())), - // password: "test_password".to_string(), - // }), - // }); - // - // get_auth_token_request.metadata_mut().insert( - // "authorization", - // metadata::MetadataValue::from_str("Bearer test_refresh_token").unwrap(), - // ); - // - // let user = User { - // id: 1, - // email: "test@test".to_string(), - // username: "test_user".to_string(), - // password: "test_pass".to_string(), - // }; - // - // let is_new_session = false; - // - // api.user_context.create(user.clone()).await.unwrap(); - // - // assert!(handle_session( - // api.session_context.clone(), - // &get_auth_token_request, - // is_new_session, - // "access_token".to_string(), - // "refresh_token".to_string(), - // user.id.to_string(), - // ) - // .await - // .is_err()); - // } -} diff --git a/src/tests/api/helpers.rs b/src/tests/api/helpers.rs index c035cbf..d8ef4c8 100644 --- a/src/tests/api/helpers.rs +++ b/src/tests/api/helpers.rs @@ -1,7 +1,13 @@ #![cfg(test)] +use crate::api::context_collection::ContextCollection; use crate::api::ecdar_api::ConcreteEcdarApi; -use crate::api::reveaal_context::ReveaalContext; +use crate::api::hashing_context::HashingContextTrait; +use crate::api::server::server::ecdar_backend_server::EcdarBackend; +use crate::api::server::server::{ + QueryRequest, QueryResponse, SimulationStartRequest, SimulationStepRequest, + SimulationStepResponse, UserTokenResponse, +}; use crate::database::access_context::AccessContextTrait; use crate::database::entity_context::EntityContextTrait; use crate::database::in_use_context::InUseContextTrait; @@ -14,17 +20,20 @@ use async_trait::async_trait; use mockall::mock; use sea_orm::DbErr; use std::sync::Arc; +use tonic::{Request, Response, Status}; pub fn get_mock_concrete_ecdar_api(mock_services: MockServices) -> ConcreteEcdarApi { - ConcreteEcdarApi::new( - Arc::new(mock_services.access_context_mock), - Arc::new(mock_services.in_use_context_mock), - Arc::new(mock_services.model_context_mock), - Arc::new(mock_services.query_context_mock), - Arc::new(mock_services.session_context_mock), - Arc::new(mock_services.user_context_mock), - Arc::new(ReveaalContext), - ) + let contexts = ContextCollection { + access_context: Arc::new(mock_services.access_context_mock), + in_use_context: Arc::new(mock_services.in_use_context_mock), + model_context: Arc::new(mock_services.model_context_mock), + query_context: Arc::new(mock_services.query_context_mock), + session_context: Arc::new(mock_services.session_context_mock), + user_context: Arc::new(mock_services.user_context_mock), + reveaal_context: Arc::new(mock_services.reveaal_context_mock), + hashing_context: Arc::new(mock_services.hashing_context_mock), + }; + ConcreteEcdarApi::new(contexts) } pub fn get_mock_services() -> MockServices { @@ -35,6 +44,8 @@ pub fn get_mock_services() -> MockServices { query_context_mock: MockQueryContext::new(), session_context_mock: MockSessionContext::new(), user_context_mock: MockUserContext::new(), + reveaal_context_mock: MockReveaalContext::new(), + hashing_context_mock: MockHashingContext::new(), } } @@ -45,6 +56,8 @@ pub struct MockServices { pub(crate) query_context_mock: MockQueryContext, pub(crate) session_context_mock: MockSessionContext, pub(crate) user_context_mock: MockUserContext, + pub(crate) reveaal_context_mock: MockReveaalContext, + pub(crate) hashing_context_mock: MockHashingContext, } mock! { @@ -135,3 +148,22 @@ mock! { async fn get_by_email(&self, email: String) -> Result, DbErr>; } } + +mock! { + pub ReveaalContext {} + #[async_trait] + impl EcdarBackend for ReveaalContext { + async fn get_user_token(&self,request: Request<()>) -> Result, Status>; + async fn send_query(&self,request: Request) -> Result, Status>; + async fn start_simulation(&self, request: Request) -> Result, Status>; + async fn take_simulation_step(&self, request: Request) -> Result, Status>; + } +} + +mock! { + pub HashingContext {} + impl HashingContextTrait for HashingContext { + fn hash_password(&self, password: String) -> String; + fn verify_password(&self, password: String, hash: &str) -> bool; + } +} diff --git a/src/tests/api/query_logic.rs b/src/tests/api/query_logic.rs index 1890b43..298a0dd 100644 --- a/src/tests/api/query_logic.rs +++ b/src/tests/api/query_logic.rs @@ -1,198 +1,195 @@ -#[cfg(test)] -mod query_logic { - use crate::api::server::server::ecdar_api_server::EcdarApi; - use crate::api::server::server::{CreateQueryRequest, DeleteQueryRequest, UpdateQueryRequest}; - use crate::entities::query; - use crate::tests::api::helpers::{get_mock_concrete_ecdar_api, get_mock_services}; - use mockall::predicate; - use sea_orm::DbErr; - use tonic::{Code, Request}; - - #[tokio::test] - async fn create_invalid_query_returns_err() { - let mut mock_services = get_mock_services(); - - let query = query::Model { - id: Default::default(), - string: "".to_string(), - result: Default::default(), - model_id: 1, - outdated: Default::default(), - }; - - mock_services - .query_context_mock - .expect_create() - .with(predicate::eq(query.clone())) - .returning(move |_| Err(DbErr::RecordNotInserted)); - - let request = Request::new(CreateQueryRequest { - string: "".to_string(), - model_id: 1, - }); - - let api = get_mock_concrete_ecdar_api(mock_services); - - let res = api.create_query(request).await.unwrap_err(); - - assert_eq!(res.code(), Code::Internal); - } - - #[tokio::test] - async fn create_query_returns_ok() { - let mut mock_services = get_mock_services(); - - let query = query::Model { - id: Default::default(), - string: "".to_string(), - result: Default::default(), - model_id: 1, - outdated: Default::default(), - }; - - mock_services - .query_context_mock - .expect_create() - .with(predicate::eq(query.clone())) - .returning(move |_| Ok(query.clone())); - - let request = Request::new(CreateQueryRequest { - string: "".to_string(), - model_id: 1, - }); - - let api = get_mock_concrete_ecdar_api(mock_services); - - let res = api.create_query(request).await; - - assert!(res.is_ok()); - } - - #[tokio::test] - async fn update_invalid_query_returns_err() { - let mut mock_services = get_mock_services(); - - let old_query = query::Model { - id: 1, - string: "".to_string(), - result: None, - model_id: Default::default(), - outdated: true, - }; - - let query = query::Model { - string: "updated".to_string(), - ..old_query.clone() - }; - - mock_services - .query_context_mock - .expect_get_by_id() - .with(predicate::eq(1)) - .returning(move |_| Ok(Some(old_query.clone()))); - - mock_services - .query_context_mock - .expect_update() - .with(predicate::eq(query.clone())) - .returning(move |_| Err(DbErr::RecordNotUpdated)); - - let request = Request::new(UpdateQueryRequest { - id: 1, - string: "updated".to_string(), - }); - - let api = get_mock_concrete_ecdar_api(mock_services); - - let res = api.update_query(request).await.unwrap_err(); - - assert_eq!(res.code(), Code::Internal); - } - - #[tokio::test] - async fn update_query_returns_ok() { - let mut mock_services = get_mock_services(); - - let old_query = query::Model { - id: 1, - string: "".to_string(), - result: None, - model_id: Default::default(), - outdated: true, - }; - - let query = query::Model { - string: "updated".to_string(), - ..old_query.clone() - }; +use crate::api::server::server::ecdar_api_server::EcdarApi; +use crate::api::server::server::{CreateQueryRequest, DeleteQueryRequest, UpdateQueryRequest}; +use crate::entities::query; +use crate::tests::api::helpers::{get_mock_concrete_ecdar_api, get_mock_services}; +use mockall::predicate; +use sea_orm::DbErr; +use tonic::{Code, Request}; + +#[tokio::test] +async fn create_invalid_query_returns_err() { + let mut mock_services = get_mock_services(); + + let query = query::Model { + id: Default::default(), + string: "".to_string(), + result: Default::default(), + model_id: 1, + outdated: Default::default(), + }; + + mock_services + .query_context_mock + .expect_create() + .with(predicate::eq(query.clone())) + .returning(move |_| Err(DbErr::RecordNotInserted)); + + let request = Request::new(CreateQueryRequest { + string: "".to_string(), + model_id: 1, + }); + + let api = get_mock_concrete_ecdar_api(mock_services); + + let res = api.create_query(request).await.unwrap_err(); + + assert_eq!(res.code(), Code::Internal); +} + +#[tokio::test] +async fn create_query_returns_ok() { + let mut mock_services = get_mock_services(); + + let query = query::Model { + id: Default::default(), + string: "".to_string(), + result: Default::default(), + model_id: 1, + outdated: Default::default(), + }; + + mock_services + .query_context_mock + .expect_create() + .with(predicate::eq(query.clone())) + .returning(move |_| Ok(query.clone())); + + let request = Request::new(CreateQueryRequest { + string: "".to_string(), + model_id: 1, + }); - mock_services - .query_context_mock - .expect_get_by_id() - .with(predicate::eq(1)) - .returning(move |_| Ok(Some(old_query.clone()))); - - mock_services - .query_context_mock - .expect_update() - .with(predicate::eq(query.clone())) - .returning(move |_| Ok(query.clone())); - - let request = Request::new(UpdateQueryRequest { - id: 1, - string: "updated".to_string(), - }); - - let api = get_mock_concrete_ecdar_api(mock_services); - - let res = api.update_query(request).await; - - assert!(res.is_ok()); - } + let api = get_mock_concrete_ecdar_api(mock_services); - #[tokio::test] - async fn delete_invalid_query_returns_err() { - let mut mock_services = get_mock_services(); + let res = api.create_query(request).await; + + assert!(res.is_ok()); +} + +#[tokio::test] +async fn update_invalid_query_returns_err() { + let mut mock_services = get_mock_services(); + + let old_query = query::Model { + id: 1, + string: "".to_string(), + result: None, + model_id: Default::default(), + outdated: true, + }; + + let query = query::Model { + string: "updated".to_string(), + ..old_query.clone() + }; + + mock_services + .query_context_mock + .expect_get_by_id() + .with(predicate::eq(1)) + .returning(move |_| Ok(Some(old_query.clone()))); + + mock_services + .query_context_mock + .expect_update() + .with(predicate::eq(query.clone())) + .returning(move |_| Err(DbErr::RecordNotUpdated)); + + let request = Request::new(UpdateQueryRequest { + id: 1, + string: "updated".to_string(), + }); + + let api = get_mock_concrete_ecdar_api(mock_services); + + let res = api.update_query(request).await.unwrap_err(); + + assert_eq!(res.code(), Code::Internal); +} - mock_services - .query_context_mock - .expect_delete() - .with(predicate::eq(1)) - .returning(move |_| Err(DbErr::RecordNotFound("".to_string()))); +#[tokio::test] +async fn update_query_returns_ok() { + let mut mock_services = get_mock_services(); + + let old_query = query::Model { + id: 1, + string: "".to_string(), + result: None, + model_id: Default::default(), + outdated: true, + }; + + let query = query::Model { + string: "updated".to_string(), + ..old_query.clone() + }; + + mock_services + .query_context_mock + .expect_get_by_id() + .with(predicate::eq(1)) + .returning(move |_| Ok(Some(old_query.clone()))); + + mock_services + .query_context_mock + .expect_update() + .with(predicate::eq(query.clone())) + .returning(move |_| Ok(query.clone())); + + let request = Request::new(UpdateQueryRequest { + id: 1, + string: "updated".to_string(), + }); + + let api = get_mock_concrete_ecdar_api(mock_services); + + let res = api.update_query(request).await; + + assert!(res.is_ok()); +} + +#[tokio::test] +async fn delete_invalid_query_returns_err() { + let mut mock_services = get_mock_services(); + + mock_services + .query_context_mock + .expect_delete() + .with(predicate::eq(1)) + .returning(move |_| Err(DbErr::RecordNotFound("".to_string()))); + + let request = Request::new(DeleteQueryRequest { id: 1 }); + + let api = get_mock_concrete_ecdar_api(mock_services); + + let res = api.delete_query(request).await.unwrap_err(); + + assert_eq!(res.code(), Code::NotFound); +} - let request = Request::new(DeleteQueryRequest { id: 1 }); +#[tokio::test] +async fn delete_query_returns_ok() { + let mut mock_services = get_mock_services(); - let api = get_mock_concrete_ecdar_api(mock_services); - - let res = api.delete_query(request).await.unwrap_err(); - - assert_eq!(res.code(), Code::NotFound); - } - - #[tokio::test] - async fn delete_query_returns_ok() { - let mut mock_services = get_mock_services(); - - let query = query::Model { - id: 1, - string: "".to_string(), - result: Default::default(), - model_id: Default::default(), - outdated: Default::default(), - }; + let query = query::Model { + id: 1, + string: "".to_string(), + result: Default::default(), + model_id: Default::default(), + outdated: Default::default(), + }; - mock_services - .query_context_mock - .expect_delete() - .with(predicate::eq(1)) - .returning(move |_| Ok(query.clone())); + mock_services + .query_context_mock + .expect_delete() + .with(predicate::eq(1)) + .returning(move |_| Ok(query.clone())); - let request = Request::new(DeleteQueryRequest { id: 1 }); + let request = Request::new(DeleteQueryRequest { id: 1 }); - let api = get_mock_concrete_ecdar_api(mock_services); + let api = get_mock_concrete_ecdar_api(mock_services); - let res = api.delete_query(request).await; + let res = api.delete_query(request).await; - assert!(res.is_ok()); - } + assert!(res.is_ok()); } diff --git a/src/tests/api/session_logic.rs b/src/tests/api/session_logic.rs new file mode 100644 index 0000000..3945c39 --- /dev/null +++ b/src/tests/api/session_logic.rs @@ -0,0 +1,133 @@ +use crate::api::ecdar_api::handle_session; +use crate::api::server::server::GetAuthTokenRequest; +use crate::entities::session; +use crate::tests::api::helpers::get_mock_services; +use mockall::predicate; +use sea_orm::DbErr; +use std::str::FromStr; +use std::sync::Arc; +use tonic::{metadata, Code, Request}; + +#[tokio::test] +async fn handle_session_updated_session_contains_correct_fields_returns_ok() { + let mut mock_services = get_mock_services(); + + let old_session = session::Model { + id: 1, + refresh_token: "old_refresh_token".to_string(), + access_token: "old_access_token".to_string(), + updated_at: Default::default(), + user_id: 1, + }; + + let new_session = session::Model { + id: 1, + refresh_token: "new_refresh_token".to_string(), + access_token: "new_access_token".to_string(), + updated_at: Default::default(), + user_id: 1, + }; + + mock_services + .session_context_mock + .expect_get_by_refresh_token() + .with(predicate::eq("old_refresh_token".to_string())) + .returning(move |_| Ok(Some(old_session.clone()))); + + mock_services + .session_context_mock + .expect_update() + .with(predicate::eq(new_session.clone())) + .returning(move |_| Ok(new_session.clone())); + + let mut get_auth_token_request = Request::new(GetAuthTokenRequest { + user_credentials: None, + }); + + get_auth_token_request.metadata_mut().insert( + "authorization", + metadata::MetadataValue::from_str("Bearer old_refresh_token").unwrap(), + ); + + let res = handle_session( + Arc::new(mock_services.session_context_mock), + &get_auth_token_request, + false, + "new_access_token".to_string(), + "new_refresh_token".to_string(), + "1".to_string(), + ) + .await; + + assert!(res.is_ok()); +} + +#[tokio::test] +async fn handle_session_no_session_exists_creates_session_returns_ok() { + let mut mock_services = get_mock_services(); + + let session = session::Model { + id: Default::default(), + refresh_token: "new_refresh_token".to_string(), + access_token: "new_access_token".to_string(), + updated_at: Default::default(), + user_id: 1, + }; + + mock_services + .session_context_mock + .expect_create() + .with(predicate::eq(session.clone())) + .returning(move |_| Ok(session.clone())); + + let get_auth_token_request = Request::new(GetAuthTokenRequest { + user_credentials: None, + }); + + let res = handle_session( + Arc::new(mock_services.session_context_mock), + &get_auth_token_request, + true, + "new_access_token".to_string(), + "new_refresh_token".to_string(), + "1".to_string(), + ) + .await; + + assert!(res.is_ok()); +} + +#[tokio::test] +async fn handle_session_no_session_exists_creates_session_returns_err() { + let mut mock_services = get_mock_services(); + + let session = session::Model { + id: Default::default(), + refresh_token: "new_refresh_token".to_string(), + access_token: "new_access_token".to_string(), + updated_at: Default::default(), + user_id: 1, + }; + + mock_services + .session_context_mock + .expect_create() + .with(predicate::eq(session.clone())) + .returning(move |_| Err(DbErr::RecordNotInserted)); + + let get_auth_token_request = Request::new(GetAuthTokenRequest { + user_credentials: None, + }); + + let res = handle_session( + Arc::new(mock_services.session_context_mock), + &get_auth_token_request, + true, + "new_access_token".to_string(), + "new_refresh_token".to_string(), + "1".to_string(), + ) + .await; + + assert_eq!(res.unwrap_err().code(), Code::Internal); +} diff --git a/src/tests/api/user_logic.rs b/src/tests/api/user_logic.rs new file mode 100644 index 0000000..0052ea7 --- /dev/null +++ b/src/tests/api/user_logic.rs @@ -0,0 +1,293 @@ +use crate::api::server::server::ecdar_api_auth_server::EcdarApiAuth; +use crate::api::server::server::ecdar_api_server::EcdarApi; +use crate::api::server::server::{CreateUserRequest, UpdateUserRequest}; +use crate::entities::user; +use crate::tests::api::helpers::{get_mock_concrete_ecdar_api, get_mock_services}; +use mockall::predicate; +use sea_orm::DbErr; +use std::str::FromStr; +use tonic::{metadata, Code, Request}; + +#[tokio::test] +async fn delete_user_nonexistent_user_returns_err() { + let mut mock_services = get_mock_services(); + + mock_services + .user_context_mock + .expect_delete() + .with(predicate::eq(1)) + .returning(|_| Err(DbErr::RecordNotFound("".into()))); + + let api = get_mock_concrete_ecdar_api(mock_services); + + let mut delete_request = Request::new(()); + + // Insert uid into request metadata + delete_request + .metadata_mut() + .insert("uid", metadata::MetadataValue::from_str("1").unwrap()); + + let delete_response = api.delete_user(delete_request).await.unwrap_err(); + let expected_response_code = Code::Internal; + + assert_eq!(delete_response.code(), expected_response_code); +} + +#[tokio::test] +async fn delete_user_existing_user_returns_ok() { + let mut mock_services = get_mock_services(); + + let user = user::Model { + id: 1, + email: "".to_string(), + username: "".to_string(), + password: "".to_string(), + }; + + mock_services + .user_context_mock + .expect_delete() + .with(predicate::eq(1)) + .returning(move |_| Ok(user.clone())); + + let api = get_mock_concrete_ecdar_api(mock_services); + + let mut delete_request = Request::new(()); + + // Insert uid into request metadata + delete_request + .metadata_mut() + .insert("uid", metadata::MetadataValue::from_str("1").unwrap()); + + let delete_response = api.delete_user(delete_request).await; + + assert!(delete_response.is_ok()); +} + +#[tokio::test] +async fn create_user_nonexistent_user_returns_ok() { + let mut mock_services = get_mock_services(); + + let user = user::Model { + id: Default::default(), + email: "anders21@student.aau.dk".to_string(), + username: "anders".to_string(), + password: "123".to_string(), + }; + + mock_services + .user_context_mock + .expect_create() + .with(predicate::eq(user.clone())) + .returning(move |_| Ok(user.clone())); + + let api = get_mock_concrete_ecdar_api(mock_services); + + let create_user_request = Request::new(CreateUserRequest { + email: "anders21@student.aau.dk".to_string(), + username: "anders".to_string(), + password: "123".to_string(), + }); + + let create_user_response = api.create_user(create_user_request).await; + assert!(create_user_response.is_ok()); +} + +#[tokio::test] +async fn create_user_duplicate_email_returns_error() { + let mut mock_services = get_mock_services(); + + let user = user::Model { + id: Default::default(), + email: "anders21@student.aau.dk".to_string(), + username: "anders".to_string(), + password: "".to_string(), + }; + + mock_services + .user_context_mock + .expect_create() + .with(predicate::eq(user.clone())) + .returning(move |_| Err(DbErr::RecordNotInserted)); //todo!("Needs to be a SqlError with UniqueConstraintViolation with 'email' in message) + + let api = get_mock_concrete_ecdar_api(mock_services); + + let create_user_request = Request::new(CreateUserRequest { + email: "anders21@student.aau.dk".to_string(), + username: "anders".to_string(), + password: "".to_string(), + }); + + let res = api.create_user(create_user_request).await; + assert_eq!(res.unwrap_err().code(), Code::Internal); //todo!("Needs to be code AlreadyExists when mocked Error is corrected) +} + +#[tokio::test] +async fn create_user_invalid_email_returns_error() { + let mock_services = get_mock_services(); + + let api = get_mock_concrete_ecdar_api(mock_services); + + let create_user_request = Request::new(CreateUserRequest { + email: "invalid-email".to_string(), + username: "newuser".to_string(), + password: "123".to_string(), + }); + + let res = api.create_user(create_user_request).await; + assert_eq!(res.unwrap_err().code(), Code::InvalidArgument); +} + +#[tokio::test] +async fn create_user_duplicate_username_returns_error() { + let mut mock_services = get_mock_services(); + + let user = user::Model { + id: Default::default(), + email: "anders21@student.aau.dk".to_string(), + username: "anders".to_string(), + password: "".to_string(), + }; + + mock_services + .user_context_mock + .expect_create() + .with(predicate::eq(user.clone())) + .returning(move |_| Err(DbErr::RecordNotInserted)); //todo!("Needs to be a SqlError with UniqueConstraintViolation with 'username' in message) + + let api = get_mock_concrete_ecdar_api(mock_services); + + let create_user_request = Request::new(CreateUserRequest { + email: "anders21@student.aau.dk".to_string(), + username: "anders".to_string(), + password: "".to_string(), + }); + + let res = api.create_user(create_user_request).await; + assert_eq!(res.unwrap_err().code(), Code::Internal); //todo!("Needs to be code AlreadyExists when mocked Error is corrected) +} + +#[tokio::test] +async fn create_user_invalid_username_returns_error() { + let mock_services = get_mock_services(); + + let api = get_mock_concrete_ecdar_api(mock_services); + + let create_user_request = Request::new(CreateUserRequest { + email: "valid@email.com".to_string(), + username: "ØØØØØ".to_string(), + password: "123".to_string(), + }); + + let res = api.create_user(create_user_request).await; + assert_eq!(res.unwrap_err().code(), Code::InvalidArgument); +} + +#[tokio::test] +async fn test_create_user_valid_request_returns_ok() { + let mut mock_services = get_mock_services(); + + let user = user::Model { + id: Default::default(), + email: "newuser@example.com".to_string(), + username: "newuser".to_string(), + password: "StrongPassword123".to_string(), + }; + + mock_services + .user_context_mock + .expect_create() + .with(predicate::eq(user.clone())) + .returning(move |_| Ok(user.clone())); + + let api = get_mock_concrete_ecdar_api(mock_services); + + let create_user_request = Request::new(CreateUserRequest { + email: "newuser@example.com".to_string(), + username: "newuser".to_string(), + password: "StrongPassword123".to_string(), + }); + + let create_user_response = api.create_user(create_user_request).await; + assert!(create_user_response.is_ok()); +} + +#[tokio::test] +async fn update_user_returns_ok() { + let mut mock_services = get_mock_services(); + + let old_user = user::Model { + id: 1, + email: "olduser@example.com".to_string(), + username: "old_username".to_string(), + password: "StrongPassword123".to_string(), + }; + + let new_user = user::Model { + id: 1, + email: "newuser@example.com".to_string(), + username: "new_username".to_string(), + password: "g76df2gd7hd837g8hjd8723hd8gd823d82d3".to_string(), + }; + + mock_services + .user_context_mock + .expect_get_by_id() + .with(predicate::eq(1)) + .returning(move |_| Ok(Some(old_user.clone()))); + + mock_services + .hashing_context_mock + .expect_hash_password() + .with(predicate::eq("StrongPassword123".to_string())) + .returning(move |_| "g76df2gd7hd837g8hjd8723hd8gd823d82d3".to_string()); + + mock_services + .user_context_mock + .expect_update() + .with(predicate::eq(new_user.clone())) + .returning(move |_| Ok(new_user.clone())); + + let api = get_mock_concrete_ecdar_api(mock_services); + + let mut update_user_request = Request::new(UpdateUserRequest { + email: Some("newuser@example.com".to_string()), + username: Some("new_username".to_string()), + password: Some("StrongPassword123".to_string()), + }); + + update_user_request + .metadata_mut() + .insert("uid", metadata::MetadataValue::from_str("1").unwrap()); + + let update_user_response = api.update_user(update_user_request).await; + + assert!(update_user_response.is_ok()) +} + +#[tokio::test] +async fn update_user_non_existant_user_returns_err() { + let mut mock_services = get_mock_services(); + + mock_services + .user_context_mock + .expect_get_by_id() + .with(predicate::eq(1)) + .returning(move |_| Err(DbErr::RecordNotFound("".to_string()))); + + let api = get_mock_concrete_ecdar_api(mock_services); + + let mut update_user_request = Request::new(UpdateUserRequest { + email: Some("new_test@test".to_string()), + username: Some("new_test_user".to_string()), + password: Some("new_test_pass".to_string()), + }); + + update_user_request + .metadata_mut() + .insert("uid", metadata::MetadataValue::from_str("1").unwrap()); + + let res = api.update_user(update_user_request).await; + + assert_eq!(res.unwrap_err().code(), Code::Internal); +} diff --git a/src/tests/database/access_context.rs b/src/tests/database/access_context.rs index 4a49a83..0fda812 100644 --- a/src/tests/database/access_context.rs +++ b/src/tests/database/access_context.rs @@ -1,344 +1,341 @@ -#[cfg(test)] -mod database_tests { - use crate::tests::database::helpers::{ - create_accesses, create_models, create_users, get_reset_database_context, - }; - use crate::{ - database::{access_context::AccessContext, entity_context::EntityContextTrait}, - entities::{access, model, user}, - to_active_models, - }; - use sea_orm::{entity::prelude::*, IntoActiveModel}; +use crate::tests::database::helpers::{ + create_accesses, create_models, create_users, get_reset_database_context, +}; +use crate::{ + database::{access_context::AccessContext, entity_context::EntityContextTrait}, + entities::{access, model, user}, + to_active_models, +}; +use sea_orm::{entity::prelude::*, IntoActiveModel}; + +async fn seed_db() -> (AccessContext, access::Model, user::Model, model::Model) { + let db_context = get_reset_database_context().await; + + let access_context = AccessContext::new(db_context); + + let user = create_users(1)[0].clone(); + let model = create_models(1, user.id)[0].clone(); + let access = create_accesses(1, user.id, model.id)[0].clone(); + + user::Entity::insert(user.clone().into_active_model()) + .exec(&access_context.db_context.get_connection()) + .await + .unwrap(); + model::Entity::insert(model.clone().into_active_model()) + .exec(&access_context.db_context.get_connection()) + .await + .unwrap(); + + (access_context, access, user, model) +} +// Test the functionality of the 'create' function, which creates a access in the database +#[tokio::test] +async fn create_test() { + let (access_context, access, _, _) = seed_db().await; + + let created_access = access_context.create(access.clone()).await.unwrap(); + + let fetched_access = access::Entity::find_by_id(created_access.id) + .one(&access_context.db_context.get_connection()) + .await + .unwrap() + .unwrap(); + + // Assert if the fetched access is the same as the created access + assert_eq!(access, created_access); + assert_eq!(fetched_access, created_access); +} - async fn seed_db() -> (AccessContext, access::Model, user::Model, model::Model) { - let db_context = get_reset_database_context().await; +#[tokio::test] +async fn create_check_unique_pair_model_id_user_id_test() { + let (access_context, access, _, _) = seed_db().await; - let access_context = AccessContext::new(db_context); + let _created_access_1 = access_context.create(access.clone()).await.unwrap(); + let _created_access_2 = access_context.create(access.clone()).await; - let user = create_users(1)[0].clone(); - let model = create_models(1, user.id)[0].clone(); - let access = create_accesses(1, user.id, model.id)[0].clone(); + assert!(matches!( + _created_access_2.unwrap_err().sql_err(), + Some(SqlErr::UniqueConstraintViolation(_)) + )); +} - user::Entity::insert(user.clone().into_active_model()) - .exec(&access_context.db_context.get_connection()) - .await - .unwrap(); - model::Entity::insert(model.clone().into_active_model()) - .exec(&access_context.db_context.get_connection()) - .await - .unwrap(); +#[tokio::test] +async fn create_invalid_role_test() { + let (access_context, mut access, _, _) = seed_db().await; - (access_context, access, user, model) - } - // Test the functionality of the 'create' function, which creates a access in the database - #[tokio::test] - async fn create_test() { - let (access_context, access, _, _) = seed_db().await; - - let created_access = access_context.create(access.clone()).await.unwrap(); - - let fetched_access = access::Entity::find_by_id(created_access.id) - .one(&access_context.db_context.get_connection()) - .await - .unwrap() - .unwrap(); - - // Assert if the fetched access is the same as the created access - assert_eq!(access, created_access); - assert_eq!(fetched_access, created_access); - } + access.role = "abc".into(); - #[tokio::test] - async fn create_check_unique_pair_model_id_user_id_test() { - let (access_context, access, _, _) = seed_db().await; + let created_access = access_context.create(access.clone()).await; - let _created_access_1 = access_context.create(access.clone()).await.unwrap(); - let _created_access_2 = access_context.create(access.clone()).await; + assert!(matches!( + created_access.unwrap_err().sql_err(), + Some(SqlErr::ForeignKeyConstraintViolation(_)) + )); +} - assert!(matches!( - _created_access_2.unwrap_err().sql_err(), - Some(SqlErr::UniqueConstraintViolation(_)) - )); - } +#[tokio::test] +async fn create_auto_increment_test() { + let (access_context, _, user, model_1) = seed_db().await; - #[tokio::test] - async fn create_invalid_role_test() { - let (access_context, mut access, _, _) = seed_db().await; + let mut model_2 = create_models(1, user.id)[0].clone(); + model_2.id = model_1.id + 1; - access.role = "abc".into(); + model::Entity::insert(model_2.into_active_model()) + .exec(&access_context.db_context.get_connection()) + .await + .unwrap(); - let created_access = access_context.create(access.clone()).await; + let access_1 = access::Model { + id: 0, + role: "Editor".to_string(), + model_id: 1, + user_id: user.id, + }; - assert!(matches!( - created_access.unwrap_err().sql_err(), - Some(SqlErr::ForeignKeyConstraintViolation(_)) - )); - } + let access_2 = access::Model { + id: 0, + role: "Editor".to_string(), + model_id: 2, + user_id: user.id, + }; - #[tokio::test] - async fn create_auto_increment_test() { - let (access_context, _, user, model_1) = seed_db().await; - - let mut model_2 = create_models(1, user.id)[0].clone(); - model_2.id = model_1.id + 1; - - model::Entity::insert(model_2.into_active_model()) - .exec(&access_context.db_context.get_connection()) - .await - .unwrap(); - - let access_1 = access::Model { - id: 0, - role: "Editor".to_string(), - model_id: 1, - user_id: user.id, - }; - - let access_2 = access::Model { - id: 0, - role: "Editor".to_string(), - model_id: 2, - user_id: user.id, - }; - - let created_access1 = access_context.create(access_1.clone()).await.unwrap(); - let created_access2 = access_context.create(access_2.clone()).await.unwrap(); - - let fetched_access1 = access::Entity::find_by_id(created_access1.id) - .one(&access_context.db_context.get_connection()) - .await - .unwrap() - .unwrap(); - - let fetched_access2 = access::Entity::find_by_id(created_access2.id) - .one(&access_context.db_context.get_connection()) - .await - .unwrap() - .unwrap(); - - assert_ne!(fetched_access1.id, fetched_access2.id); - assert_ne!(created_access1.id, created_access2.id); - assert_eq!(created_access1.id, fetched_access1.id); - assert_eq!(created_access2.id, fetched_access2.id); - } + let created_access1 = access_context.create(access_1.clone()).await.unwrap(); + let created_access2 = access_context.create(access_2.clone()).await.unwrap(); + + let fetched_access1 = access::Entity::find_by_id(created_access1.id) + .one(&access_context.db_context.get_connection()) + .await + .unwrap() + .unwrap(); + + let fetched_access2 = access::Entity::find_by_id(created_access2.id) + .one(&access_context.db_context.get_connection()) + .await + .unwrap() + .unwrap(); + + assert_ne!(fetched_access1.id, fetched_access2.id); + assert_ne!(created_access1.id, created_access2.id); + assert_eq!(created_access1.id, fetched_access1.id); + assert_eq!(created_access2.id, fetched_access2.id); +} - #[tokio::test] - async fn get_by_id_test() { - let (access_context, access, _, _) = seed_db().await; +#[tokio::test] +async fn get_by_id_test() { + let (access_context, access, _, _) = seed_db().await; - access::Entity::insert(access.clone().into_active_model()) - .exec(&access_context.db_context.get_connection()) - .await - .unwrap(); + access::Entity::insert(access.clone().into_active_model()) + .exec(&access_context.db_context.get_connection()) + .await + .unwrap(); - // Fetches the access created using the 'get_by_id' function - let fetched_access = access_context.get_by_id(access.id).await.unwrap().unwrap(); + // Fetches the access created using the 'get_by_id' function + let fetched_access = access_context.get_by_id(access.id).await.unwrap().unwrap(); - // Assert if the fetched access is the same as the created access - assert_eq!(access, fetched_access); - } + // Assert if the fetched access is the same as the created access + assert_eq!(access, fetched_access); +} - #[tokio::test] - async fn get_by_non_existing_id_test() { - let (access_context, _, _, _) = seed_db().await; +#[tokio::test] +async fn get_by_non_existing_id_test() { + let (access_context, _, _, _) = seed_db().await; - let fetched_access = access_context.get_by_id(1).await.unwrap(); + let fetched_access = access_context.get_by_id(1).await.unwrap(); - assert!(fetched_access.is_none()); - } + assert!(fetched_access.is_none()); +} - #[tokio::test] - async fn get_all_test() { - let (access_context, _, user, model) = seed_db().await; +#[tokio::test] +async fn get_all_test() { + let (access_context, _, user, model) = seed_db().await; - // Creates a model of the access which will be created - let new_accesses = create_accesses(1, user.id, model.id); + // Creates a model of the access which will be created + let new_accesses = create_accesses(1, user.id, model.id); - // Creates the access in the database using the 'create' function - access::Entity::insert_many(to_active_models!(new_accesses.clone())) - .exec(&access_context.db_context.get_connection()) - .await - .unwrap(); + // Creates the access in the database using the 'create' function + access::Entity::insert_many(to_active_models!(new_accesses.clone())) + .exec(&access_context.db_context.get_connection()) + .await + .unwrap(); - assert_eq!(access_context.get_all().await.unwrap().len(), 1); + assert_eq!(access_context.get_all().await.unwrap().len(), 1); - let mut sorted: Vec = new_accesses.clone(); - sorted.sort_by_key(|k| k.id); + let mut sorted: Vec = new_accesses.clone(); + sorted.sort_by_key(|k| k.id); - for (i, access) in sorted.into_iter().enumerate() { - assert_eq!(access, new_accesses[i]); - } + for (i, access) in sorted.into_iter().enumerate() { + assert_eq!(access, new_accesses[i]); } +} - #[tokio::test] - async fn get_all_empty_test() { - let (access_context, _, _, _) = seed_db().await; +#[tokio::test] +async fn get_all_empty_test() { + let (access_context, _, _, _) = seed_db().await; - let result = access_context.get_all().await.unwrap(); - let empty_accesses: Vec = vec![]; + let result = access_context.get_all().await.unwrap(); + let empty_accesses: Vec = vec![]; - assert_eq!(empty_accesses, result); - } + assert_eq!(empty_accesses, result); +} - #[tokio::test] - async fn update_test() { - let (access_context, access, _, _) = seed_db().await; +#[tokio::test] +async fn update_test() { + let (access_context, access, _, _) = seed_db().await; - access::Entity::insert(access.clone().into_active_model()) - .exec(&access_context.db_context.get_connection()) - .await - .unwrap(); + access::Entity::insert(access.clone().into_active_model()) + .exec(&access_context.db_context.get_connection()) + .await + .unwrap(); - let new_access = access::Model { ..access }; + let new_access = access::Model { ..access }; - let updated_access = access_context.update(new_access.clone()).await.unwrap(); + let updated_access = access_context.update(new_access.clone()).await.unwrap(); - let fetched_access = access::Entity::find_by_id(updated_access.id) - .one(&access_context.db_context.get_connection()) - .await - .unwrap() - .unwrap(); + let fetched_access = access::Entity::find_by_id(updated_access.id) + .one(&access_context.db_context.get_connection()) + .await + .unwrap() + .unwrap(); - assert_eq!(new_access, updated_access); - assert_eq!(updated_access, fetched_access); - } + assert_eq!(new_access, updated_access); + assert_eq!(updated_access, fetched_access); +} - #[tokio::test] - async fn update_modifies_role_test() { - let (access_context, access, _, _) = seed_db().await; +#[tokio::test] +async fn update_modifies_role_test() { + let (access_context, access, _, _) = seed_db().await; - let access = access::Model { - role: "Editor".into(), - ..access - }; + let access = access::Model { + role: "Editor".into(), + ..access + }; - access::Entity::insert(access.clone().into_active_model()) - .exec(&access_context.db_context.get_connection()) - .await - .unwrap(); + access::Entity::insert(access.clone().into_active_model()) + .exec(&access_context.db_context.get_connection()) + .await + .unwrap(); - let new_access = access::Model { - role: "Commenter".into(), - ..access - }; + let new_access = access::Model { + role: "Commenter".into(), + ..access + }; - let updated_access = access_context.update(new_access.clone()).await.unwrap(); + let updated_access = access_context.update(new_access.clone()).await.unwrap(); - assert_ne!(access, updated_access); - assert_ne!(access, new_access); - } + assert_ne!(access, updated_access); + assert_ne!(access, new_access); +} - #[tokio::test] - async fn update_does_not_modify_id_test() { - let (access_context, access, _, _) = seed_db().await; - access::Entity::insert(access.clone().into_active_model()) - .exec(&access_context.db_context.get_connection()) - .await - .unwrap(); - - let updated_access = access::Model { - id: &access.id + 1, - ..access.clone() - }; - let res = access_context.update(updated_access.clone()).await; - - assert!(matches!(res.unwrap_err(), DbErr::RecordNotUpdated)); - } - #[tokio::test] - async fn update_does_not_modify_model_id_test() { - let (access_context, access, _, _) = seed_db().await; - - access::Entity::insert(access.clone().into_active_model()) - .exec(&access_context.db_context.get_connection()) - .await - .unwrap(); - - let updated_access = access::Model { - model_id: &access.model_id + 1, - ..access.clone() - }; - let res = access_context.update(updated_access.clone()).await.unwrap(); - - assert_eq!(access, res); - } - #[tokio::test] - async fn update_does_not_modify_user_id_test() { - let (access_context, access, _, _) = seed_db().await; - - access::Entity::insert(access.clone().into_active_model()) - .exec(&access_context.db_context.get_connection()) - .await - .unwrap(); - - let updated_access = access::Model { - user_id: &access.user_id + 1, - ..access.clone() - }; - let res = access_context.update(updated_access.clone()).await.unwrap(); - - assert_eq!(access, res); - } +#[tokio::test] +async fn update_does_not_modify_id_test() { + let (access_context, access, _, _) = seed_db().await; + access::Entity::insert(access.clone().into_active_model()) + .exec(&access_context.db_context.get_connection()) + .await + .unwrap(); + + let updated_access = access::Model { + id: &access.id + 1, + ..access.clone() + }; + let res = access_context.update(updated_access.clone()).await; - #[tokio::test] - async fn update_invalid_role_test() { - let (access_context, mut access, _, _) = seed_db().await; + assert!(matches!(res.unwrap_err(), DbErr::RecordNotUpdated)); +} +#[tokio::test] +async fn update_does_not_modify_model_id_test() { + let (access_context, access, _, _) = seed_db().await; + + access::Entity::insert(access.clone().into_active_model()) + .exec(&access_context.db_context.get_connection()) + .await + .unwrap(); + + let updated_access = access::Model { + model_id: &access.model_id + 1, + ..access.clone() + }; + let res = access_context.update(updated_access.clone()).await.unwrap(); - access::Entity::insert(access.clone().into_active_model()) - .exec(&access_context.db_context.get_connection()) - .await - .unwrap(); + assert_eq!(access, res); +} +#[tokio::test] +async fn update_does_not_modify_user_id_test() { + let (access_context, access, _, _) = seed_db().await; + + access::Entity::insert(access.clone().into_active_model()) + .exec(&access_context.db_context.get_connection()) + .await + .unwrap(); + + let updated_access = access::Model { + user_id: &access.user_id + 1, + ..access.clone() + }; + let res = access_context.update(updated_access.clone()).await.unwrap(); - access.role = "abc".into(); + assert_eq!(access, res); +} - let updated_access = access_context.update(access.clone()).await; +#[tokio::test] +async fn update_invalid_role_test() { + let (access_context, mut access, _, _) = seed_db().await; - assert!(matches!( - updated_access.unwrap_err().sql_err(), - Some(SqlErr::ForeignKeyConstraintViolation(_)) - )); - } + access::Entity::insert(access.clone().into_active_model()) + .exec(&access_context.db_context.get_connection()) + .await + .unwrap(); - #[tokio::test] - async fn update_non_existing_id_test() { - let (access_context, access, _, _) = seed_db().await; + access.role = "abc".into(); - let updated_access = access_context.update(access.clone()).await; + let updated_access = access_context.update(access.clone()).await; - assert!(matches!( - updated_access.unwrap_err(), - DbErr::RecordNotUpdated - )); - } + assert!(matches!( + updated_access.unwrap_err().sql_err(), + Some(SqlErr::ForeignKeyConstraintViolation(_)) + )); +} - #[tokio::test] - async fn delete_test() { - let (access_context, access, _, _) = seed_db().await; +#[tokio::test] +async fn update_non_existing_id_test() { + let (access_context, access, _, _) = seed_db().await; - access::Entity::insert(access.clone().into_active_model()) - .exec(&access_context.db_context.get_connection()) - .await - .unwrap(); + let updated_access = access_context.update(access.clone()).await; - let deleted_access = access_context.delete(access.id).await.unwrap(); + assert!(matches!( + updated_access.unwrap_err(), + DbErr::RecordNotUpdated + )); +} - let all_accesses = access::Entity::find() - .all(&access_context.db_context.get_connection()) - .await - .unwrap(); +#[tokio::test] +async fn delete_test() { + let (access_context, access, _, _) = seed_db().await; - assert_eq!(access, deleted_access); - assert!(all_accesses.is_empty()); - } + access::Entity::insert(access.clone().into_active_model()) + .exec(&access_context.db_context.get_connection()) + .await + .unwrap(); - #[tokio::test] - async fn delete_non_existing_id_test() { - let (access_context, _, _, _) = seed_db().await; + let deleted_access = access_context.delete(access.id).await.unwrap(); - let deleted_access = access_context.delete(1).await; + let all_accesses = access::Entity::find() + .all(&access_context.db_context.get_connection()) + .await + .unwrap(); - assert!(matches!( - deleted_access.unwrap_err(), - DbErr::RecordNotFound(_) - )); - } + assert_eq!(access, deleted_access); + assert!(all_accesses.is_empty()); +} + +#[tokio::test] +async fn delete_non_existing_id_test() { + let (access_context, _, _, _) = seed_db().await; + + let deleted_access = access_context.delete(1).await; + + assert!(matches!( + deleted_access.unwrap_err(), + DbErr::RecordNotFound(_) + )); } diff --git a/src/tests/database/in_use_context.rs b/src/tests/database/in_use_context.rs index 44180dd..a62f6b5 100644 --- a/src/tests/database/in_use_context.rs +++ b/src/tests/database/in_use_context.rs @@ -1,279 +1,276 @@ -#[cfg(test)] -mod database_tests { - use crate::tests::database::helpers::*; - use crate::{ - database::{ - entity_context::EntityContextTrait, - in_use_context::{DbErr, InUseContext}, - }, - entities::{in_use, model, session, user}, - to_active_models, - }; - use chrono::{Duration, Utc}; - use sea_orm::{entity::prelude::*, IntoActiveModel}; - use std::matches; - use std::ops::Add; - - async fn seed_db() -> ( - InUseContext, - in_use::Model, - session::Model, - model::Model, - user::Model, - ) { - let db_context = get_reset_database_context().await; - - let in_use_context = InUseContext::new(db_context); - - let user = create_users(1)[0].clone(); - let model = create_models(1, user.id)[0].clone(); - let session = create_sessions(1, user.id)[0].clone(); - let in_use = create_in_uses(1, model.id, session.id)[0].clone(); - - user::Entity::insert(user.clone().into_active_model()) - .exec(&in_use_context.db_context.get_connection()) - .await - .unwrap(); - model::Entity::insert(model.clone().into_active_model()) - .exec(&in_use_context.db_context.get_connection()) - .await - .unwrap(); - session::Entity::insert(session.clone().into_active_model()) - .exec(&in_use_context.db_context.get_connection()) - .await - .unwrap(); - - (in_use_context, in_use, session, model, user) - } +use crate::tests::database::helpers::*; +use crate::{ + database::{ + entity_context::EntityContextTrait, + in_use_context::{DbErr, InUseContext}, + }, + entities::{in_use, model, session, user}, + to_active_models, +}; +use chrono::{Duration, Utc}; +use sea_orm::{entity::prelude::*, IntoActiveModel}; +use std::matches; +use std::ops::Add; + +async fn seed_db() -> ( + InUseContext, + in_use::Model, + session::Model, + model::Model, + user::Model, +) { + let db_context = get_reset_database_context().await; + + let in_use_context = InUseContext::new(db_context); + + let user = create_users(1)[0].clone(); + let model = create_models(1, user.id)[0].clone(); + let session = create_sessions(1, user.id)[0].clone(); + let in_use = create_in_uses(1, model.id, session.id)[0].clone(); + + user::Entity::insert(user.clone().into_active_model()) + .exec(&in_use_context.db_context.get_connection()) + .await + .unwrap(); + model::Entity::insert(model.clone().into_active_model()) + .exec(&in_use_context.db_context.get_connection()) + .await + .unwrap(); + session::Entity::insert(session.clone().into_active_model()) + .exec(&in_use_context.db_context.get_connection()) + .await + .unwrap(); + + (in_use_context, in_use, session, model, user) +} - #[tokio::test] - async fn create_test() { - let (in_use_context, mut in_use, _, _, _) = seed_db().await; +#[tokio::test] +async fn create_test() { + let (in_use_context, mut in_use, _, _, _) = seed_db().await; - let inserted_in_use = in_use_context.create(in_use.clone()).await.unwrap(); + let inserted_in_use = in_use_context.create(in_use.clone()).await.unwrap(); - in_use.latest_activity = inserted_in_use.latest_activity; + in_use.latest_activity = inserted_in_use.latest_activity; - let fetched_in_use = in_use::Entity::find_by_id(inserted_in_use.clone().model_id) - .one(&in_use_context.db_context.get_connection()) - .await - .unwrap() - .unwrap(); + let fetched_in_use = in_use::Entity::find_by_id(inserted_in_use.clone().model_id) + .one(&in_use_context.db_context.get_connection()) + .await + .unwrap() + .unwrap(); - assert_eq!(in_use, inserted_in_use); - assert_eq!(in_use, fetched_in_use); - } + assert_eq!(in_use, inserted_in_use); + assert_eq!(in_use, fetched_in_use); +} - #[tokio::test] - async fn create_default_latest_activity_test() { - let t_min = Utc::now().timestamp(); +#[tokio::test] +async fn create_default_latest_activity_test() { + let t_min = Utc::now().timestamp(); - let (in_use_context, in_use, _, _, _) = seed_db().await; + let (in_use_context, in_use, _, _, _) = seed_db().await; - let inserted_in_use = in_use_context.create(in_use.clone()).await.unwrap(); + let inserted_in_use = in_use_context.create(in_use.clone()).await.unwrap(); - let fetched_in_use = in_use::Entity::find_by_id(inserted_in_use.model_id) - .one(&in_use_context.db_context.get_connection()) - .await - .unwrap() - .unwrap(); + let fetched_in_use = in_use::Entity::find_by_id(inserted_in_use.model_id) + .one(&in_use_context.db_context.get_connection()) + .await + .unwrap() + .unwrap(); - let t_max = Utc::now().timestamp(); + let t_max = Utc::now().timestamp(); - let t_actual = fetched_in_use.clone().latest_activity.timestamp(); + let t_actual = fetched_in_use.clone().latest_activity.timestamp(); - assert!(t_min <= t_actual && t_actual <= t_max) - } + assert!(t_min <= t_actual && t_actual <= t_max) +} - #[tokio::test] - async fn get_by_id_test() { - let (in_use_context, in_use, _, _, _) = seed_db().await; +#[tokio::test] +async fn get_by_id_test() { + let (in_use_context, in_use, _, _, _) = seed_db().await; - in_use::Entity::insert(in_use.clone().into_active_model()) - .exec(&in_use_context.db_context.get_connection()) - .await - .unwrap(); + in_use::Entity::insert(in_use.clone().into_active_model()) + .exec(&in_use_context.db_context.get_connection()) + .await + .unwrap(); - let fetched_in_use = in_use_context - .get_by_id(in_use.model_id) - .await - .unwrap() - .unwrap(); + let fetched_in_use = in_use_context + .get_by_id(in_use.model_id) + .await + .unwrap() + .unwrap(); - assert_eq!(fetched_in_use, in_use) - } + assert_eq!(fetched_in_use, in_use) +} - #[tokio::test] - async fn get_by_non_existing_id_test() { - let (in_use_context, _in_use, _, _, _) = seed_db().await; +#[tokio::test] +async fn get_by_non_existing_id_test() { + let (in_use_context, _in_use, _, _, _) = seed_db().await; - let in_use = in_use_context.get_by_id(1).await; + let in_use = in_use_context.get_by_id(1).await; - assert!(in_use.unwrap().is_none()) - } + assert!(in_use.unwrap().is_none()) +} - #[tokio::test] - async fn get_all_test() { - let (in_use_context, _in_use, session, model, user) = seed_db().await; +#[tokio::test] +async fn get_all_test() { + let (in_use_context, _in_use, session, model, user) = seed_db().await; - let mut models = create_models(2, user.id); - models[0].id = 3; + let mut models = create_models(2, user.id); + models[0].id = 3; - let in_uses = create_in_uses(3, model.id, session.id); + let in_uses = create_in_uses(3, model.id, session.id); - model::Entity::insert_many(to_active_models!(models.clone())) - .exec(&in_use_context.db_context.get_connection()) - .await - .unwrap(); + model::Entity::insert_many(to_active_models!(models.clone())) + .exec(&in_use_context.db_context.get_connection()) + .await + .unwrap(); - in_use::Entity::insert_many(to_active_models!(in_uses.clone())) - .exec(&in_use_context.db_context.get_connection()) - .await - .unwrap(); + in_use::Entity::insert_many(to_active_models!(in_uses.clone())) + .exec(&in_use_context.db_context.get_connection()) + .await + .unwrap(); - assert_eq!(in_use_context.get_all().await.unwrap().len(), 3); + assert_eq!(in_use_context.get_all().await.unwrap().len(), 3); - let mut sorted = in_uses.clone(); - sorted.sort_by_key(|k| k.model_id); + let mut sorted = in_uses.clone(); + sorted.sort_by_key(|k| k.model_id); - for (i, in_use) in sorted.into_iter().enumerate() { - assert_eq!(in_use, in_uses[i]); - } + for (i, in_use) in sorted.into_iter().enumerate() { + assert_eq!(in_use, in_uses[i]); } +} - #[tokio::test] - async fn get_all_empty_test() { - let (in_use_context, _, _, _, _) = seed_db().await; +#[tokio::test] +async fn get_all_empty_test() { + let (in_use_context, _, _, _, _) = seed_db().await; - let in_uses = in_use_context.get_all().await.unwrap(); + let in_uses = in_use_context.get_all().await.unwrap(); - assert_eq!(0, in_uses.len()) - } + assert_eq!(0, in_uses.len()) +} - #[tokio::test] - async fn update_test() { - let (in_use_context, in_use, _, _, _) = seed_db().await; +#[tokio::test] +async fn update_test() { + let (in_use_context, in_use, _, _, _) = seed_db().await; - in_use::Entity::insert(in_use.clone().into_active_model()) - .exec(&in_use_context.db_context.get_connection()) - .await - .unwrap(); + in_use::Entity::insert(in_use.clone().into_active_model()) + .exec(&in_use_context.db_context.get_connection()) + .await + .unwrap(); - let new_in_use = in_use::Model { ..in_use }; + let new_in_use = in_use::Model { ..in_use }; - let updated_in_use = in_use_context.update(new_in_use.clone()).await.unwrap(); + let updated_in_use = in_use_context.update(new_in_use.clone()).await.unwrap(); - let fetched_in_use = in_use::Entity::find_by_id(updated_in_use.model_id) - .one(&in_use_context.db_context.get_connection()) - .await - .unwrap() - .unwrap(); + let fetched_in_use = in_use::Entity::find_by_id(updated_in_use.model_id) + .one(&in_use_context.db_context.get_connection()) + .await + .unwrap() + .unwrap(); - assert_eq!(new_in_use, updated_in_use); - assert_eq!(updated_in_use, fetched_in_use); - } + assert_eq!(new_in_use, updated_in_use); + assert_eq!(updated_in_use, fetched_in_use); +} - #[tokio::test] - async fn update_modifies_latest_activity_test() { - let (in_use_context, in_use, _, _, _) = seed_db().await; +#[tokio::test] +async fn update_modifies_latest_activity_test() { + let (in_use_context, in_use, _, _, _) = seed_db().await; - in_use::Entity::insert(in_use.clone().into_active_model()) - .exec(&in_use_context.db_context.get_connection()) - .await - .unwrap(); + in_use::Entity::insert(in_use.clone().into_active_model()) + .exec(&in_use_context.db_context.get_connection()) + .await + .unwrap(); - let new_in_use = in_use::Model { - latest_activity: in_use.clone().latest_activity.add(Duration::seconds(1)), - ..in_use - }; + let new_in_use = in_use::Model { + latest_activity: in_use.clone().latest_activity.add(Duration::seconds(1)), + ..in_use + }; - let updated_in_use = in_use_context.update(new_in_use.clone()).await.unwrap(); + let updated_in_use = in_use_context.update(new_in_use.clone()).await.unwrap(); - assert_ne!(in_use, updated_in_use); - assert_ne!(in_use, new_in_use); - } + assert_ne!(in_use, updated_in_use); + assert_ne!(in_use, new_in_use); +} - #[tokio::test] - async fn update_does_not_modify_model_id_test() { - let (in_use_context, in_use, _, _, _) = seed_db().await; +#[tokio::test] +async fn update_does_not_modify_model_id_test() { + let (in_use_context, in_use, _, _, _) = seed_db().await; - in_use::Entity::insert(in_use.clone().into_active_model()) - .exec(&in_use_context.db_context.get_connection()) - .await - .unwrap(); + in_use::Entity::insert(in_use.clone().into_active_model()) + .exec(&in_use_context.db_context.get_connection()) + .await + .unwrap(); - let updated_in_use = in_use::Model { - model_id: in_use.model_id + 1, - ..in_use.clone() - }; + let updated_in_use = in_use::Model { + model_id: in_use.model_id + 1, + ..in_use.clone() + }; - let updated_in_use = in_use_context.update(updated_in_use.clone()).await; + let updated_in_use = in_use_context.update(updated_in_use.clone()).await; - assert!(matches!( - updated_in_use.unwrap_err(), - DbErr::RecordNotUpdated - )); - } + assert!(matches!( + updated_in_use.unwrap_err(), + DbErr::RecordNotUpdated + )); +} - #[tokio::test] - async fn update_does_not_modify_session_id_test() { - let (in_use_context, in_use, _, _, _) = seed_db().await; +#[tokio::test] +async fn update_does_not_modify_session_id_test() { + let (in_use_context, in_use, _, _, _) = seed_db().await; - in_use::Entity::insert(in_use.clone().into_active_model()) - .exec(&in_use_context.db_context.get_connection()) - .await - .unwrap(); + in_use::Entity::insert(in_use.clone().into_active_model()) + .exec(&in_use_context.db_context.get_connection()) + .await + .unwrap(); - let updated_in_use = in_use::Model { - session_id: in_use.session_id + 1, - ..in_use.clone() - }; + let updated_in_use = in_use::Model { + session_id: in_use.session_id + 1, + ..in_use.clone() + }; - let updated_in_use = in_use_context.update(updated_in_use.clone()).await.unwrap(); - assert_eq!(in_use, updated_in_use); - } + let updated_in_use = in_use_context.update(updated_in_use.clone()).await.unwrap(); + assert_eq!(in_use, updated_in_use); +} - #[tokio::test] - async fn update_non_existing_id_test() { - let (in_use_context, in_use, _, _, _) = seed_db().await; +#[tokio::test] +async fn update_non_existing_id_test() { + let (in_use_context, in_use, _, _, _) = seed_db().await; - let updated_in_use = in_use_context.update(in_use.clone()).await; + let updated_in_use = in_use_context.update(in_use.clone()).await; - assert!(matches!( - updated_in_use.unwrap_err(), - DbErr::RecordNotUpdated - )); - } + assert!(matches!( + updated_in_use.unwrap_err(), + DbErr::RecordNotUpdated + )); +} - #[tokio::test] - async fn delete_test() { - let (in_use_context, in_use, _, _, _) = seed_db().await; +#[tokio::test] +async fn delete_test() { + let (in_use_context, in_use, _, _, _) = seed_db().await; - in_use::Entity::insert(in_use.clone().into_active_model()) - .exec(&in_use_context.db_context.get_connection()) - .await - .unwrap(); + in_use::Entity::insert(in_use.clone().into_active_model()) + .exec(&in_use_context.db_context.get_connection()) + .await + .unwrap(); - let deleted_in_use = in_use_context.delete(in_use.model_id).await.unwrap(); + let deleted_in_use = in_use_context.delete(in_use.model_id).await.unwrap(); - let all_in_uses = in_use::Entity::find() - .all(&in_use_context.db_context.get_connection()) - .await - .unwrap(); + let all_in_uses = in_use::Entity::find() + .all(&in_use_context.db_context.get_connection()) + .await + .unwrap(); - assert_eq!(in_use, deleted_in_use); - assert!(all_in_uses.is_empty()); - } + assert_eq!(in_use, deleted_in_use); + assert!(all_in_uses.is_empty()); +} - #[tokio::test] - async fn delete_non_existing_id_test() { - let (in_use_context, _, _, _, _) = seed_db().await; +#[tokio::test] +async fn delete_non_existing_id_test() { + let (in_use_context, _, _, _, _) = seed_db().await; - let deleted_in_use = in_use_context.delete(1).await; + let deleted_in_use = in_use_context.delete(1).await; - assert!(matches!( - deleted_in_use.unwrap_err(), - DbErr::RecordNotFound(_) - )) - } + assert!(matches!( + deleted_in_use.unwrap_err(), + DbErr::RecordNotFound(_) + )) } diff --git a/src/tests/database/model_context.rs b/src/tests/database/model_context.rs index 58c0368..29464d4 100644 --- a/src/tests/database/model_context.rs +++ b/src/tests/database/model_context.rs @@ -1,405 +1,402 @@ -#[cfg(test)] -mod database_tests { - use crate::tests::database::helpers::*; - use crate::{ - database::{entity_context::EntityContextTrait, model_context::ModelContext}, - entities::{access, in_use, model, query, session, user}, - to_active_models, - }; - use sea_orm::error::DbErr; - use sea_orm::{entity::prelude::*, IntoActiveModel}; - use std::matches; - - async fn seed_db() -> (ModelContext, model::Model, user::Model) { - let db_context = get_reset_database_context().await; - - let model_context = ModelContext::new(db_context); - - let user = create_users(1)[0].clone(); - let model = create_models(1, user.id)[0].clone(); - - user::Entity::insert(user.clone().into_active_model()) - .exec(&model_context.db_context.get_connection()) - .await - .unwrap(); - - (model_context, model, user) - } +use crate::tests::database::helpers::*; +use crate::{ + database::{entity_context::EntityContextTrait, model_context::ModelContext}, + entities::{access, in_use, model, query, session, user}, + to_active_models, +}; +use sea_orm::error::DbErr; +use sea_orm::{entity::prelude::*, IntoActiveModel}; +use std::matches; + +async fn seed_db() -> (ModelContext, model::Model, user::Model) { + let db_context = get_reset_database_context().await; + + let model_context = ModelContext::new(db_context); + + let user = create_users(1)[0].clone(); + let model = create_models(1, user.id)[0].clone(); + + user::Entity::insert(user.clone().into_active_model()) + .exec(&model_context.db_context.get_connection()) + .await + .unwrap(); + + (model_context, model, user) +} - #[tokio::test] - async fn create_test() { - let (model_context, model, _) = seed_db().await; +#[tokio::test] +async fn create_test() { + let (model_context, model, _) = seed_db().await; - let created_model = model_context.create(model.clone()).await.unwrap(); + let created_model = model_context.create(model.clone()).await.unwrap(); - let fetched_model = model::Entity::find_by_id(created_model.id) - .one(&model_context.db_context.get_connection()) - .await - .unwrap() - .unwrap(); + let fetched_model = model::Entity::find_by_id(created_model.id) + .one(&model_context.db_context.get_connection()) + .await + .unwrap() + .unwrap(); - assert_eq!(model, created_model); - assert_eq!(fetched_model, created_model); - } + assert_eq!(model, created_model); + assert_eq!(fetched_model, created_model); +} - #[tokio::test] - async fn create_auto_increment_test() { - let (model_context, model, _) = seed_db().await; - - let created_model1 = model_context.create(model.clone()).await.unwrap(); - let created_model2 = model_context.create(model.clone()).await.unwrap(); - - let fetched_model1 = model::Entity::find_by_id(created_model1.id) - .one(&model_context.db_context.get_connection()) - .await - .unwrap() - .unwrap(); - - let fetched_model2 = model::Entity::find_by_id(created_model2.id) - .one(&model_context.db_context.get_connection()) - .await - .unwrap() - .unwrap(); - - assert_ne!(fetched_model1.id, fetched_model2.id); - assert_ne!(created_model1.id, created_model2.id); - assert_eq!(created_model1.id, fetched_model1.id); - assert_eq!(created_model2.id, fetched_model2.id); - } +#[tokio::test] +async fn create_auto_increment_test() { + let (model_context, model, _) = seed_db().await; + + let created_model1 = model_context.create(model.clone()).await.unwrap(); + let created_model2 = model_context.create(model.clone()).await.unwrap(); + + let fetched_model1 = model::Entity::find_by_id(created_model1.id) + .one(&model_context.db_context.get_connection()) + .await + .unwrap() + .unwrap(); + + let fetched_model2 = model::Entity::find_by_id(created_model2.id) + .one(&model_context.db_context.get_connection()) + .await + .unwrap() + .unwrap(); + + assert_ne!(fetched_model1.id, fetched_model2.id); + assert_ne!(created_model1.id, created_model2.id); + assert_eq!(created_model1.id, fetched_model1.id); + assert_eq!(created_model2.id, fetched_model2.id); +} - #[tokio::test] - async fn get_by_id_test() { - let (model_context, model, _) = seed_db().await; +#[tokio::test] +async fn get_by_id_test() { + let (model_context, model, _) = seed_db().await; - model::Entity::insert(model.clone().into_active_model()) - .exec(&model_context.db_context.get_connection()) - .await - .unwrap(); + model::Entity::insert(model.clone().into_active_model()) + .exec(&model_context.db_context.get_connection()) + .await + .unwrap(); - let fetched_model = model_context.get_by_id(model.id).await.unwrap().unwrap(); + let fetched_model = model_context.get_by_id(model.id).await.unwrap().unwrap(); - assert_eq!(model, fetched_model); - } + assert_eq!(model, fetched_model); +} - #[tokio::test] - async fn get_by_non_existing_id_test() { - let (model_context, _, _) = seed_db().await; +#[tokio::test] +async fn get_by_non_existing_id_test() { + let (model_context, _, _) = seed_db().await; - let fetched_model = model_context.get_by_id(1).await.unwrap(); + let fetched_model = model_context.get_by_id(1).await.unwrap(); - assert!(fetched_model.is_none()); - } + assert!(fetched_model.is_none()); +} - #[tokio::test] - async fn get_all_test() { - let (model_context, _, user) = seed_db().await; +#[tokio::test] +async fn get_all_test() { + let (model_context, _, user) = seed_db().await; - let new_models = create_models(3, user.id); + let new_models = create_models(3, user.id); - model::Entity::insert_many(to_active_models!(new_models.clone())) - .exec(&model_context.db_context.get_connection()) - .await - .unwrap(); + model::Entity::insert_many(to_active_models!(new_models.clone())) + .exec(&model_context.db_context.get_connection()) + .await + .unwrap(); - assert_eq!(model_context.get_all().await.unwrap().len(), 3); + assert_eq!(model_context.get_all().await.unwrap().len(), 3); - let mut sorted = new_models.clone(); - sorted.sort_by_key(|k| k.id); + let mut sorted = new_models.clone(); + sorted.sort_by_key(|k| k.id); - for (i, model) in sorted.into_iter().enumerate() { - assert_eq!(model, new_models[i]); - } + for (i, model) in sorted.into_iter().enumerate() { + assert_eq!(model, new_models[i]); } +} - #[tokio::test] - async fn get_all_empty_test() { - let (model_context, _, _) = seed_db().await; +#[tokio::test] +async fn get_all_empty_test() { + let (model_context, _, _) = seed_db().await; - let result = model_context.get_all().await.unwrap(); - let empty_models: Vec = vec![]; + let result = model_context.get_all().await.unwrap(); + let empty_models: Vec = vec![]; - assert_eq!(empty_models, result); - } + assert_eq!(empty_models, result); +} - #[tokio::test] - async fn update_test() { - let (model_context, model, _) = seed_db().await; +#[tokio::test] +async fn update_test() { + let (model_context, model, _) = seed_db().await; - model::Entity::insert(model.clone().into_active_model()) - .exec(&model_context.db_context.get_connection()) - .await - .unwrap(); + model::Entity::insert(model.clone().into_active_model()) + .exec(&model_context.db_context.get_connection()) + .await + .unwrap(); - let new_model = model::Model { ..model }; + let new_model = model::Model { ..model }; - let updated_model = model_context.update(new_model.clone()).await.unwrap(); + let updated_model = model_context.update(new_model.clone()).await.unwrap(); - let fetched_model = model::Entity::find_by_id(updated_model.id) - .one(&model_context.db_context.get_connection()) - .await - .unwrap() - .unwrap(); + let fetched_model = model::Entity::find_by_id(updated_model.id) + .one(&model_context.db_context.get_connection()) + .await + .unwrap() + .unwrap(); - assert_eq!(new_model, updated_model); - assert_eq!(updated_model, fetched_model); - } + assert_eq!(new_model, updated_model); + assert_eq!(updated_model, fetched_model); +} - #[tokio::test] - async fn update_modifies_name_test() { - let (model_context, model, _) = seed_db().await; +#[tokio::test] +async fn update_modifies_name_test() { + let (model_context, model, _) = seed_db().await; - let model = model::Model { - name: "model1".into(), - ..model.clone() - }; + let model = model::Model { + name: "model1".into(), + ..model.clone() + }; - model::Entity::insert(model.clone().into_active_model()) - .exec(&model_context.db_context.get_connection()) - .await - .unwrap(); + model::Entity::insert(model.clone().into_active_model()) + .exec(&model_context.db_context.get_connection()) + .await + .unwrap(); - let new_model = model::Model { - name: "model2".into(), - ..model.clone() - }; + let new_model = model::Model { + name: "model2".into(), + ..model.clone() + }; - let updated_model = model_context.update(new_model.clone()).await.unwrap(); + let updated_model = model_context.update(new_model.clone()).await.unwrap(); - assert_ne!(model, updated_model); - assert_ne!(model, new_model); - } + assert_ne!(model, updated_model); + assert_ne!(model, new_model); +} - #[tokio::test] - async fn update_modifies_components_info_test() { - let (model_context, model, _) = seed_db().await; +#[tokio::test] +async fn update_modifies_components_info_test() { + let (model_context, model, _) = seed_db().await; - let model = model::Model { - components_info: "{\"a\":1}".to_owned().parse().unwrap(), - ..model.clone() - }; + let model = model::Model { + components_info: "{\"a\":1}".to_owned().parse().unwrap(), + ..model.clone() + }; - model::Entity::insert(model.clone().into_active_model()) - .exec(&model_context.db_context.get_connection()) - .await - .unwrap(); + model::Entity::insert(model.clone().into_active_model()) + .exec(&model_context.db_context.get_connection()) + .await + .unwrap(); - let new_model = model::Model { - components_info: "{\"a\":2}".to_owned().parse().unwrap(), - ..model.clone() - }; + let new_model = model::Model { + components_info: "{\"a\":2}".to_owned().parse().unwrap(), + ..model.clone() + }; - let updated_model = model_context.update(new_model.clone()).await.unwrap(); + let updated_model = model_context.update(new_model.clone()).await.unwrap(); - assert_ne!(model, updated_model); - assert_ne!(model, new_model); - } + assert_ne!(model, updated_model); + assert_ne!(model, new_model); +} - #[tokio::test] - async fn update_does_not_modify_id_test() { - let (model_context, model, _) = seed_db().await; +#[tokio::test] +async fn update_does_not_modify_id_test() { + let (model_context, model, _) = seed_db().await; - model::Entity::insert(model.clone().into_active_model()) - .exec(&model_context.db_context.get_connection()) - .await - .unwrap(); + model::Entity::insert(model.clone().into_active_model()) + .exec(&model_context.db_context.get_connection()) + .await + .unwrap(); - let new_model = model::Model { - id: &model.id + 1, - ..model.clone() - }; + let new_model = model::Model { + id: &model.id + 1, + ..model.clone() + }; - let res = model_context.update(new_model.clone()).await; + let res = model_context.update(new_model.clone()).await; - assert!(matches!(res.unwrap_err(), DbErr::RecordNotUpdated)); - } + assert!(matches!(res.unwrap_err(), DbErr::RecordNotUpdated)); +} - #[tokio::test] - async fn update_does_not_modify_owner_id_test() { - let (model_context, model, _) = seed_db().await; +#[tokio::test] +async fn update_does_not_modify_owner_id_test() { + let (model_context, model, _) = seed_db().await; - model::Entity::insert(model.clone().into_active_model()) - .exec(&model_context.db_context.get_connection()) - .await - .unwrap(); + model::Entity::insert(model.clone().into_active_model()) + .exec(&model_context.db_context.get_connection()) + .await + .unwrap(); - let new_model = model::Model { - owner_id: &model.owner_id + 1, - ..model.clone() - }; + let new_model = model::Model { + owner_id: &model.owner_id + 1, + ..model.clone() + }; - let res = model_context.update(new_model.clone()).await.unwrap(); + let res = model_context.update(new_model.clone()).await.unwrap(); - assert_eq!(model, res); - } + assert_eq!(model, res); +} - #[tokio::test] - async fn update_check_query_outdated_test() { - let (model_context, model, _) = seed_db().await; +#[tokio::test] +async fn update_check_query_outdated_test() { + let (model_context, model, _) = seed_db().await; - let mut query = create_queries(1, model.id)[0].clone(); + let mut query = create_queries(1, model.id)[0].clone(); - query.outdated = false; + query.outdated = false; - model::Entity::insert(model.clone().into_active_model()) - .exec(&model_context.db_context.get_connection()) - .await - .unwrap(); + model::Entity::insert(model.clone().into_active_model()) + .exec(&model_context.db_context.get_connection()) + .await + .unwrap(); - query::Entity::insert(query.clone().into_active_model()) - .exec(&model_context.db_context.get_connection()) - .await - .unwrap(); + query::Entity::insert(query.clone().into_active_model()) + .exec(&model_context.db_context.get_connection()) + .await + .unwrap(); - let new_model = model::Model { ..model }; + let new_model = model::Model { ..model }; - let updated_model = model_context.update(new_model.clone()).await.unwrap(); + let updated_model = model_context.update(new_model.clone()).await.unwrap(); - let fetched_query = query::Entity::find_by_id(updated_model.id) - .one(&model_context.db_context.get_connection()) - .await - .unwrap() - .unwrap(); + let fetched_query = query::Entity::find_by_id(updated_model.id) + .one(&model_context.db_context.get_connection()) + .await + .unwrap() + .unwrap(); - assert!(fetched_query.outdated); - } + assert!(fetched_query.outdated); +} - #[tokio::test] - async fn update_non_existing_id_test() { - let (model_context, model, _) = seed_db().await; +#[tokio::test] +async fn update_non_existing_id_test() { + let (model_context, model, _) = seed_db().await; - let updated_model = model_context.update(model.clone()).await; + let updated_model = model_context.update(model.clone()).await; - assert!(matches!( - updated_model.unwrap_err(), - DbErr::RecordNotUpdated - )); - } + assert!(matches!( + updated_model.unwrap_err(), + DbErr::RecordNotUpdated + )); +} - #[tokio::test] - async fn delete_test() { - // Setting up database and user context - let (model_context, model, _) = seed_db().await; +#[tokio::test] +async fn delete_test() { + // Setting up database and user context + let (model_context, model, _) = seed_db().await; - model::Entity::insert(model.clone().into_active_model()) - .exec(&model_context.db_context.get_connection()) - .await - .unwrap(); + model::Entity::insert(model.clone().into_active_model()) + .exec(&model_context.db_context.get_connection()) + .await + .unwrap(); - let deleted_model = model_context.delete(model.id).await.unwrap(); + let deleted_model = model_context.delete(model.id).await.unwrap(); - let all_models = model::Entity::find() - .all(&model_context.db_context.get_connection()) - .await - .unwrap(); + let all_models = model::Entity::find() + .all(&model_context.db_context.get_connection()) + .await + .unwrap(); - assert_eq!(model, deleted_model); - assert_eq!(all_models.len(), 0); - } + assert_eq!(model, deleted_model); + assert_eq!(all_models.len(), 0); +} - #[tokio::test] - async fn delete_cascade_query_test() { - let (model_context, model, _) = seed_db().await; - - let query = create_queries(1, model.clone().id)[0].clone(); - - model::Entity::insert(model.clone().into_active_model()) - .exec(&model_context.db_context.get_connection()) - .await - .unwrap(); - query::Entity::insert(query.clone().into_active_model()) - .exec(&model_context.db_context.get_connection()) - .await - .unwrap(); - - model_context.delete(model.id).await.unwrap(); - - let all_queries = query::Entity::find() - .all(&model_context.db_context.get_connection()) - .await - .unwrap(); - let all_models = model::Entity::find() - .all(&model_context.db_context.get_connection()) - .await - .unwrap(); - - assert_eq!(all_queries.len(), 0); - assert_eq!(all_models.len(), 0); - } +#[tokio::test] +async fn delete_cascade_query_test() { + let (model_context, model, _) = seed_db().await; + + let query = create_queries(1, model.clone().id)[0].clone(); + + model::Entity::insert(model.clone().into_active_model()) + .exec(&model_context.db_context.get_connection()) + .await + .unwrap(); + query::Entity::insert(query.clone().into_active_model()) + .exec(&model_context.db_context.get_connection()) + .await + .unwrap(); + + model_context.delete(model.id).await.unwrap(); + + let all_queries = query::Entity::find() + .all(&model_context.db_context.get_connection()) + .await + .unwrap(); + let all_models = model::Entity::find() + .all(&model_context.db_context.get_connection()) + .await + .unwrap(); + + assert_eq!(all_queries.len(), 0); + assert_eq!(all_models.len(), 0); +} - #[tokio::test] - async fn delete_cascade_access_test() { - let (model_context, model, _) = seed_db().await; - - let access = create_accesses(1, 1, model.clone().id)[0].clone(); - - model::Entity::insert(model.clone().into_active_model()) - .exec(&model_context.db_context.get_connection()) - .await - .unwrap(); - access::Entity::insert(access.clone().into_active_model()) - .exec(&model_context.db_context.get_connection()) - .await - .unwrap(); - - model_context.delete(model.id).await.unwrap(); - - let all_models = model::Entity::find() - .all(&model_context.db_context.get_connection()) - .await - .unwrap(); - let all_accesses = access::Entity::find() - .all(&model_context.db_context.get_connection()) - .await - .unwrap(); - - assert_eq!(all_models.len(), 0); - assert_eq!(all_accesses.len(), 0); - } +#[tokio::test] +async fn delete_cascade_access_test() { + let (model_context, model, _) = seed_db().await; + + let access = create_accesses(1, 1, model.clone().id)[0].clone(); + + model::Entity::insert(model.clone().into_active_model()) + .exec(&model_context.db_context.get_connection()) + .await + .unwrap(); + access::Entity::insert(access.clone().into_active_model()) + .exec(&model_context.db_context.get_connection()) + .await + .unwrap(); + + model_context.delete(model.id).await.unwrap(); + + let all_models = model::Entity::find() + .all(&model_context.db_context.get_connection()) + .await + .unwrap(); + let all_accesses = access::Entity::find() + .all(&model_context.db_context.get_connection()) + .await + .unwrap(); + + assert_eq!(all_models.len(), 0); + assert_eq!(all_accesses.len(), 0); +} - #[tokio::test] - async fn delete_cascade_in_use_test() { - let (model_context, model, user) = seed_db().await; - - let session = create_sessions(1, user.clone().id)[0].clone(); - let in_use = create_in_uses(1, model.clone().id, 1)[0].clone(); - - session::Entity::insert(session.clone().into_active_model()) - .exec(&model_context.db_context.get_connection()) - .await - .unwrap(); - model::Entity::insert(model.clone().into_active_model()) - .exec(&model_context.db_context.get_connection()) - .await - .unwrap(); - in_use::Entity::insert(in_use.clone().into_active_model()) - .exec(&model_context.db_context.get_connection()) - .await - .unwrap(); - - model_context.delete(model.id).await.unwrap(); - - let all_models = model::Entity::find() - .all(&model_context.db_context.get_connection()) - .await - .unwrap(); - let all_in_uses = in_use::Entity::find() - .all(&model_context.db_context.get_connection()) - .await - .unwrap(); - - assert_eq!(all_models.len(), 0); - assert_eq!(all_in_uses.len(), 0); - } +#[tokio::test] +async fn delete_cascade_in_use_test() { + let (model_context, model, user) = seed_db().await; + + let session = create_sessions(1, user.clone().id)[0].clone(); + let in_use = create_in_uses(1, model.clone().id, 1)[0].clone(); + + session::Entity::insert(session.clone().into_active_model()) + .exec(&model_context.db_context.get_connection()) + .await + .unwrap(); + model::Entity::insert(model.clone().into_active_model()) + .exec(&model_context.db_context.get_connection()) + .await + .unwrap(); + in_use::Entity::insert(in_use.clone().into_active_model()) + .exec(&model_context.db_context.get_connection()) + .await + .unwrap(); + + model_context.delete(model.id).await.unwrap(); + + let all_models = model::Entity::find() + .all(&model_context.db_context.get_connection()) + .await + .unwrap(); + let all_in_uses = in_use::Entity::find() + .all(&model_context.db_context.get_connection()) + .await + .unwrap(); + + assert_eq!(all_models.len(), 0); + assert_eq!(all_in_uses.len(), 0); +} - #[tokio::test] - async fn delete_non_existing_id_test() { - let (model_context, _, _) = seed_db().await; +#[tokio::test] +async fn delete_non_existing_id_test() { + let (model_context, _, _) = seed_db().await; - let deleted_model = model_context.delete(1).await; + let deleted_model = model_context.delete(1).await; - assert!(matches!( - deleted_model.unwrap_err(), - DbErr::RecordNotFound(_) - )); - } + assert!(matches!( + deleted_model.unwrap_err(), + DbErr::RecordNotFound(_) + )); } diff --git a/src/tests/database/query_context.rs b/src/tests/database/query_context.rs index 2de8620..90c30d5 100644 --- a/src/tests/database/query_context.rs +++ b/src/tests/database/query_context.rs @@ -1,317 +1,314 @@ -#[cfg(test)] -mod database_tests { - use crate::tests::database::helpers::{ - create_models, create_queries, create_users, get_reset_database_context, - }; - use crate::{ - database::{entity_context::EntityContextTrait, query_context::QueryContext}, - entities::{model, query, user}, - to_active_models, - }; - use sea_orm::{entity::prelude::*, IntoActiveModel}; - - async fn seed_db() -> (QueryContext, query::Model, model::Model) { - let db_context = get_reset_database_context().await; - - let query_context = QueryContext::new(db_context); - - let user = create_users(1)[0].clone(); - let model = create_models(1, user.id)[0].clone(); - let query = create_queries(1, model.id)[0].clone(); - - user::Entity::insert(user.clone().into_active_model()) - .exec(&query_context.db_context.get_connection()) - .await - .unwrap(); - model::Entity::insert(model.clone().into_active_model()) - .exec(&query_context.db_context.get_connection()) - .await - .unwrap(); - - (query_context, query, model) - } +use crate::tests::database::helpers::{ + create_models, create_queries, create_users, get_reset_database_context, +}; +use crate::{ + database::{entity_context::EntityContextTrait, query_context::QueryContext}, + entities::{model, query, user}, + to_active_models, +}; +use sea_orm::{entity::prelude::*, IntoActiveModel}; + +async fn seed_db() -> (QueryContext, query::Model, model::Model) { + let db_context = get_reset_database_context().await; + + let query_context = QueryContext::new(db_context); + + let user = create_users(1)[0].clone(); + let model = create_models(1, user.id)[0].clone(); + let query = create_queries(1, model.id)[0].clone(); + + user::Entity::insert(user.clone().into_active_model()) + .exec(&query_context.db_context.get_connection()) + .await + .unwrap(); + model::Entity::insert(model.clone().into_active_model()) + .exec(&query_context.db_context.get_connection()) + .await + .unwrap(); + + (query_context, query, model) +} - #[tokio::test] - async fn create_test() { - let (query_context, query, _) = seed_db().await; +#[tokio::test] +async fn create_test() { + let (query_context, query, _) = seed_db().await; - let created_query = query_context.create(query.clone()).await.unwrap(); + let created_query = query_context.create(query.clone()).await.unwrap(); - let fetched_query = query::Entity::find_by_id(created_query.id) - .one(&query_context.db_context.get_connection()) - .await - .unwrap() - .unwrap(); + let fetched_query = query::Entity::find_by_id(created_query.id) + .one(&query_context.db_context.get_connection()) + .await + .unwrap() + .unwrap(); - // Assert if the fetched access is the same as the created access - assert_eq!(query, created_query); - assert_eq!(fetched_query, created_query); - } + // Assert if the fetched access is the same as the created access + assert_eq!(query, created_query); + assert_eq!(fetched_query, created_query); +} - #[tokio::test] - async fn create_default_outdated_test() { - let (query_context, query, _) = seed_db().await; +#[tokio::test] +async fn create_default_outdated_test() { + let (query_context, query, _) = seed_db().await; - let _inserted_query = query_context.create(query.clone()).await.unwrap(); + let _inserted_query = query_context.create(query.clone()).await.unwrap(); - let fetched_query = query::Entity::find_by_id(query.model_id) - .one(&query_context.db_context.get_connection()) - .await - .unwrap() - .unwrap(); + let fetched_query = query::Entity::find_by_id(query.model_id) + .one(&query_context.db_context.get_connection()) + .await + .unwrap() + .unwrap(); - assert!(fetched_query.outdated) - } + assert!(fetched_query.outdated) +} - #[tokio::test] - async fn create_auto_increment_test() { - let (query_context, query, _) = seed_db().await; - - let created_query1 = query_context.create(query.clone()).await.unwrap(); - let created_query2 = query_context.create(query.clone()).await.unwrap(); - - let fetched_query1 = query::Entity::find_by_id(created_query1.id) - .one(&query_context.db_context.get_connection()) - .await - .unwrap() - .unwrap(); - - let fetched_query2 = query::Entity::find_by_id(created_query2.id) - .one(&query_context.db_context.get_connection()) - .await - .unwrap() - .unwrap(); - - assert_ne!(fetched_query1.id, fetched_query2.id); - assert_ne!(created_query1.id, created_query2.id); - assert_eq!(created_query1.id, fetched_query1.id); - assert_eq!(created_query2.id, fetched_query2.id); - } +#[tokio::test] +async fn create_auto_increment_test() { + let (query_context, query, _) = seed_db().await; + + let created_query1 = query_context.create(query.clone()).await.unwrap(); + let created_query2 = query_context.create(query.clone()).await.unwrap(); + + let fetched_query1 = query::Entity::find_by_id(created_query1.id) + .one(&query_context.db_context.get_connection()) + .await + .unwrap() + .unwrap(); + + let fetched_query2 = query::Entity::find_by_id(created_query2.id) + .one(&query_context.db_context.get_connection()) + .await + .unwrap() + .unwrap(); + + assert_ne!(fetched_query1.id, fetched_query2.id); + assert_ne!(created_query1.id, created_query2.id); + assert_eq!(created_query1.id, fetched_query1.id); + assert_eq!(created_query2.id, fetched_query2.id); +} - #[tokio::test] - async fn get_by_id_test() { - let (query_context, query, _) = seed_db().await; +#[tokio::test] +async fn get_by_id_test() { + let (query_context, query, _) = seed_db().await; - query::Entity::insert(query.clone().into_active_model()) - .exec(&query_context.db_context.get_connection()) - .await - .unwrap(); + query::Entity::insert(query.clone().into_active_model()) + .exec(&query_context.db_context.get_connection()) + .await + .unwrap(); - let fetched_in_use = query_context - .get_by_id(query.model_id) - .await - .unwrap() - .unwrap(); + let fetched_in_use = query_context + .get_by_id(query.model_id) + .await + .unwrap() + .unwrap(); - assert_eq!(fetched_in_use, query) - } + assert_eq!(fetched_in_use, query) +} - #[tokio::test] - async fn get_by_non_existing_id_test() { - let (query_context, _, _) = seed_db().await; +#[tokio::test] +async fn get_by_non_existing_id_test() { + let (query_context, _, _) = seed_db().await; - let query = query_context.get_by_id(1).await; + let query = query_context.get_by_id(1).await; - assert!(query.unwrap().is_none()) - } + assert!(query.unwrap().is_none()) +} - #[tokio::test] - async fn get_all_test() { - let (query_context, _, model) = seed_db().await; +#[tokio::test] +async fn get_all_test() { + let (query_context, _, model) = seed_db().await; - let queries = create_queries(10, model.id); + let queries = create_queries(10, model.id); - query::Entity::insert_many(to_active_models!(queries.clone())) - .exec(&query_context.db_context.get_connection()) - .await - .unwrap(); + query::Entity::insert_many(to_active_models!(queries.clone())) + .exec(&query_context.db_context.get_connection()) + .await + .unwrap(); - assert_eq!(query_context.get_all().await.unwrap().len(), 10); + assert_eq!(query_context.get_all().await.unwrap().len(), 10); - let mut sorted = queries.clone(); - sorted.sort_by_key(|k| k.model_id); + let mut sorted = queries.clone(); + sorted.sort_by_key(|k| k.model_id); - for (i, query) in sorted.into_iter().enumerate() { - assert_eq!(query, queries[i]); - } + for (i, query) in sorted.into_iter().enumerate() { + assert_eq!(query, queries[i]); } +} - #[tokio::test] - async fn get_all_empty_test() { - let (query_context, _, _) = seed_db().await; +#[tokio::test] +async fn get_all_empty_test() { + let (query_context, _, _) = seed_db().await; - let queries = query_context.get_all().await.unwrap(); + let queries = query_context.get_all().await.unwrap(); - assert_eq!(0, queries.len()) - } + assert_eq!(0, queries.len()) +} - #[tokio::test] - async fn update_test() { - let (query_context, query, _) = seed_db().await; +#[tokio::test] +async fn update_test() { + let (query_context, query, _) = seed_db().await; - query::Entity::insert(query.clone().into_active_model()) - .exec(&query_context.db_context.get_connection()) - .await - .unwrap(); + query::Entity::insert(query.clone().into_active_model()) + .exec(&query_context.db_context.get_connection()) + .await + .unwrap(); - let new_query = query::Model { ..query }; + let new_query = query::Model { ..query }; - let updated_query = query_context.update(new_query.clone()).await.unwrap(); + let updated_query = query_context.update(new_query.clone()).await.unwrap(); - let fetched_query = query::Entity::find_by_id(updated_query.model_id) - .one(&query_context.db_context.get_connection()) - .await - .unwrap() - .unwrap(); + let fetched_query = query::Entity::find_by_id(updated_query.model_id) + .one(&query_context.db_context.get_connection()) + .await + .unwrap() + .unwrap(); - assert_eq!(new_query, updated_query); - assert_eq!(updated_query, fetched_query); - } + assert_eq!(new_query, updated_query); + assert_eq!(updated_query, fetched_query); +} - #[tokio::test] - async fn update_modifies_string_test() { - let (query_context, query, _) = seed_db().await; +#[tokio::test] +async fn update_modifies_string_test() { + let (query_context, query, _) = seed_db().await; - query::Entity::insert(query.clone().into_active_model()) - .exec(&query_context.db_context.get_connection()) - .await - .unwrap(); + query::Entity::insert(query.clone().into_active_model()) + .exec(&query_context.db_context.get_connection()) + .await + .unwrap(); - let new_query = query::Model { - string: query.clone().string + "123", - ..query.clone() - }; + let new_query = query::Model { + string: query.clone().string + "123", + ..query.clone() + }; - let updated_query = query_context.update(new_query.clone()).await.unwrap(); + let updated_query = query_context.update(new_query.clone()).await.unwrap(); - assert_ne!(query, updated_query); - assert_ne!(query, new_query); - } + assert_ne!(query, updated_query); + assert_ne!(query, new_query); +} - #[tokio::test] - async fn update_modifies_outdated_test() { - let (query_context, query, _) = seed_db().await; +#[tokio::test] +async fn update_modifies_outdated_test() { + let (query_context, query, _) = seed_db().await; - query::Entity::insert(query.clone().into_active_model()) - .exec(&query_context.db_context.get_connection()) - .await - .unwrap(); + query::Entity::insert(query.clone().into_active_model()) + .exec(&query_context.db_context.get_connection()) + .await + .unwrap(); - let new_query = query::Model { - outdated: !query.clone().outdated, - ..query.clone() - }; + let new_query = query::Model { + outdated: !query.clone().outdated, + ..query.clone() + }; - let updated_query = query_context.update(new_query.clone()).await.unwrap(); + let updated_query = query_context.update(new_query.clone()).await.unwrap(); - assert_ne!(query, updated_query); - assert_ne!(query, new_query); - } + assert_ne!(query, updated_query); + assert_ne!(query, new_query); +} - #[tokio::test] - async fn update_modifies_result_test() { - let (query_context, mut query, _) = seed_db().await; +#[tokio::test] +async fn update_modifies_result_test() { + let (query_context, mut query, _) = seed_db().await; - query.result = Some("{}".to_owned().parse().unwrap()); + query.result = Some("{}".to_owned().parse().unwrap()); - query::Entity::insert(query.clone().into_active_model()) - .exec(&query_context.db_context.get_connection()) - .await - .unwrap(); + query::Entity::insert(query.clone().into_active_model()) + .exec(&query_context.db_context.get_connection()) + .await + .unwrap(); - let new_query = query::Model { - result: None, - ..query.clone() - }; + let new_query = query::Model { + result: None, + ..query.clone() + }; - let updated_query = query_context.update(new_query.clone()).await.unwrap(); + let updated_query = query_context.update(new_query.clone()).await.unwrap(); - assert_ne!(query, updated_query); - assert_ne!(query, new_query); - } + assert_ne!(query, updated_query); + assert_ne!(query, new_query); +} - #[tokio::test] - async fn update_does_not_modify_id_test() { - let (query_context, query, _) = seed_db().await; +#[tokio::test] +async fn update_does_not_modify_id_test() { + let (query_context, query, _) = seed_db().await; - query::Entity::insert(query.clone().into_active_model()) - .exec(&query_context.db_context.get_connection()) - .await - .unwrap(); + query::Entity::insert(query.clone().into_active_model()) + .exec(&query_context.db_context.get_connection()) + .await + .unwrap(); - let new_query = query::Model { - id: query.id + 1, - ..query.clone() - }; + let new_query = query::Model { + id: query.id + 1, + ..query.clone() + }; - let updated_query = query_context.update(new_query.clone()).await; + let updated_query = query_context.update(new_query.clone()).await; - assert!(matches!( - updated_query.unwrap_err(), - DbErr::RecordNotUpdated - )); - } + assert!(matches!( + updated_query.unwrap_err(), + DbErr::RecordNotUpdated + )); +} - #[tokio::test] - async fn update_does_not_modify_model_id_test() { - let (query_context, query, _) = seed_db().await; +#[tokio::test] +async fn update_does_not_modify_model_id_test() { + let (query_context, query, _) = seed_db().await; - query::Entity::insert(query.clone().into_active_model()) - .exec(&query_context.db_context.get_connection()) - .await - .unwrap(); + query::Entity::insert(query.clone().into_active_model()) + .exec(&query_context.db_context.get_connection()) + .await + .unwrap(); - let new_query = query::Model { - model_id: query.model_id + 1, - ..query.clone() - }; + let new_query = query::Model { + model_id: query.model_id + 1, + ..query.clone() + }; - let updated_query = query_context.update(new_query.clone()).await.unwrap(); + let updated_query = query_context.update(new_query.clone()).await.unwrap(); - assert_eq!(query, updated_query); - } + assert_eq!(query, updated_query); +} - #[tokio::test] - async fn update_non_existing_id_test() { - let (query_context, query, _) = seed_db().await; +#[tokio::test] +async fn update_non_existing_id_test() { + let (query_context, query, _) = seed_db().await; - let updated_query = query_context.update(query.clone()).await; + let updated_query = query_context.update(query.clone()).await; - assert!(matches!( - updated_query.unwrap_err(), - DbErr::RecordNotUpdated - )); - } + assert!(matches!( + updated_query.unwrap_err(), + DbErr::RecordNotUpdated + )); +} - #[tokio::test] - async fn delete_test() { - let (query_context, query, _) = seed_db().await; +#[tokio::test] +async fn delete_test() { + let (query_context, query, _) = seed_db().await; - query::Entity::insert(query.clone().into_active_model()) - .exec(&query_context.db_context.get_connection()) - .await - .unwrap(); + query::Entity::insert(query.clone().into_active_model()) + .exec(&query_context.db_context.get_connection()) + .await + .unwrap(); - let deleted_query = query_context.delete(query.model_id).await.unwrap(); + let deleted_query = query_context.delete(query.model_id).await.unwrap(); - let all_queries = query::Entity::find() - .all(&query_context.db_context.get_connection()) - .await - .unwrap(); + let all_queries = query::Entity::find() + .all(&query_context.db_context.get_connection()) + .await + .unwrap(); - assert_eq!(query, deleted_query); - assert!(all_queries.is_empty()); - } + assert_eq!(query, deleted_query); + assert!(all_queries.is_empty()); +} - #[tokio::test] - async fn delete_non_existing_id_test() { - let (query_context, _, _) = seed_db().await; +#[tokio::test] +async fn delete_non_existing_id_test() { + let (query_context, _, _) = seed_db().await; - let deleted_query = query_context.delete(1).await; + let deleted_query = query_context.delete(1).await; - assert!(matches!( - deleted_query.unwrap_err(), - DbErr::RecordNotFound(_) - )) - } + assert!(matches!( + deleted_query.unwrap_err(), + DbErr::RecordNotFound(_) + )) } diff --git a/src/tests/database/session_context.rs b/src/tests/database/session_context.rs index 70b6bff..6d4ee56 100644 --- a/src/tests/database/session_context.rs +++ b/src/tests/database/session_context.rs @@ -1,364 +1,361 @@ -#[cfg(test)] -mod database_tests { - use crate::tests::database::helpers::*; - use sea_orm::{entity::prelude::*, IntoActiveModel}; - use std::ops::Add; - - use crate::{ - database::{entity_context::EntityContextTrait, session_context::SessionContext}, - entities::{in_use, model, session, user}, - to_active_models, - }; +use crate::tests::database::helpers::*; +use sea_orm::{entity::prelude::*, IntoActiveModel}; +use std::ops::Add; + +use crate::{ + database::{entity_context::EntityContextTrait, session_context::SessionContext}, + entities::{in_use, model, session, user}, + to_active_models, +}; + +use crate::database::session_context::SessionContextTrait; +use chrono::{Duration, Utc}; + +async fn seed_db() -> (SessionContext, session::Model, user::Model, model::Model) { + let db_context = get_reset_database_context().await; + + let session_context = SessionContext::new(db_context); + + let user = create_users(1)[0].clone(); + let model = create_models(1, user.id)[0].clone(); + let session = create_sessions(1, user.id)[0].clone(); + + user::Entity::insert(user.clone().into_active_model()) + .exec(&session_context.db_context.get_connection()) + .await + .unwrap(); + model::Entity::insert(model.clone().into_active_model()) + .exec(&session_context.db_context.get_connection()) + .await + .unwrap(); + + (session_context, session, user, model) +} - use crate::database::session_context::SessionContextTrait; - use chrono::{Duration, Utc}; +#[tokio::test] +async fn create_test() { + // Setting up a sqlite database in memory. + let (session_context, mut session, _, _) = seed_db().await; - async fn seed_db() -> (SessionContext, session::Model, user::Model, model::Model) { - let db_context = get_reset_database_context().await; + let created_session = session_context.create(session.clone()).await.unwrap(); - let session_context = SessionContext::new(db_context); + session.updated_at = created_session.updated_at; - let user = create_users(1)[0].clone(); - let model = create_models(1, user.id)[0].clone(); - let session = create_sessions(1, user.id)[0].clone(); + let fetched_session = session::Entity::find_by_id(created_session.id) + .one(&session_context.db_context.get_connection()) + .await + .unwrap() + .unwrap(); - user::Entity::insert(user.clone().into_active_model()) - .exec(&session_context.db_context.get_connection()) - .await - .unwrap(); - model::Entity::insert(model.clone().into_active_model()) - .exec(&session_context.db_context.get_connection()) - .await - .unwrap(); + assert_eq!(session, created_session); + assert_eq!(fetched_session, created_session); +} - (session_context, session, user, model) - } +#[tokio::test] +async fn create_default_created_at_test() { + let t_min = Utc::now().timestamp(); - #[tokio::test] - async fn create_test() { - // Setting up a sqlite database in memory. - let (session_context, mut session, _, _) = seed_db().await; + let (session_context, session, _, _) = seed_db().await; - let created_session = session_context.create(session.clone()).await.unwrap(); + let _created_session = session_context.create(session.clone()).await.unwrap(); - session.updated_at = created_session.updated_at; + let fetched_session = session::Entity::find_by_id(1) + .one(&session_context.db_context.get_connection()) + .await + .unwrap() + .unwrap(); - let fetched_session = session::Entity::find_by_id(created_session.id) - .one(&session_context.db_context.get_connection()) - .await - .unwrap() - .unwrap(); + let t_max = Utc::now().timestamp(); + let t_actual = fetched_session.clone().updated_at.timestamp(); - assert_eq!(session, created_session); - assert_eq!(fetched_session, created_session); - } + assert!(t_min <= t_actual && t_actual <= t_max) +} - #[tokio::test] - async fn create_default_created_at_test() { - let t_min = Utc::now().timestamp(); +#[tokio::test] +async fn create_auto_increment_test() { + // Setting up database and session context + let (session_context, _, user, _) = seed_db().await; + + let sessions = create_sessions(2, user.id); + + // Creates the sessions in the database using the 'create' function + let created_session1 = session_context.create(sessions[0].clone()).await.unwrap(); + let created_session2 = session_context.create(sessions[1].clone()).await.unwrap(); + + let fetched_session1 = session::Entity::find_by_id(created_session1.id) + .one(&session_context.db_context.get_connection()) + .await + .unwrap() + .unwrap(); + + let fetched_session2 = session::Entity::find_by_id(created_session2.id) + .one(&session_context.db_context.get_connection()) + .await + .unwrap() + .unwrap(); + + // Assert if the new_session, created_session, and fetched_session are the same + assert_ne!(fetched_session1.id, fetched_session2.id); + assert_ne!(created_session1.id, created_session2.id); + assert_eq!(created_session1.id, fetched_session1.id); + assert_eq!(created_session2.id, fetched_session2.id); +} - let (session_context, session, _, _) = seed_db().await; +#[tokio::test] +async fn create_non_unique_refresh_token_test() { + let (session_context, _, _, user) = seed_db().await; - let _created_session = session_context.create(session.clone()).await.unwrap(); + let mut sessions = create_sessions(2, user.id); - let fetched_session = session::Entity::find_by_id(1) - .one(&session_context.db_context.get_connection()) - .await - .unwrap() - .unwrap(); + sessions[1].refresh_token = sessions[0].refresh_token.clone(); - let t_max = Utc::now().timestamp(); - let t_actual = fetched_session.clone().updated_at.timestamp(); + let _created_session1 = session_context.create(sessions[0].clone()).await.unwrap(); + let created_session2 = session_context.create(sessions[1].clone()).await; - assert!(t_min <= t_actual && t_actual <= t_max) - } + assert!(matches!( + created_session2.unwrap_err().sql_err(), + Some(SqlErr::UniqueConstraintViolation(_)) + )); +} - #[tokio::test] - async fn create_auto_increment_test() { - // Setting up database and session context - let (session_context, _, user, _) = seed_db().await; - - let sessions = create_sessions(2, user.id); - - // Creates the sessions in the database using the 'create' function - let created_session1 = session_context.create(sessions[0].clone()).await.unwrap(); - let created_session2 = session_context.create(sessions[1].clone()).await.unwrap(); - - let fetched_session1 = session::Entity::find_by_id(created_session1.id) - .one(&session_context.db_context.get_connection()) - .await - .unwrap() - .unwrap(); - - let fetched_session2 = session::Entity::find_by_id(created_session2.id) - .one(&session_context.db_context.get_connection()) - .await - .unwrap() - .unwrap(); - - // Assert if the new_session, created_session, and fetched_session are the same - assert_ne!(fetched_session1.id, fetched_session2.id); - assert_ne!(created_session1.id, created_session2.id); - assert_eq!(created_session1.id, fetched_session1.id); - assert_eq!(created_session2.id, fetched_session2.id); - } +#[tokio::test] +async fn get_by_id_test() { + let (session_context, session, _, _) = seed_db().await; - #[tokio::test] - async fn create_non_unique_refresh_token_test() { - let (session_context, _, _, user) = seed_db().await; + session::Entity::insert(session.clone().into_active_model()) + .exec(&session_context.db_context.get_connection()) + .await + .unwrap(); - let mut sessions = create_sessions(2, user.id); + let fetched_session = session_context + .get_by_id(session.id) + .await + .unwrap() + .unwrap(); - sessions[1].refresh_token = sessions[0].refresh_token.clone(); + assert_eq!(session, fetched_session); +} - let _created_session1 = session_context.create(sessions[0].clone()).await.unwrap(); - let created_session2 = session_context.create(sessions[1].clone()).await; +#[tokio::test] +async fn get_by_non_existing_id_test() { + let (session_context, _, _, _) = seed_db().await; - assert!(matches!( - created_session2.unwrap_err().sql_err(), - Some(SqlErr::UniqueConstraintViolation(_)) - )); - } + let fetched_session = session_context.get_by_id(1).await.unwrap(); - #[tokio::test] - async fn get_by_id_test() { - let (session_context, session, _, _) = seed_db().await; + assert!(fetched_session.is_none()); +} - session::Entity::insert(session.clone().into_active_model()) - .exec(&session_context.db_context.get_connection()) - .await - .unwrap(); +#[tokio::test] +async fn get_all_test() { + let (session_context, _, user, _) = seed_db().await; - let fetched_session = session_context - .get_by_id(session.id) - .await - .unwrap() - .unwrap(); + let new_sessions = create_sessions(3, user.id); - assert_eq!(session, fetched_session); - } + session::Entity::insert_many(to_active_models!(new_sessions.clone())) + .exec(&session_context.db_context.get_connection()) + .await + .unwrap(); - #[tokio::test] - async fn get_by_non_existing_id_test() { - let (session_context, _, _, _) = seed_db().await; + assert_eq!(session_context.get_all().await.unwrap().len(), 3); - let fetched_session = session_context.get_by_id(1).await.unwrap(); + let mut sorted: Vec = new_sessions.clone(); + sorted.sort_by_key(|k| k.id); - assert!(fetched_session.is_none()); + for (i, session) in sorted.into_iter().enumerate() { + assert_eq!(session, new_sessions[i]); } +} - #[tokio::test] - async fn get_all_test() { - let (session_context, _, user, _) = seed_db().await; - - let new_sessions = create_sessions(3, user.id); - - session::Entity::insert_many(to_active_models!(new_sessions.clone())) - .exec(&session_context.db_context.get_connection()) - .await - .unwrap(); - - assert_eq!(session_context.get_all().await.unwrap().len(), 3); +#[tokio::test] +async fn get_all_empty_test() { + let (session_context, _, _, _) = seed_db().await; - let mut sorted: Vec = new_sessions.clone(); - sorted.sort_by_key(|k| k.id); + let result = session_context.get_all().await.unwrap(); + let empty_accesses: Vec = vec![]; - for (i, session) in sorted.into_iter().enumerate() { - assert_eq!(session, new_sessions[i]); - } - } - - #[tokio::test] - async fn get_all_empty_test() { - let (session_context, _, _, _) = seed_db().await; + assert_eq!(empty_accesses, result); +} - let result = session_context.get_all().await.unwrap(); - let empty_accesses: Vec = vec![]; +#[tokio::test] +async fn update_test() { + let (session_context, session, _, _) = seed_db().await; - assert_eq!(empty_accesses, result); - } + session::Entity::insert(session.clone().into_active_model()) + .exec(&session_context.db_context.get_connection()) + .await + .unwrap(); - #[tokio::test] - async fn update_test() { - let (session_context, session, _, _) = seed_db().await; + //A session has nothing to update + let mut new_session = session::Model { ..session }; - session::Entity::insert(session.clone().into_active_model()) - .exec(&session_context.db_context.get_connection()) - .await - .unwrap(); + let mut updated_session = session_context.update(new_session.clone()).await.unwrap(); - //A session has nothing to update - let mut new_session = session::Model { ..session }; + let fetched_session = session::Entity::find_by_id(updated_session.id) + .one(&session_context.db_context.get_connection()) + .await + .unwrap() + .unwrap(); - let mut updated_session = session_context.update(new_session.clone()).await.unwrap(); + new_session.updated_at = fetched_session.updated_at; + updated_session.updated_at = fetched_session.updated_at; - let fetched_session = session::Entity::find_by_id(updated_session.id) - .one(&session_context.db_context.get_connection()) - .await - .unwrap() - .unwrap(); + assert_eq!(new_session, updated_session); + assert_eq!(updated_session, fetched_session); +} - new_session.updated_at = fetched_session.updated_at; - updated_session.updated_at = fetched_session.updated_at; +#[tokio::test] +async fn update_does_not_modify_id_test() { + let (session_context, session, _, _) = seed_db().await; + session::Entity::insert(session.clone().into_active_model()) + .exec(&session_context.db_context.get_connection()) + .await + .unwrap(); + + let updated_session = session::Model { + id: &session.id + 1, + ..session.clone() + }; + let res = session_context.update(updated_session.clone()).await; - assert_eq!(new_session, updated_session); - assert_eq!(updated_session, fetched_session); - } + assert!(matches!(res.unwrap_err(), DbErr::RecordNotUpdated)); +} - #[tokio::test] - async fn update_does_not_modify_id_test() { - let (session_context, session, _, _) = seed_db().await; - session::Entity::insert(session.clone().into_active_model()) - .exec(&session_context.db_context.get_connection()) - .await - .unwrap(); - - let updated_session = session::Model { - id: &session.id + 1, - ..session.clone() - }; - let res = session_context.update(updated_session.clone()).await; - - assert!(matches!(res.unwrap_err(), DbErr::RecordNotUpdated)); - } +#[tokio::test] +async fn update_does_modifies_updated_at_automatically_test() { + let (session_context, mut session, _, _) = seed_db().await; + session::Entity::insert(session.clone().into_active_model()) + .exec(&session_context.db_context.get_connection()) + .await + .unwrap(); + + let updated_session = session::Model { + updated_at: session.clone().updated_at.add(Duration::seconds(1)), + ..session.clone() + }; + let res = session_context + .update(updated_session.clone()) + .await + .unwrap(); - #[tokio::test] - async fn update_does_modifies_updated_at_automatically_test() { - let (session_context, mut session, _, _) = seed_db().await; - session::Entity::insert(session.clone().into_active_model()) - .exec(&session_context.db_context.get_connection()) - .await - .unwrap(); + assert!(session.updated_at < res.updated_at); - let updated_session = session::Model { - updated_at: session.clone().updated_at.add(Duration::seconds(1)), - ..session.clone() - }; - let res = session_context - .update(updated_session.clone()) - .await - .unwrap(); + session.updated_at = res.updated_at; - assert!(session.updated_at < res.updated_at); + assert_eq!(session, res); +} - session.updated_at = res.updated_at; +#[tokio::test] +async fn update_does_not_modify_user_id_test() { + let (session_context, mut session, _, _) = seed_db().await; + session::Entity::insert(session.clone().into_active_model()) + .exec(&session_context.db_context.get_connection()) + .await + .unwrap(); + + let updated_session = session::Model { + user_id: &session.user_id + 1, + ..session.clone() + }; + let res = session_context + .update(updated_session.clone()) + .await + .unwrap(); - assert_eq!(session, res); - } + session.updated_at = res.updated_at; - #[tokio::test] - async fn update_does_not_modify_user_id_test() { - let (session_context, mut session, _, _) = seed_db().await; - session::Entity::insert(session.clone().into_active_model()) - .exec(&session_context.db_context.get_connection()) - .await - .unwrap(); - - let updated_session = session::Model { - user_id: &session.user_id + 1, - ..session.clone() - }; - let res = session_context - .update(updated_session.clone()) - .await - .unwrap(); - - session.updated_at = res.updated_at; - - assert_eq!(session, res); - } + assert_eq!(session, res); +} - #[tokio::test] - async fn update_non_existing_id_test() { - let (session_context, session, _, _) = seed_db().await; +#[tokio::test] +async fn update_non_existing_id_test() { + let (session_context, session, _, _) = seed_db().await; - let updated_session = session_context.update(session.clone()).await; + let updated_session = session_context.update(session.clone()).await; - assert!(matches!( - updated_session.unwrap_err(), - DbErr::RecordNotUpdated - )); - } + assert!(matches!( + updated_session.unwrap_err(), + DbErr::RecordNotUpdated + )); +} - #[tokio::test] - async fn delete_test() { - let (session_context, session, _, _) = seed_db().await; +#[tokio::test] +async fn delete_test() { + let (session_context, session, _, _) = seed_db().await; - session::Entity::insert(session.clone().into_active_model()) - .exec(&session_context.db_context.get_connection()) - .await - .unwrap(); + session::Entity::insert(session.clone().into_active_model()) + .exec(&session_context.db_context.get_connection()) + .await + .unwrap(); - let deleted_session = session_context.delete(session.id).await.unwrap(); + let deleted_session = session_context.delete(session.id).await.unwrap(); - let all_sessions = session::Entity::find() - .all(&session_context.db_context.get_connection()) - .await - .unwrap(); + let all_sessions = session::Entity::find() + .all(&session_context.db_context.get_connection()) + .await + .unwrap(); - assert_eq!(session, deleted_session); - assert!(all_sessions.is_empty()); - } + assert_eq!(session, deleted_session); + assert!(all_sessions.is_empty()); +} - #[tokio::test] - async fn delete_cascade_in_use_test() { - let (session_context, session, _, model) = seed_db().await; - - let in_use = create_in_uses(1, model.id, session.id)[0].clone(); - - session::Entity::insert(session.clone().into_active_model()) - .exec(&session_context.db_context.get_connection()) - .await - .unwrap(); - in_use::Entity::insert(in_use.clone().into_active_model()) - .exec(&session_context.db_context.get_connection()) - .await - .unwrap(); - - session_context.delete(session.id).await.unwrap(); - - let all_sessions = session::Entity::find() - .all(&session_context.db_context.get_connection()) - .await - .unwrap(); - let all_in_uses = in_use::Entity::find() - .all(&session_context.db_context.get_connection()) - .await - .unwrap(); - - assert_eq!(all_sessions.len(), 0); - assert_eq!(all_in_uses.len(), 0); - } +#[tokio::test] +async fn delete_cascade_in_use_test() { + let (session_context, session, _, model) = seed_db().await; + + let in_use = create_in_uses(1, model.id, session.id)[0].clone(); + + session::Entity::insert(session.clone().into_active_model()) + .exec(&session_context.db_context.get_connection()) + .await + .unwrap(); + in_use::Entity::insert(in_use.clone().into_active_model()) + .exec(&session_context.db_context.get_connection()) + .await + .unwrap(); + + session_context.delete(session.id).await.unwrap(); + + let all_sessions = session::Entity::find() + .all(&session_context.db_context.get_connection()) + .await + .unwrap(); + let all_in_uses = in_use::Entity::find() + .all(&session_context.db_context.get_connection()) + .await + .unwrap(); + + assert_eq!(all_sessions.len(), 0); + assert_eq!(all_in_uses.len(), 0); +} - #[tokio::test] - async fn delete_non_existing_id_test() { - let (session_context, _, _, _) = seed_db().await; +#[tokio::test] +async fn delete_non_existing_id_test() { + let (session_context, _, _, _) = seed_db().await; - let deleted_session = session_context.delete(1).await; + let deleted_session = session_context.delete(1).await; - assert!(matches!( - deleted_session.unwrap_err(), - DbErr::RecordNotFound(_) - )); - } + assert!(matches!( + deleted_session.unwrap_err(), + DbErr::RecordNotFound(_) + )); +} - #[tokio::test] - async fn get_by_refresh_token_test() { - let (session_context, session, _, _) = seed_db().await; +#[tokio::test] +async fn get_by_refresh_token_test() { + let (session_context, session, _, _) = seed_db().await; - session::Entity::insert(session.clone().into_active_model()) - .exec(&session_context.db_context.get_connection()) - .await - .unwrap(); + session::Entity::insert(session.clone().into_active_model()) + .exec(&session_context.db_context.get_connection()) + .await + .unwrap(); - let fetched_session = session_context - .get_by_refresh_token(session.refresh_token.clone()) - .await - .unwrap(); + let fetched_session = session_context + .get_by_refresh_token(session.refresh_token.clone()) + .await + .unwrap(); - assert_eq!( - fetched_session.unwrap().refresh_token, - session.refresh_token - ); - } + assert_eq!( + fetched_session.unwrap().refresh_token, + session.refresh_token + ); } diff --git a/src/tests/database/user_context.rs b/src/tests/database/user_context.rs index 4d28c53..6dd5652 100644 --- a/src/tests/database/user_context.rs +++ b/src/tests/database/user_context.rs @@ -1,537 +1,534 @@ -#[cfg(test)] -mod database_tests { - use crate::database::user_context::UserContextTrait; - use crate::tests::database::helpers::*; - use crate::{ - database::{ - entity_context::EntityContextTrait, - user_context::{DbErr, UserContext}, - }, - entities::{access, model, session, user}, - to_active_models, - }; - use sea_orm::{entity::prelude::*, IntoActiveModel}; - use std::matches; - - async fn seed_db() -> (UserContext, user::Model) { - let db_context = get_reset_database_context().await; - - let user_context = UserContext::new(db_context); - - let user = create_users(1)[0].clone(); - - (user_context, user) - } +use crate::database::user_context::UserContextTrait; +use crate::tests::database::helpers::*; +use crate::{ + database::{ + entity_context::EntityContextTrait, + user_context::{DbErr, UserContext}, + }, + entities::{access, model, session, user}, + to_active_models, +}; +use sea_orm::{entity::prelude::*, IntoActiveModel}; +use std::matches; + +async fn seed_db() -> (UserContext, user::Model) { + let db_context = get_reset_database_context().await; + + let user_context = UserContext::new(db_context); + + let user = create_users(1)[0].clone(); + + (user_context, user) +} - // Test the functionality of the 'create' function, which creates a user in the database - #[tokio::test] - async fn create_test() { - // Setting up database and user context - let (user_context, user) = seed_db().await; +// Test the functionality of the 'create' function, which creates a user in the database +#[tokio::test] +async fn create_test() { + // Setting up database and user context + let (user_context, user) = seed_db().await; - // Creates the user in the database using the 'create' function - let created_user = user_context.create(user.clone()).await.unwrap(); + // Creates the user in the database using the 'create' function + let created_user = user_context.create(user.clone()).await.unwrap(); - let fetched_user = user::Entity::find_by_id(created_user.id) - .one(&user_context.db_context.get_connection()) - .await - .unwrap() - .unwrap(); + let fetched_user = user::Entity::find_by_id(created_user.id) + .one(&user_context.db_context.get_connection()) + .await + .unwrap() + .unwrap(); - // Assert if the new_user, created_user, and fetched_user are the same - assert_eq!(user, created_user); - assert_eq!(created_user, fetched_user); - } + // Assert if the new_user, created_user, and fetched_user are the same + assert_eq!(user, created_user); + assert_eq!(created_user, fetched_user); +} - #[tokio::test] - async fn create_non_unique_username_test() { - // Setting up database and user context - let (user_context, user) = seed_db().await; +#[tokio::test] +async fn create_non_unique_username_test() { + // Setting up database and user context + let (user_context, user) = seed_db().await; - // Creates a model of the user which will be created - let mut users = create_users(2); + // Creates a model of the user which will be created + let mut users = create_users(2); - users[0].username = user.clone().username; - users[1].username = user.clone().username; + users[0].username = user.clone().username; + users[1].username = user.clone().username; - // Creates the user in the database using the 'create' function - let _created_user1 = user_context.create(users[0].clone()).await.unwrap(); - let created_user2 = user_context.create(users[1].clone()).await; + // Creates the user in the database using the 'create' function + let _created_user1 = user_context.create(users[0].clone()).await.unwrap(); + let created_user2 = user_context.create(users[1].clone()).await; - assert!(matches!( - created_user2.unwrap_err().sql_err(), - Some(SqlErr::UniqueConstraintViolation(_)) - )); - } + assert!(matches!( + created_user2.unwrap_err().sql_err(), + Some(SqlErr::UniqueConstraintViolation(_)) + )); +} - #[tokio::test] - async fn create_non_unique_email_test() { - // Setting up database and user context - let (user_context, user) = seed_db().await; +#[tokio::test] +async fn create_non_unique_email_test() { + // Setting up database and user context + let (user_context, user) = seed_db().await; - // Creates a model of the user which will be created - let mut users = create_users(2); + // Creates a model of the user which will be created + let mut users = create_users(2); - users[0].email = user.clone().email; - users[1].email = user.clone().email; + users[0].email = user.clone().email; + users[1].email = user.clone().email; - // Creates the user in the database using the 'create' function - let _created_user1 = user_context.create(users[0].clone()).await.unwrap(); - let created_user2 = user_context.create(users[1].clone()).await; + // Creates the user in the database using the 'create' function + let _created_user1 = user_context.create(users[0].clone()).await.unwrap(); + let created_user2 = user_context.create(users[1].clone()).await; - // Assert if the new_user, created_user, and fetched_user are the same - assert!(matches!( - created_user2.unwrap_err().sql_err(), - Some(SqlErr::UniqueConstraintViolation(_)) - )); - } + // Assert if the new_user, created_user, and fetched_user are the same + assert!(matches!( + created_user2.unwrap_err().sql_err(), + Some(SqlErr::UniqueConstraintViolation(_)) + )); +} - #[tokio::test] - async fn create_auto_increment_test() { - // Setting up database and user context - let (user_context, user) = seed_db().await; - - let mut users = create_users(2); - - users[0].id = user.clone().id; - users[1].id = user.clone().id; - - // Creates the user in the database using the 'create' function - let created_user1 = user_context.create(users[0].clone()).await.unwrap(); - let created_user2 = user_context.create(users[1].clone()).await.unwrap(); - - let fetched_user1 = user::Entity::find_by_id(created_user1.id) - .one(&user_context.db_context.get_connection()) - .await - .unwrap() - .unwrap(); - - let fetched_user2 = user::Entity::find_by_id(created_user2.id) - .one(&user_context.db_context.get_connection()) - .await - .unwrap() - .unwrap(); - - // Assert if the new_user, created_user, and fetched_user are the same - assert_ne!(fetched_user1.id, fetched_user2.id); - assert_ne!(created_user1.id, created_user2.id); - assert_eq!(created_user1.id, fetched_user1.id); - assert_eq!(created_user2.id, fetched_user2.id); - } +#[tokio::test] +async fn create_auto_increment_test() { + // Setting up database and user context + let (user_context, user) = seed_db().await; + + let mut users = create_users(2); + + users[0].id = user.clone().id; + users[1].id = user.clone().id; + + // Creates the user in the database using the 'create' function + let created_user1 = user_context.create(users[0].clone()).await.unwrap(); + let created_user2 = user_context.create(users[1].clone()).await.unwrap(); + + let fetched_user1 = user::Entity::find_by_id(created_user1.id) + .one(&user_context.db_context.get_connection()) + .await + .unwrap() + .unwrap(); + + let fetched_user2 = user::Entity::find_by_id(created_user2.id) + .one(&user_context.db_context.get_connection()) + .await + .unwrap() + .unwrap(); + + // Assert if the new_user, created_user, and fetched_user are the same + assert_ne!(fetched_user1.id, fetched_user2.id); + assert_ne!(created_user1.id, created_user2.id); + assert_eq!(created_user1.id, fetched_user1.id); + assert_eq!(created_user2.id, fetched_user2.id); +} - #[tokio::test] - async fn get_by_id_test() { - // Setting up database and user context - let (user_context, user) = seed_db().await; +#[tokio::test] +async fn get_by_id_test() { + // Setting up database and user context + let (user_context, user) = seed_db().await; - // Creates the user in the database using the 'create' function - user::Entity::insert(user.clone().into_active_model()) - .exec(&user_context.db_context.get_connection()) - .await - .unwrap(); + // Creates the user in the database using the 'create' function + user::Entity::insert(user.clone().into_active_model()) + .exec(&user_context.db_context.get_connection()) + .await + .unwrap(); - // Fetches the user created using the 'get_by_id' function - let fetched_user = user_context.get_by_id(user.id).await.unwrap().unwrap(); + // Fetches the user created using the 'get_by_id' function + let fetched_user = user_context.get_by_id(user.id).await.unwrap().unwrap(); - // Assert if the new_user, created_user, and fetched_user are the same - assert_eq!(user, fetched_user); - } + // Assert if the new_user, created_user, and fetched_user are the same + assert_eq!(user, fetched_user); +} - #[tokio::test] - async fn get_by_non_existing_id_test() { - // Setting up database and user context - let (user_context, _) = seed_db().await; +#[tokio::test] +async fn get_by_non_existing_id_test() { + // Setting up database and user context + let (user_context, _) = seed_db().await; - // Fetches the user created using the 'get_by_id' function - let fetched_user = user_context.get_by_id(1).await.unwrap(); + // Fetches the user created using the 'get_by_id' function + let fetched_user = user_context.get_by_id(1).await.unwrap(); - assert!(fetched_user.is_none()); - } + assert!(fetched_user.is_none()); +} - #[tokio::test] - async fn get_all_test() { - // Setting up database and user context - let (user_context, _) = seed_db().await; +#[tokio::test] +async fn get_all_test() { + // Setting up database and user context + let (user_context, _) = seed_db().await; - let users = create_users(10); - let active_users_vec = to_active_models!(users.clone()); + let users = create_users(10); + let active_users_vec = to_active_models!(users.clone()); - user::Entity::insert_many(active_users_vec) - .exec(&user_context.db_context.get_connection()) - .await - .unwrap(); + user::Entity::insert_many(active_users_vec) + .exec(&user_context.db_context.get_connection()) + .await + .unwrap(); - assert_eq!(user_context.get_all().await.unwrap().len(), 10); + assert_eq!(user_context.get_all().await.unwrap().len(), 10); - let mut sorted = users.clone(); - sorted.sort_by_key(|k| k.id); + let mut sorted = users.clone(); + sorted.sort_by_key(|k| k.id); - for (i, user) in sorted.into_iter().enumerate() { - assert_eq!(user, users[i]); - } + for (i, user) in sorted.into_iter().enumerate() { + assert_eq!(user, users[i]); } +} - #[tokio::test] - async fn get_all_empty_test() { - // Setting up database and user context - let (user_context, _) = seed_db().await; +#[tokio::test] +async fn get_all_empty_test() { + // Setting up database and user context + let (user_context, _) = seed_db().await; - let result = user_context.get_all().await.unwrap(); - let empty_users: Vec = vec![]; + let result = user_context.get_all().await.unwrap(); + let empty_users: Vec = vec![]; - assert_eq!(empty_users, result); - } + assert_eq!(empty_users, result); +} - #[tokio::test] - async fn update_test() { - // Setting up database and user context - let (user_context, user) = seed_db().await; +#[tokio::test] +async fn update_test() { + // Setting up database and user context + let (user_context, user) = seed_db().await; - user::Entity::insert(user.clone().into_active_model()) - .exec(&user_context.db_context.get_connection()) - .await - .unwrap(); + user::Entity::insert(user.clone().into_active_model()) + .exec(&user_context.db_context.get_connection()) + .await + .unwrap(); - let new_user = user::Model { ..user }; + let new_user = user::Model { ..user }; - let updated_user = user_context.update(new_user.clone()).await.unwrap(); + let updated_user = user_context.update(new_user.clone()).await.unwrap(); - let fetched_user = user::Entity::find_by_id(updated_user.id) - .one(&user_context.db_context.get_connection()) - .await - .unwrap() - .unwrap(); + let fetched_user = user::Entity::find_by_id(updated_user.id) + .one(&user_context.db_context.get_connection()) + .await + .unwrap() + .unwrap(); - assert_eq!(new_user, updated_user); - assert_eq!(updated_user, fetched_user); - } + assert_eq!(new_user, updated_user); + assert_eq!(updated_user, fetched_user); +} - #[tokio::test] - async fn update_modifies_username_test() { - let (user_context, user) = seed_db().await; +#[tokio::test] +async fn update_modifies_username_test() { + let (user_context, user) = seed_db().await; - let user = user::Model { - username: "tester1".into(), - ..user.clone() - }; + let user = user::Model { + username: "tester1".into(), + ..user.clone() + }; - user::Entity::insert(user.clone().into_active_model()) - .exec(&user_context.db_context.get_connection()) - .await - .unwrap(); + user::Entity::insert(user.clone().into_active_model()) + .exec(&user_context.db_context.get_connection()) + .await + .unwrap(); - let new_user = user::Model { - username: "tester2".into(), - ..user.clone() - }; + let new_user = user::Model { + username: "tester2".into(), + ..user.clone() + }; - let updated_user = user_context.update(new_user.clone()).await.unwrap(); + let updated_user = user_context.update(new_user.clone()).await.unwrap(); - assert_ne!(user, updated_user); - assert_ne!(user, new_user); - } + assert_ne!(user, updated_user); + assert_ne!(user, new_user); +} - #[tokio::test] - async fn update_modifies_email_test() { - let (user_context, user) = seed_db().await; +#[tokio::test] +async fn update_modifies_email_test() { + let (user_context, user) = seed_db().await; - let user = user::Model { - email: "tester1@mail.dk".into(), - ..user.clone() - }; + let user = user::Model { + email: "tester1@mail.dk".into(), + ..user.clone() + }; - user::Entity::insert(user.clone().into_active_model()) - .exec(&user_context.db_context.get_connection()) - .await - .unwrap(); + user::Entity::insert(user.clone().into_active_model()) + .exec(&user_context.db_context.get_connection()) + .await + .unwrap(); - let new_user = user::Model { - email: "tester2@mail.dk".into(), - ..user.clone() - }; + let new_user = user::Model { + email: "tester2@mail.dk".into(), + ..user.clone() + }; - let updated_user = user_context.update(new_user.clone()).await.unwrap(); + let updated_user = user_context.update(new_user.clone()).await.unwrap(); - assert_ne!(user, updated_user); - assert_ne!(user, new_user); - } + assert_ne!(user, updated_user); + assert_ne!(user, new_user); +} - #[tokio::test] - async fn update_modifies_password_test() { - let (user_context, user) = seed_db().await; +#[tokio::test] +async fn update_modifies_password_test() { + let (user_context, user) = seed_db().await; - let user = user::Model { - password: "12345".into(), - ..user.clone() - }; + let user = user::Model { + password: "12345".into(), + ..user.clone() + }; - user::Entity::insert(user.clone().into_active_model()) - .exec(&user_context.db_context.get_connection()) - .await - .unwrap(); + user::Entity::insert(user.clone().into_active_model()) + .exec(&user_context.db_context.get_connection()) + .await + .unwrap(); - let new_user = user::Model { - password: "123456".into(), - ..user.clone() - }; + let new_user = user::Model { + password: "123456".into(), + ..user.clone() + }; - let updated_user = user_context.update(new_user.clone()).await.unwrap(); + let updated_user = user_context.update(new_user.clone()).await.unwrap(); - assert_ne!(user, updated_user); - assert_ne!(user, new_user); - } + assert_ne!(user, updated_user); + assert_ne!(user, new_user); +} - #[tokio::test] - async fn update_does_not_modify_id_test() { - let (user_context, user) = seed_db().await; +#[tokio::test] +async fn update_does_not_modify_id_test() { + let (user_context, user) = seed_db().await; - user::Entity::insert(user.clone().into_active_model()) - .exec(&user_context.db_context.get_connection()) - .await - .unwrap(); + user::Entity::insert(user.clone().into_active_model()) + .exec(&user_context.db_context.get_connection()) + .await + .unwrap(); - let updated_user = user::Model { - id: user.id + 1, - ..user - }; + let updated_user = user::Model { + id: user.id + 1, + ..user + }; - let res = user_context.update(updated_user.clone()).await; + let res = user_context.update(updated_user.clone()).await; - assert!(matches!(res.unwrap_err(), DbErr::RecordNotUpdated)); - } + assert!(matches!(res.unwrap_err(), DbErr::RecordNotUpdated)); +} - #[tokio::test] - async fn update_non_unique_username_test() { - // Setting up database and user context - let (user_context, _) = seed_db().await; +#[tokio::test] +async fn update_non_unique_username_test() { + // Setting up database and user context + let (user_context, _) = seed_db().await; - let users = create_users(2); + let users = create_users(2); - user::Entity::insert_many(to_active_models!(users.clone())) - .exec(&user_context.db_context.get_connection()) - .await - .unwrap(); + user::Entity::insert_many(to_active_models!(users.clone())) + .exec(&user_context.db_context.get_connection()) + .await + .unwrap(); - let new_user = user::Model { - username: users[1].clone().username, - ..users[0].clone() - }; + let new_user = user::Model { + username: users[1].clone().username, + ..users[0].clone() + }; - let updated_user = user_context.update(new_user.clone()).await; + let updated_user = user_context.update(new_user.clone()).await; - // Assert if the new_user, created_user, and fetched_user are the same - assert!(matches!( - updated_user.unwrap_err().sql_err(), - Some(SqlErr::UniqueConstraintViolation(_)) - )); - } + // Assert if the new_user, created_user, and fetched_user are the same + assert!(matches!( + updated_user.unwrap_err().sql_err(), + Some(SqlErr::UniqueConstraintViolation(_)) + )); +} - #[tokio::test] - async fn update_non_unique_email_test() { - // Setting up database and user context - let (user_context, _) = seed_db().await; +#[tokio::test] +async fn update_non_unique_email_test() { + // Setting up database and user context + let (user_context, _) = seed_db().await; - // Creates a model of the user which will be created - let users = create_users(2); + // Creates a model of the user which will be created + let users = create_users(2); - user::Entity::insert_many(to_active_models!(users.clone())) - .exec(&user_context.db_context.get_connection()) - .await - .unwrap(); + user::Entity::insert_many(to_active_models!(users.clone())) + .exec(&user_context.db_context.get_connection()) + .await + .unwrap(); - let new_user = user::Model { - email: users[1].clone().email, - ..users[0].clone() - }; + let new_user = user::Model { + email: users[1].clone().email, + ..users[0].clone() + }; - let updated_user = user_context.update(new_user.clone()).await; + let updated_user = user_context.update(new_user.clone()).await; - // Assert if the new_user, created_user, and fetched_user are the same - assert!(matches!( - updated_user.unwrap_err().sql_err(), - Some(SqlErr::UniqueConstraintViolation(_)) - )); - } + // Assert if the new_user, created_user, and fetched_user are the same + assert!(matches!( + updated_user.unwrap_err().sql_err(), + Some(SqlErr::UniqueConstraintViolation(_)) + )); +} - #[tokio::test] - async fn update_non_existing_id_test() { - // Setting up database and user context - let (user_context, user) = seed_db().await; +#[tokio::test] +async fn update_non_existing_id_test() { + // Setting up database and user context + let (user_context, user) = seed_db().await; - let updated_user = user_context.update(user.clone()).await; + let updated_user = user_context.update(user.clone()).await; - // Assert if the new_user, created_user, and fetched_user are the same - assert!(matches!(updated_user.unwrap_err(), DbErr::RecordNotUpdated)); - } + // Assert if the new_user, created_user, and fetched_user are the same + assert!(matches!(updated_user.unwrap_err(), DbErr::RecordNotUpdated)); +} - #[tokio::test] - async fn delete_test() { - // Setting up database and user context - let (user_context, user) = seed_db().await; +#[tokio::test] +async fn delete_test() { + // Setting up database and user context + let (user_context, user) = seed_db().await; - user::Entity::insert(user.clone().into_active_model()) - .exec(&user_context.db_context.get_connection()) - .await - .unwrap(); + user::Entity::insert(user.clone().into_active_model()) + .exec(&user_context.db_context.get_connection()) + .await + .unwrap(); - let deleted_user = user_context.delete(user.id).await.unwrap(); + let deleted_user = user_context.delete(user.id).await.unwrap(); - let all_users = user::Entity::find() - .all(&user_context.db_context.get_connection()) - .await - .unwrap(); + let all_users = user::Entity::find() + .all(&user_context.db_context.get_connection()) + .await + .unwrap(); - assert_eq!(user, deleted_user); - assert!(all_users.is_empty()); - } + assert_eq!(user, deleted_user); + assert!(all_users.is_empty()); +} - #[tokio::test] - async fn delete_cascade_model_test() { - // Setting up database and user context - let (user_context, user) = seed_db().await; - - let model = create_models(1, user.clone().id)[0].clone(); - - user::Entity::insert(user.clone().into_active_model()) - .exec(&user_context.db_context.get_connection()) - .await - .unwrap(); - model::Entity::insert(model.clone().into_active_model()) - .exec(&user_context.db_context.get_connection()) - .await - .unwrap(); - - user_context.delete(user.id).await.unwrap(); - - let all_users = user::Entity::find() - .all(&user_context.db_context.get_connection()) - .await - .unwrap(); - let all_models = model::Entity::find() - .all(&user_context.db_context.get_connection()) - .await - .unwrap(); - - assert_eq!(all_users.len(), 0); - assert_eq!(all_models.len(), 0); - } +#[tokio::test] +async fn delete_cascade_model_test() { + // Setting up database and user context + let (user_context, user) = seed_db().await; + + let model = create_models(1, user.clone().id)[0].clone(); + + user::Entity::insert(user.clone().into_active_model()) + .exec(&user_context.db_context.get_connection()) + .await + .unwrap(); + model::Entity::insert(model.clone().into_active_model()) + .exec(&user_context.db_context.get_connection()) + .await + .unwrap(); + + user_context.delete(user.id).await.unwrap(); + + let all_users = user::Entity::find() + .all(&user_context.db_context.get_connection()) + .await + .unwrap(); + let all_models = model::Entity::find() + .all(&user_context.db_context.get_connection()) + .await + .unwrap(); + + assert_eq!(all_users.len(), 0); + assert_eq!(all_models.len(), 0); +} - #[tokio::test] - async fn delete_access_model_test() { - // Setting up database and user context - let (user_context, user) = seed_db().await; - - let model = create_models(1, user.clone().id)[0].clone(); - let access = create_accesses(1, user.clone().id, model.clone().id)[0].clone(); - - user::Entity::insert(user.clone().into_active_model()) - .exec(&user_context.db_context.get_connection()) - .await - .unwrap(); - model::Entity::insert(model.clone().into_active_model()) - .exec(&user_context.db_context.get_connection()) - .await - .unwrap(); - access::Entity::insert(access.clone().into_active_model()) - .exec(&user_context.db_context.get_connection()) - .await - .unwrap(); - - user_context.delete(user.id).await.unwrap(); - - let all_users = user::Entity::find() - .all(&user_context.db_context.get_connection()) - .await - .unwrap(); - let all_models = model::Entity::find() - .all(&user_context.db_context.get_connection()) - .await - .unwrap(); - let all_accesses = access::Entity::find() - .all(&user_context.db_context.get_connection()) - .await - .unwrap(); - - assert_eq!(all_users.len(), 0); - assert_eq!(all_models.len(), 0); - assert_eq!(all_accesses.len(), 0); - } +#[tokio::test] +async fn delete_access_model_test() { + // Setting up database and user context + let (user_context, user) = seed_db().await; + + let model = create_models(1, user.clone().id)[0].clone(); + let access = create_accesses(1, user.clone().id, model.clone().id)[0].clone(); + + user::Entity::insert(user.clone().into_active_model()) + .exec(&user_context.db_context.get_connection()) + .await + .unwrap(); + model::Entity::insert(model.clone().into_active_model()) + .exec(&user_context.db_context.get_connection()) + .await + .unwrap(); + access::Entity::insert(access.clone().into_active_model()) + .exec(&user_context.db_context.get_connection()) + .await + .unwrap(); + + user_context.delete(user.id).await.unwrap(); + + let all_users = user::Entity::find() + .all(&user_context.db_context.get_connection()) + .await + .unwrap(); + let all_models = model::Entity::find() + .all(&user_context.db_context.get_connection()) + .await + .unwrap(); + let all_accesses = access::Entity::find() + .all(&user_context.db_context.get_connection()) + .await + .unwrap(); + + assert_eq!(all_users.len(), 0); + assert_eq!(all_models.len(), 0); + assert_eq!(all_accesses.len(), 0); +} - #[tokio::test] - async fn delete_cascade_session_test() { - // Setting up database and user context - let (user_context, user) = seed_db().await; - - let session = create_sessions(1, user.clone().id)[0].clone(); - - user::Entity::insert(user.clone().into_active_model()) - .exec(&user_context.db_context.get_connection()) - .await - .unwrap(); - session::Entity::insert(session.clone().into_active_model()) - .exec(&user_context.db_context.get_connection()) - .await - .unwrap(); - - user_context.delete(user.id).await.unwrap(); - - let all_users = user::Entity::find() - .all(&user_context.db_context.get_connection()) - .await - .unwrap(); - let all_sessions = session::Entity::find() - .all(&user_context.db_context.get_connection()) - .await - .unwrap(); - - assert_eq!(all_users.len(), 0); - assert_eq!(all_sessions.len(), 0); - } +#[tokio::test] +async fn delete_cascade_session_test() { + // Setting up database and user context + let (user_context, user) = seed_db().await; + + let session = create_sessions(1, user.clone().id)[0].clone(); + + user::Entity::insert(user.clone().into_active_model()) + .exec(&user_context.db_context.get_connection()) + .await + .unwrap(); + session::Entity::insert(session.clone().into_active_model()) + .exec(&user_context.db_context.get_connection()) + .await + .unwrap(); + + user_context.delete(user.id).await.unwrap(); + + let all_users = user::Entity::find() + .all(&user_context.db_context.get_connection()) + .await + .unwrap(); + let all_sessions = session::Entity::find() + .all(&user_context.db_context.get_connection()) + .await + .unwrap(); + + assert_eq!(all_users.len(), 0); + assert_eq!(all_sessions.len(), 0); +} - #[tokio::test] - async fn delete_non_existing_id_test() { - // Setting up database and user context - let (user_context, _) = seed_db().await; +#[tokio::test] +async fn delete_non_existing_id_test() { + // Setting up database and user context + let (user_context, _) = seed_db().await; - let deleted_user = user_context.delete(1).await; + let deleted_user = user_context.delete(1).await; - // Assert if the new_user, created_user, and fetched_user are the same - assert!(matches!( - deleted_user.unwrap_err(), - DbErr::RecordNotFound(_) - )); - } + // Assert if the new_user, created_user, and fetched_user are the same + assert!(matches!( + deleted_user.unwrap_err(), + DbErr::RecordNotFound(_) + )); +} - #[tokio::test] - async fn get_by_username_test() { - let (user_context, user) = seed_db().await; +#[tokio::test] +async fn get_by_username_test() { + let (user_context, user) = seed_db().await; - user::Entity::insert(user.clone().into_active_model()) - .exec(&user_context.db_context.get_connection()) - .await - .unwrap(); + user::Entity::insert(user.clone().into_active_model()) + .exec(&user_context.db_context.get_connection()) + .await + .unwrap(); - // Fetches the user created using the 'get_by_username' function - let fetched_user = user_context - .get_by_username(user.username.clone()) - .await - .unwrap(); + // Fetches the user created using the 'get_by_username' function + let fetched_user = user_context + .get_by_username(user.username.clone()) + .await + .unwrap(); - // Assert if the fetched user is the same as the created user - assert_eq!(fetched_user.unwrap().username, user.username); - } + // Assert if the fetched user is the same as the created user + assert_eq!(fetched_user.unwrap().username, user.username); +} - #[tokio::test] - async fn get_by_email_test() { - let (user_context, user) = seed_db().await; +#[tokio::test] +async fn get_by_email_test() { + let (user_context, user) = seed_db().await; - user::Entity::insert(user.clone().into_active_model()) - .exec(&user_context.db_context.get_connection()) - .await - .unwrap(); + user::Entity::insert(user.clone().into_active_model()) + .exec(&user_context.db_context.get_connection()) + .await + .unwrap(); - let fetched_user = user_context.get_by_email(user.email.clone()).await.unwrap(); + let fetched_user = user_context.get_by_email(user.email.clone()).await.unwrap(); - assert_eq!(fetched_user.unwrap().email, user.email); - } + assert_eq!(fetched_user.unwrap().email, user.email); }