From baaecd37d1dfcd2734804e25547997d32ae8f5ae Mon Sep 17 00:00:00 2001 From: Agit Rubar Demir <61833677+agitrubard@users.noreply.github.com> Date: Thu, 2 Jan 2025 19:48:59 +0300 Subject: [PATCH] AYS-640 | Create and Update Role Flows Have Been Fixed with Same Name for Different Institutions (#422) --- .../org/ays/auth/port/AysRoleReadPort.java | 9 +- .../ays/auth/port/adapter/AysRoleAdapter.java | 12 +- .../auth/repository/AysRoleRepository.java | 9 +- .../impl/AysRoleCreateServiceImpl.java | 58 +++-- .../impl/AysRoleUpdateServiceImpl.java | 44 ++-- .../auth/controller/AysRoleEndToEndTest.java | 231 ++++++++++++++++- .../auth/port/adapter/AysRoleAdapterTest.java | 18 +- .../impl/AysRoleCreateServiceImplTest.java | 74 +++--- .../impl/AysRoleUpdateServiceImplTest.java | 244 ++++++++++-------- .../institution/model/InstitutionBuilder.java | 6 + 10 files changed, 500 insertions(+), 205 deletions(-) diff --git a/src/main/java/org/ays/auth/port/AysRoleReadPort.java b/src/main/java/org/ays/auth/port/AysRoleReadPort.java index 60a50efca..700e53ad2 100644 --- a/src/main/java/org/ays/auth/port/AysRoleReadPort.java +++ b/src/main/java/org/ays/auth/port/AysRoleReadPort.java @@ -53,12 +53,13 @@ public interface AysRoleReadPort { List findAllByIds(Set ids); /** - * Retrieves a role by its name. + * Retrieves a role by its name and institution ID. * - * @param name The name of the role to retrieve. - * @return An optional containing the role if found, otherwise empty. + * @param name The name of the role to retrieve. + * @param institutionId The ID of the institution to which the role belongs. + * @return An {@link Optional} containing the role if found, otherwise empty. */ - Optional findByName(String name); + Optional findByNameAndInstitutionId(String name, String institutionId); /** * Checks if any users are assigned to a role identified by its ID. diff --git a/src/main/java/org/ays/auth/port/adapter/AysRoleAdapter.java b/src/main/java/org/ays/auth/port/adapter/AysRoleAdapter.java index 4a4b8e4a9..ca2438793 100644 --- a/src/main/java/org/ays/auth/port/adapter/AysRoleAdapter.java +++ b/src/main/java/org/ays/auth/port/adapter/AysRoleAdapter.java @@ -106,14 +106,14 @@ public List findAllByIds(Set ids) { /** - * Retrieves an {@link AysRole} by its name. + * Retrieves an {@link AysRole} by its name and institution ID. * - * @param name The name of the role to retrieve. - * @return An optional containing the {@link AysRole} if found, otherwise empty. + * @param name The name of the role to retrieve. + * @param institutionId The ID of the institution to which the role belongs. + * @return An {@link Optional} containing the {@link AysRole} if found, otherwise empty. */ - @Override - public Optional findByName(final String name) { - final Optional roleEntity = roleRepository.findByName(name); + public Optional findByNameAndInstitutionId(final String name, final String institutionId) { + final Optional roleEntity = roleRepository.findByNameAndInstitutionId(name, institutionId); return roleEntity.map(roleEntityToDomainMapper::map); } diff --git a/src/main/java/org/ays/auth/repository/AysRoleRepository.java b/src/main/java/org/ays/auth/repository/AysRoleRepository.java index 395c22e5d..2b545e0e3 100644 --- a/src/main/java/org/ays/auth/repository/AysRoleRepository.java +++ b/src/main/java/org/ays/auth/repository/AysRoleRepository.java @@ -31,12 +31,13 @@ public interface AysRoleRepository extends JpaRepository, List findAllByInstitutionIdAndStatus(String institutionId, AysRoleStatus status); /** - * Finds a {@link AysRoleEntity} by the given role name. + * Finds a {@link AysRoleEntity} by its name and institution ID. * - * @param name the name of the role - * @return an {@link Optional} containing the {@link AysRoleEntity} if found, or empty if not found + * @param name The name of the role. + * @param institutionId The ID of the institution to which the role belongs. + * @return An {@link Optional} containing the {@link AysRoleEntity} if found, otherwise empty. */ - Optional findByName(String name); + Optional findByNameAndInstitutionId(String name, String institutionId); /** * Checks if any users are assigned to the role identified by the given role ID. diff --git a/src/main/java/org/ays/auth/service/impl/AysRoleCreateServiceImpl.java b/src/main/java/org/ays/auth/service/impl/AysRoleCreateServiceImpl.java index 10273a7ad..917d528f1 100644 --- a/src/main/java/org/ays/auth/service/impl/AysRoleCreateServiceImpl.java +++ b/src/main/java/org/ays/auth/service/impl/AysRoleCreateServiceImpl.java @@ -41,25 +41,31 @@ class AysRoleCreateServiceImpl implements AysRoleCreateService { /** * Creates a new role based on the provided create request. *

- * This method validates the uniqueness of the role name, checks the existence of permissions, - * and saves the new role with the associated permissions. + * This method performs the following steps: + *

    + *
  • Validates the uniqueness of the role name within the institution.
  • + *
  • Checks if the provided permission IDs exist.
  • + *
  • Ensures the user has the appropriate authority to assign permissions, especially super permissions.
  • + *
  • Saves the new role with its associated permissions.
  • + *
*

* - * @param createRequest the request object containing the role name and permission IDs - * @throws AysRoleAlreadyExistsByNameException if a role with the same name already exists - * @throws AysPermissionNotExistException if any of the specified permission IDs do not exist - * @throws AysUserNotSuperAdminException if the current user is not authorized to assign super permissions + * @param createRequest The request object containing the role name and permission IDs. + * @throws AysRoleAlreadyExistsByNameException If a role with the same name already exists in the institution. + * @throws AysPermissionNotExistException If any of the specified permission IDs do not exist. + * @throws AysUserNotSuperAdminException If the current user is not authorized to assign super permissions. */ @Override public void create(final AysRoleCreateRequest createRequest) { - this.checkExistingRoleName(createRequest.getName()); + final String institutionId = identity.getInstitutionId(); + this.checkExistingRoleName(createRequest.getName(), institutionId); final List permissions = this.checkExistingPermissionsAndGet(createRequest.getPermissionIds()); final AysRole role = AysRole.builder() .name(createRequest.getName()) - .institution(Institution.builder().id(identity.getInstitutionId()).build()) + .institution(Institution.builder().id(institutionId).build()) .permissions(permissions) .status(AysRoleStatus.ACTIVE) .build(); @@ -68,25 +74,35 @@ public void create(final AysRoleCreateRequest createRequest) { } /** - * Checks if a role with the specified name already exists. + * Checks if a role with the specified name already exists within the institution. * - * @param name the name of the role to check - * @throws AysRoleAlreadyExistsByNameException if a role with the same name already exists + * @param name The name of the role to check. + * @param institutionId The ID of the institution where the role is being created. + * @throws AysRoleAlreadyExistsByNameException If a role with the same name already exists in the institution. */ - private void checkExistingRoleName(final String name) { - roleReadPort.findByName(name).ifPresent(role -> { - throw new AysRoleAlreadyExistsByNameException(name); - }); + private void checkExistingRoleName(final String name, final String institutionId) { + roleReadPort.findByNameAndInstitutionId(name, institutionId) + .ifPresent(role -> { + throw new AysRoleAlreadyExistsByNameException(name); + }); } /** - * Checks the existence of permissions based on the provided permission IDs. - * Verifies if all permission IDs exist and validates super admin restrictions. + * Checks the existence of permissions based on the provided permission IDs + * and ensures that the user has the authority to assign the permissions. + *

+ * This method performs the following steps: + *

    + *
  • Retrieves all permissions corresponding to the provided IDs.
  • + *
  • Validates that all requested permissions exist in the system.
  • + *
  • Ensures that super permissions can only be assigned by super admins.
  • + *
+ *

* - * @param permissionIds the set of permission IDs to check - * @return the list of permissions corresponding to the provided IDs - * @throws AysPermissionNotExistException if any of the permission IDs do not exist - * @throws AysUserNotSuperAdminException if the current user is not authorized to assign super permissions + * @param permissionIds The set of permission IDs to check. + * @return A list of {@link AysPermission} objects corresponding to the provided IDs. + * @throws AysPermissionNotExistException If any of the permission IDs do not exist. + * @throws AysUserNotSuperAdminException If the current user is not authorized to assign super permissions. */ private List checkExistingPermissionsAndGet(final Set permissionIds) { final List permissions = permissionReadPort.findAllByIds(permissionIds); diff --git a/src/main/java/org/ays/auth/service/impl/AysRoleUpdateServiceImpl.java b/src/main/java/org/ays/auth/service/impl/AysRoleUpdateServiceImpl.java index 70c497371..537229d67 100644 --- a/src/main/java/org/ays/auth/service/impl/AysRoleUpdateServiceImpl.java +++ b/src/main/java/org/ays/auth/service/impl/AysRoleUpdateServiceImpl.java @@ -44,14 +44,19 @@ class AysRoleUpdateServiceImpl implements AysRoleUpdateService { /** * Updates an existing role identified by its ID. *

- * This method performs checks to ensure the role name is unique and validates the existence of provided permissions. - * It also verifies that the role belongs to the same institution as the current user's institution. + * This method performs the following steps: + *

    + *
  • Ensures the role exists and belongs to the same institution as the current user.
  • + *
  • Validates the uniqueness of the role name within the institution.
  • + *
  • Checks if the provided permissions exist and validates the user's authorization for assigning super permissions.
  • + *
  • Updates the role's attributes such as name and permissions, and persists the changes.
  • + *
*

* * @param id The ID of the role to update. * @param updateRequest The request object containing updated data for the role. * @throws AysRoleAlreadyExistsByNameException if a role with the same name already exists, excluding the current role ID. - * @throws AysPermissionNotExistException if any of the permission IDs provided do not exist. + * @throws AysPermissionNotExistException if any of the specified permission IDs do not exist. * @throws AysUserNotSuperAdminException if the current user does not have super admin privileges required for assigning super permissions. * @throws AysRoleNotExistByIdException if the role with the given ID does not exist or does not belong to the current user's institution. */ @@ -59,13 +64,14 @@ class AysRoleUpdateServiceImpl implements AysRoleUpdateService { public void update(final String id, final AysRoleUpdateRequest updateRequest) { + final String institutionId = identity.getInstitutionId(); final AysRole role = roleReadPort.findById(id) - .filter(roleFromDatabase -> identity.getInstitutionId().equals(roleFromDatabase.getInstitution().getId())) + .filter(roleFromDatabase -> institutionId.equals(roleFromDatabase.getInstitution().getId())) .orElseThrow(() -> new AysRoleNotExistByIdException(id)); final boolean isRoleNameChanged = !role.getName().equals(updateRequest.getName()); if (isRoleNameChanged) { - this.checkExistingRoleNameByWithoutId(id, updateRequest.getName()); + this.checkExistingRoleNameByWithoutId(id, updateRequest.getName(), institutionId); } final Set existingPermissionIds = role.getPermissions().stream() @@ -86,13 +92,18 @@ public void update(final String id, /** * Checks the existence of another role with the same name, excluding the current role ID. + *

+ * This method ensures that the role name is unique within the institution for all roles + * except the one being updated. + *

* - * @param id The ID of the role being updated. - * @param name The name to check for uniqueness. + * @param id The ID of the role being updated. + * @param name The name to check for uniqueness. + * @param institutionId The ID of the institution to which the role belongs. * @throws AysRoleAlreadyExistsByNameException if a role with the same name already exists, excluding the current role ID. */ - private void checkExistingRoleNameByWithoutId(final String id, final String name) { - roleReadPort.findByName(name) + private void checkExistingRoleNameByWithoutId(final String id, final String name, final String institutionId) { + roleReadPort.findByNameAndInstitutionId(name, institutionId) .filter(role -> !id.equals(role.getId())) .ifPresent(role -> { throw new AysRoleAlreadyExistsByNameException(name); @@ -102,14 +113,17 @@ private void checkExistingRoleNameByWithoutId(final String id, final String name /** * Validates the specified permission IDs and checks user authorization. *

- * This method verifies if all permission IDs exist in the system and checks if the user - * has appropriate access level for super permissions. Only super admin users can assign - * super permissions. + * This method performs the following steps: + *

    + *
  • Verifies if all provided permission IDs exist in the system.
  • + *
  • Ensures only super admin users can assign super permissions.
  • + *
  • Throws appropriate exceptions for missing permissions or unauthorized access attempts.
  • + *
*

* - * @param permissionIds the set of permission IDs to validate - * @throws AysPermissionNotExistException if any of the specified permissions do not exist - * @throws AysUserNotSuperAdminException if a non-super admin user attempts to assign super permissions + * @param permissionIds the set of permission IDs to validate. + * @throws AysPermissionNotExistException if any of the specified permissions do not exist. + * @throws AysUserNotSuperAdminException if a non-super admin user attempts to assign super permissions. */ private void validatePermissions(final Set permissionIds) { diff --git a/src/test/java/org/ays/auth/controller/AysRoleEndToEndTest.java b/src/test/java/org/ays/auth/controller/AysRoleEndToEndTest.java index fb6a50670..bc2e3a51f 100644 --- a/src/test/java/org/ays/auth/controller/AysRoleEndToEndTest.java +++ b/src/test/java/org/ays/auth/controller/AysRoleEndToEndTest.java @@ -26,6 +26,7 @@ import org.ays.common.util.AysRandomUtil; import org.ays.institution.model.Institution; import org.ays.institution.model.InstitutionBuilder; +import org.ays.institution.port.InstitutionSavePort; import org.ays.util.AysMockMvcRequestBuilders; import org.ays.util.AysMockResultMatchersBuilders; import org.ays.util.AysValidTestData; @@ -45,6 +46,9 @@ class AysRoleEndToEndTest extends AysEndToEndTest { + @Autowired + private InstitutionSavePort institutionSavePort; + @Autowired private AysRoleSavePort roleSavePort; @@ -319,7 +323,10 @@ void givenValidRoleCreateRequest_whenSuperRoleCreated_thenReturnSuccess() throws .doesNotExist()); // Verify - Optional role = roleReadPort.findByName(createRequest.getName()); + Optional role = roleReadPort.findByNameAndInstitutionId( + createRequest.getName(), + AysValidTestData.SuperAdmin.INSTITUTION_ID + ); Assertions.assertTrue(role.isPresent()); Assertions.assertNotNull(role.get().getId()); @@ -331,6 +338,9 @@ void givenValidRoleCreateRequest_whenSuperRoleCreated_thenReturnSuccess() throws .anyMatch(permission -> permission.getId().equals(permissionId)) )); Assertions.assertTrue(UUIDTestUtil.isValid(role.get().getCreatedUser())); + Assertions.assertNotNull(role.get().getCreatedAt()); + Assertions.assertNull(role.get().getUpdatedUser()); + Assertions.assertNull(role.get().getUpdatedAt()); } @Test @@ -361,7 +371,93 @@ void givenValidRoleCreateRequest_whenRoleCreated_thenReturnSuccess() throws Exce .doesNotExist()); // Verify - Optional role = roleReadPort.findByName(createRequest.getName()); + Optional role = roleReadPort.findByNameAndInstitutionId( + createRequest.getName(), + AysValidTestData.Admin.INSTITUTION_ID + ); + + Assertions.assertTrue(role.isPresent()); + Assertions.assertNotNull(role.get().getId()); + Assertions.assertNotNull(role.get().getInstitution()); + Assertions.assertEquals(createRequest.getName(), role.get().getName()); + Assertions.assertEquals(AysRoleStatus.ACTIVE, role.get().getStatus()); + createRequest.getPermissionIds().forEach(permissionId -> Assertions.assertTrue( + role.get().getPermissions().stream() + .anyMatch(permission -> permission.getId().equals(permissionId)) + )); + Assertions.assertTrue(UUIDTestUtil.isValid(role.get().getCreatedUser())); + Assertions.assertNotNull(role.get().getCreatedAt()); + Assertions.assertNull(role.get().getUpdatedUser()); + Assertions.assertNull(role.get().getUpdatedAt()); + } + + @Test + void givenValidRoleCreateRequest_whenRoleCreatedWithSameNameForDifferentInstitution_thenReturnSuccess() throws Exception { + + // Initialize + List permissions = permissionReadPort.findAllByIsSuperFalse(); + Set permissionIds = permissions.stream() + .map(AysPermission::getId) + .collect(Collectors.toSet()); + + String sameRoleName = AysRandomUtil.generateText(10); + + Institution testInstitutionOne = institutionSavePort.save( + new InstitutionBuilder() + .withValidValues() + .withoutId() + .build() + ); + roleSavePort.save( + new AysRoleBuilder() + .withValidValues() + .withoutId() + .withName(sameRoleName) + .withPermissions(permissions) + .withInstitution(testInstitutionOne) + .build() + ); + + Institution testInstitutionTwo = institutionSavePort.save( + new InstitutionBuilder() + .withValidValues() + .withoutId() + .build() + ); + roleSavePort.save( + new AysRoleBuilder() + .withValidValues() + .withoutId() + .withName(sameRoleName) + .withPermissions(permissions) + .withInstitution(testInstitutionTwo) + .build() + ); + + // Given + AysRoleCreateRequest createRequest = new AysRoleCreateRequestBuilder() + .withPermissionIds(permissionIds) + .withName(sameRoleName) + .build(); + + // Then + String endpoint = BASE_PATH.concat("/role"); + MockHttpServletRequestBuilder mockHttpServletRequestBuilder = AysMockMvcRequestBuilders + .post(endpoint, adminToken.getAccessToken(), createRequest); + + AysResponse mockResponse = AysResponseBuilder.success(); + + aysMockMvc.perform(mockHttpServletRequestBuilder, mockResponse) + .andExpect(AysMockResultMatchersBuilders.status() + .isOk()) + .andExpect(AysMockResultMatchersBuilders.response() + .doesNotExist()); + + // Verify + Optional role = roleReadPort.findByNameAndInstitutionId( + createRequest.getName(), + AysValidTestData.Admin.INSTITUTION_ID + ); Assertions.assertTrue(role.isPresent()); Assertions.assertNotNull(role.get().getId()); @@ -373,6 +469,9 @@ void givenValidRoleCreateRequest_whenRoleCreated_thenReturnSuccess() throws Exce .anyMatch(permission -> permission.getId().equals(permissionId)) )); Assertions.assertTrue(UUIDTestUtil.isValid(role.get().getCreatedUser())); + Assertions.assertNotNull(role.get().getCreatedAt()); + Assertions.assertNull(role.get().getUpdatedUser()); + Assertions.assertNull(role.get().getUpdatedAt()); } @Test @@ -404,7 +503,10 @@ void givenRoleCreateRequest_whenRequestHasSuperPermissionsAndUserIsNotSuperAdmin .doesNotHaveJsonPath()); // Verify - Optional role = roleReadPort.findByName(createRequest.getName()); + Optional role = roleReadPort.findByNameAndInstitutionId( + createRequest.getName(), + AysValidTestData.Admin.INSTITUTION_ID + ); Assertions.assertFalse(role.isPresent()); } @@ -460,40 +562,44 @@ void givenValidIdAndRoleUpdateRequest_whenSuperRoleUpdated_thenReturnSuccess() t roleFromDatabase.get().getPermissions().stream() .anyMatch(permission -> permission.getId().equals(permissionId)) )); + Assertions.assertNotNull(roleFromDatabase.get().getCreatedUser()); + Assertions.assertNotNull(roleFromDatabase.get().getCreatedAt()); Assertions.assertTrue(UUIDTestUtil.isValid(roleFromDatabase.get().getUpdatedUser())); + Assertions.assertNotNull(roleFromDatabase.get().getUpdatedAt()); } @Test void givenValidRoleUpdateRequest_whenRoleUpdated_thenReturnSuccess() throws Exception { // Initialize - List permissions = permissionReadPort.findAllByIsSuperFalse(); + List permissions = permissionReadPort.findAll(); Set permissionIds = permissions.stream() .map(AysPermission::getId) .collect(Collectors.toSet()); - + Institution institution = new InstitutionBuilder() + .withId(AysValidTestData.SuperAdmin.INSTITUTION_ID) + .build(); AysRole role = roleSavePort.save( new AysRoleBuilder() .withValidValues() .withoutId() - .withName("Admin Role 2") + .withName("Admin Role 1") .withPermissions(permissions) - .withInstitution(new InstitutionBuilder().withId(AysValidTestData.Admin.INSTITUTION_ID).build()) + .withInstitution(institution) .build() ); // Given String id = role.getId(); AysRoleUpdateRequest updateRequest = new AysRoleUpdateRequestBuilder() - .withName("Updated Role") .withPermissionIds(permissionIds) .build(); // Then String endpoint = BASE_PATH.concat("/role/").concat(id); MockHttpServletRequestBuilder mockHttpServletRequestBuilder = AysMockMvcRequestBuilders - .put(endpoint, adminToken.getAccessToken(), updateRequest); + .put(endpoint, superAdminToken.getAccessToken(), updateRequest); AysResponse mockResponse = AysResponseBuilder.success(); @@ -515,7 +621,10 @@ void givenValidRoleUpdateRequest_whenRoleUpdated_thenReturnSuccess() throws Exce roleFromDatabase.get().getPermissions().stream() .anyMatch(permission -> permission.getId().equals(permissionId)) )); + Assertions.assertNotNull(roleFromDatabase.get().getCreatedUser()); + Assertions.assertNotNull(roleFromDatabase.get().getCreatedAt()); Assertions.assertTrue(UUIDTestUtil.isValid(roleFromDatabase.get().getUpdatedUser())); + Assertions.assertNotNull(roleFromDatabase.get().getUpdatedAt()); } @Test @@ -572,7 +681,104 @@ void givenValidRoleUpdateRequest_whenPermissionsUpdatedAndNameUnchanged_thenRetu roleFromDatabase.get().getPermissions().stream() .anyMatch(permission -> permission.getId().equals(permissionId)) )); + Assertions.assertNotNull(roleFromDatabase.get().getCreatedUser()); + Assertions.assertNotNull(roleFromDatabase.get().getCreatedAt()); + Assertions.assertTrue(UUIDTestUtil.isValid(roleFromDatabase.get().getUpdatedUser())); + Assertions.assertNotNull(roleFromDatabase.get().getUpdatedAt()); + } + + @Test + void givenValidIdAndRoleUpdateRequest_whenRoleUpdatedWithSameNameForDifferentInstitution_thenReturnSuccess() throws Exception { + + // Initialize + List permissions = permissionReadPort.findAllByIsSuperFalse(); + Set permissionIds = permissions.stream() + .map(AysPermission::getId) + .collect(Collectors.toSet()); + + String sameRoleName = AysRandomUtil.generateText(10); + + Institution testInstitutionOne = institutionSavePort.save( + new InstitutionBuilder() + .withValidValues() + .withoutId() + .build() + ); + roleSavePort.save( + new AysRoleBuilder() + .withValidValues() + .withoutId() + .withName(sameRoleName) + .withPermissions(permissions) + .withInstitution(testInstitutionOne) + .build() + ); + + Institution testInstitutionTwo = institutionSavePort.save( + new InstitutionBuilder() + .withValidValues() + .withoutId() + .build() + ); + roleSavePort.save( + new AysRoleBuilder() + .withValidValues() + .withoutId() + .withName(sameRoleName) + .withPermissions(permissions) + .withInstitution(testInstitutionTwo) + .build() + ); + + Institution institution = new InstitutionBuilder() + .withId(AysValidTestData.Admin.INSTITUTION_ID) + .build(); + AysRole role = roleSavePort.save( + new AysRoleBuilder() + .withValidValues() + .withoutId() + .withName(sameRoleName) + .withPermissions(permissions) + .withInstitution(institution) + .build() + ); + + // Given + String id = role.getId(); + AysRoleUpdateRequest updateRequest = new AysRoleUpdateRequestBuilder() + .withName(sameRoleName) + .withPermissionIds(permissionIds.stream().limit(1).collect(Collectors.toSet())) + .build(); + + // Then + String endpoint = BASE_PATH.concat("/role/").concat(id); + MockHttpServletRequestBuilder mockHttpServletRequestBuilder = AysMockMvcRequestBuilders + .put(endpoint, adminToken.getAccessToken(), updateRequest); + + AysResponse mockResponse = AysResponseBuilder.success(); + + aysMockMvc.perform(mockHttpServletRequestBuilder, mockResponse) + .andExpect(AysMockResultMatchersBuilders.status() + .isOk()) + .andExpect(AysMockResultMatchersBuilders.response() + .doesNotExist()); + + // Verify + Optional roleFromDatabase = roleReadPort.findById(id); + + Assertions.assertTrue(roleFromDatabase.isPresent()); + Assertions.assertNotNull(roleFromDatabase.get().getId()); + Assertions.assertNotNull(roleFromDatabase.get().getInstitution()); + Assertions.assertEquals(updateRequest.getName(), roleFromDatabase.get().getName()); + Assertions.assertEquals(AysRoleStatus.ACTIVE, roleFromDatabase.get().getStatus()); + updateRequest.getPermissionIds().forEach(permissionId -> Assertions.assertTrue( + roleFromDatabase.get().getPermissions().stream() + .anyMatch(permission -> permission.getId().equals(permissionId)) + )); + Assertions.assertNotNull(roleFromDatabase.get().getCreatedUser()); + Assertions.assertNotNull(roleFromDatabase.get().getCreatedAt()); Assertions.assertTrue(UUIDTestUtil.isValid(roleFromDatabase.get().getUpdatedUser())); + Assertions.assertNotNull(roleFromDatabase.get().getUpdatedAt()); } @Test @@ -584,13 +790,16 @@ void givenValidIdAndRoleUpdateRequest_whenRequestHasSuperPermissionsAndUserIsNot .map(AysPermission::getId) .collect(Collectors.toSet()); + Institution institution = new InstitutionBuilder() + .withId(AysValidTestData.Admin.INSTITUTION_ID) + .build(); AysRole role = roleSavePort.save( new AysRoleBuilder() .withValidValues() .withoutId() .withName(AysRandomUtil.generateText(10)) .withPermissions(List.of(permissions.get(0))) - .withInstitution(new InstitutionBuilder().withId(AysValidTestData.Admin.INSTITUTION_ID).build()) + .withInstitution(institution) .build() ); @@ -618,6 +827,8 @@ void givenValidIdAndRoleUpdateRequest_whenRequestHasSuperPermissionsAndUserIsNot Assertions.assertTrue(roleFromDatabase.isPresent()); Assertions.assertNotEquals(updateRequest.getName(), roleFromDatabase.get().getName()); + Assertions.assertNotNull(roleFromDatabase.get().getCreatedUser()); + Assertions.assertNotNull(roleFromDatabase.get().getCreatedAt()); Assertions.assertNull(roleFromDatabase.get().getUpdatedUser()); Assertions.assertNull(roleFromDatabase.get().getUpdatedAt()); } diff --git a/src/test/java/org/ays/auth/port/adapter/AysRoleAdapterTest.java b/src/test/java/org/ays/auth/port/adapter/AysRoleAdapterTest.java index df52397fe..c3ca74455 100644 --- a/src/test/java/org/ays/auth/port/adapter/AysRoleAdapterTest.java +++ b/src/test/java/org/ays/auth/port/adapter/AysRoleAdapterTest.java @@ -276,48 +276,50 @@ void givenValidIds_whenAllRoleEntitiesNotFoundByIds_thenReturnEmptyList() { @Test - void givenValidName_whenRoleNotFoundByName_thenReturnOptionalEmpty() { + void givenValidNameAndInstitutionId_whenRoleNotFound_thenReturnOptionalEmpty() { // Given String mockName = "Test Role"; + String mockInstitutionId = "4907d8a9-dd9b-47ff-9780-b1a6074e81d6"; // When - Mockito.when(roleRepository.findByName(mockName)) + Mockito.when(roleRepository.findByNameAndInstitutionId(Mockito.anyString(), Mockito.anyString())) .thenReturn(Optional.empty()); // Then - Optional role = roleAdapter.findByName(mockName); + Optional role = roleAdapter.findByNameAndInstitutionId(mockName, mockInstitutionId); Assertions.assertFalse(role.isPresent()); // Verify Mockito.verify(roleRepository, Mockito.times(1)) - .findByName(mockName); + .findByNameAndInstitutionId(Mockito.anyString(), Mockito.anyString()); } @Test - void givenValidName_whenRoleFoundByName_thenReturnOptionalRole() { + void givenValidNameAndInstitutionId_whenRoleFound_thenReturnOptionalRole() { // Given String mockName = "Test Role"; + String mockInstitutionId = "99921b54-5a19-4552-afb7-c3e8ffde3dd3"; // When AysRoleEntity mockRoleEntity = new AysRoleEntityBuilder() .withValidValues() .withName(mockName) .build(); - Mockito.when(roleRepository.findByName(mockName)) + Mockito.when(roleRepository.findByNameAndInstitutionId(mockName, mockInstitutionId)) .thenReturn(Optional.of(mockRoleEntity)); // Then - Optional role = roleAdapter.findByName(mockName); + Optional role = roleAdapter.findByNameAndInstitutionId(mockName, mockInstitutionId); Assertions.assertTrue(role.isPresent()); Assertions.assertEquals(mockName, role.get().getName()); // Verify Mockito.verify(roleRepository, Mockito.times(1)) - .findByName(mockName); + .findByNameAndInstitutionId(mockName, mockInstitutionId); } diff --git a/src/test/java/org/ays/auth/service/impl/AysRoleCreateServiceImplTest.java b/src/test/java/org/ays/auth/service/impl/AysRoleCreateServiceImplTest.java index 1362849ed..80afc7d72 100644 --- a/src/test/java/org/ays/auth/service/impl/AysRoleCreateServiceImplTest.java +++ b/src/test/java/org/ays/auth/service/impl/AysRoleCreateServiceImplTest.java @@ -13,7 +13,6 @@ import org.ays.auth.port.AysPermissionReadPort; import org.ays.auth.port.AysRoleReadPort; import org.ays.auth.port.AysRoleSavePort; -import org.ays.common.util.AysRandomUtil; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; @@ -50,7 +49,10 @@ void givenRoleCreateRequest_whenFieldsValid_thenCreateSuperRole() { .build(); // When - Mockito.when(roleReadPort.findByName(Mockito.anyString())) + Mockito.when(identity.getInstitutionId()) + .thenReturn("3ec91697-ebc9-42b2-8d4c-c0e792b027cb"); + + Mockito.when(roleReadPort.findByNameAndInstitutionId(Mockito.anyString(), Mockito.anyString())) .thenReturn(Optional.empty()); List mockPermissions = new ArrayList<>(); @@ -68,9 +70,6 @@ void givenRoleCreateRequest_whenFieldsValid_thenCreateSuperRole() { Mockito.when(identity.isSuperAdmin()) .thenReturn(true); - Mockito.when(identity.getInstitutionId()) - .thenReturn(AysRandomUtil.generateUUID()); - Mockito.when(roleSavePort.save(Mockito.any(AysRole.class))) .thenReturn(Mockito.mock(AysRole.class)); @@ -78,8 +77,11 @@ void givenRoleCreateRequest_whenFieldsValid_thenCreateSuperRole() { roleCreateService.create(mockCreateRequest); // Verify + Mockito.verify(identity, Mockito.times(1)) + .getInstitutionId(); + Mockito.verify(roleReadPort, Mockito.times(1)) - .findByName(Mockito.anyString()); + .findByNameAndInstitutionId(Mockito.anyString(), Mockito.anyString()); Mockito.verify(permissionReadPort, Mockito.times(1)) .findAllByIds(Mockito.anySet()); @@ -90,9 +92,6 @@ void givenRoleCreateRequest_whenFieldsValid_thenCreateSuperRole() { Mockito.verify(identity, Mockito.never()) .getUserId(); - Mockito.verify(identity, Mockito.times(1)) - .getInstitutionId(); - Mockito.verify(roleSavePort, Mockito.times(1)) .save(Mockito.any(AysRole.class)); } @@ -105,7 +104,10 @@ void givenRoleCreateRequest_whenFieldsValid_thenCreateRole() { .build(); // When - Mockito.when(roleReadPort.findByName(Mockito.anyString())) + Mockito.when(identity.getInstitutionId()) + .thenReturn("5e0e83da-73b2-4cbb-9753-10f17d63ab3b"); + + Mockito.when(roleReadPort.findByNameAndInstitutionId(Mockito.anyString(), Mockito.anyString())) .thenReturn(Optional.empty()); List mockPermissions = new ArrayList<>(); @@ -123,9 +125,6 @@ void givenRoleCreateRequest_whenFieldsValid_thenCreateRole() { Mockito.when(identity.isSuperAdmin()) .thenReturn(false); - Mockito.when(identity.getInstitutionId()) - .thenReturn(AysRandomUtil.generateUUID()); - Mockito.when(roleSavePort.save(Mockito.any(AysRole.class))) .thenReturn(Mockito.mock(AysRole.class)); @@ -133,8 +132,11 @@ void givenRoleCreateRequest_whenFieldsValid_thenCreateRole() { roleCreateService.create(mockCreateRequest); // Verify + Mockito.verify(identity, Mockito.times(1)) + .getInstitutionId(); + Mockito.verify(roleReadPort, Mockito.times(1)) - .findByName(Mockito.anyString()); + .findByNameAndInstitutionId(Mockito.anyString(), Mockito.anyString()); Mockito.verify(permissionReadPort, Mockito.times(1)) .findAllByIds(Mockito.anySet()); @@ -145,9 +147,6 @@ void givenRoleCreateRequest_whenFieldsValid_thenCreateRole() { Mockito.verify(identity, Mockito.never()) .getUserId(); - Mockito.verify(identity, Mockito.times(1)) - .getInstitutionId(); - Mockito.verify(roleSavePort, Mockito.times(1)) .save(Mockito.any(AysRole.class)); } @@ -160,7 +159,10 @@ void givenRoleCreateRequest_whenNameAlreadyExist_thenThrowAysRoleAlreadyExistsBy .build(); // When - Mockito.when(roleReadPort.findByName(Mockito.anyString())) + Mockito.when(identity.getInstitutionId()) + .thenReturn("04ba9be6-d1bc-4c0a-9188-336af6faa7a3"); + + Mockito.when(roleReadPort.findByNameAndInstitutionId(Mockito.anyString(), Mockito.anyString())) .thenReturn(Optional.of(Mockito.mock(AysRole.class))); // Then @@ -170,8 +172,11 @@ void givenRoleCreateRequest_whenNameAlreadyExist_thenThrowAysRoleAlreadyExistsBy ); // Verify + Mockito.verify(identity, Mockito.times(1)) + .getInstitutionId(); + Mockito.verify(roleReadPort, Mockito.times(1)) - .findByName(Mockito.anyString()); + .findByNameAndInstitutionId(Mockito.anyString(), Mockito.anyString()); Mockito.verify(permissionReadPort, Mockito.never()) .findAllByIds(Mockito.anySet()); @@ -182,9 +187,6 @@ void givenRoleCreateRequest_whenNameAlreadyExist_thenThrowAysRoleAlreadyExistsBy Mockito.verify(identity, Mockito.never()) .getUserId(); - Mockito.verify(identity, Mockito.never()) - .getInstitutionId(); - Mockito.verify(roleSavePort, Mockito.never()) .save(Mockito.any(AysRole.class)); } @@ -197,7 +199,10 @@ void givenRoleCreateRequest_whenRequestHasSuperPermissionsAndUserIsNotSuperAdmin .build(); // When - Mockito.when(roleReadPort.findByName(Mockito.anyString())) + Mockito.when(identity.getInstitutionId()) + .thenReturn("0e1b24e2-bd74-4d3d-a419-a26a0e118d28"); + + Mockito.when(roleReadPort.findByNameAndInstitutionId(Mockito.anyString(), Mockito.anyString())) .thenReturn(Optional.empty()); List mockPermissions = new ArrayList<>(); @@ -216,7 +221,7 @@ void givenRoleCreateRequest_whenRequestHasSuperPermissionsAndUserIsNotSuperAdmin .thenReturn(false); Mockito.when(identity.getUserId()) - .thenReturn(AysRandomUtil.generateUUID()); + .thenReturn("e3c9bbc3-bd45-4f46-9717-a38a8c94d593"); // Then Assertions.assertThrows( @@ -225,8 +230,11 @@ void givenRoleCreateRequest_whenRequestHasSuperPermissionsAndUserIsNotSuperAdmin ); // Verify + Mockito.verify(identity, Mockito.times(1)) + .getInstitutionId(); + Mockito.verify(roleReadPort, Mockito.times(1)) - .findByName(Mockito.anyString()); + .findByNameAndInstitutionId(Mockito.anyString(), Mockito.anyString()); Mockito.verify(permissionReadPort, Mockito.times(1)) .findAllByIds(Mockito.anySet()); @@ -237,9 +245,6 @@ void givenRoleCreateRequest_whenRequestHasSuperPermissionsAndUserIsNotSuperAdmin Mockito.verify(identity, Mockito.times(1)) .getUserId(); - Mockito.verify(identity, Mockito.never()) - .getInstitutionId(); - Mockito.verify(roleSavePort, Mockito.never()) .save(Mockito.any(AysRole.class)); } @@ -253,7 +258,10 @@ void givenRoleCreateRequest_whenPermissionsNotExists_thenThrowAysPermissionNotEx .build(); // When - Mockito.when(roleReadPort.findByName(Mockito.anyString())) + Mockito.when(identity.getInstitutionId()) + .thenReturn("c38cc1dd-7474-463c-b93c-eeeae858fa35"); + + Mockito.when(roleReadPort.findByNameAndInstitutionId(Mockito.anyString(), Mockito.anyString())) .thenReturn(Optional.empty()); Mockito.when(permissionReadPort.findAllByIds(Mockito.anySet())) @@ -266,8 +274,11 @@ void givenRoleCreateRequest_whenPermissionsNotExists_thenThrowAysPermissionNotEx ); // Verify + Mockito.verify(identity, Mockito.times(1)) + .getInstitutionId(); + Mockito.verify(roleReadPort, Mockito.times(1)) - .findByName(Mockito.anyString()); + .findByNameAndInstitutionId(Mockito.anyString(), Mockito.anyString()); Mockito.verify(permissionReadPort, Mockito.times(1)) .findAllByIds(Mockito.anySet()); @@ -278,9 +289,6 @@ void givenRoleCreateRequest_whenPermissionsNotExists_thenThrowAysPermissionNotEx Mockito.verify(identity, Mockito.never()) .getUserId(); - Mockito.verify(identity, Mockito.never()) - .getInstitutionId(); - Mockito.verify(roleSavePort, Mockito.never()) .save(Mockito.any(AysRole.class)); } diff --git a/src/test/java/org/ays/auth/service/impl/AysRoleUpdateServiceImplTest.java b/src/test/java/org/ays/auth/service/impl/AysRoleUpdateServiceImplTest.java index 895aff3b7..85f1b98fe 100644 --- a/src/test/java/org/ays/auth/service/impl/AysRoleUpdateServiceImplTest.java +++ b/src/test/java/org/ays/auth/service/impl/AysRoleUpdateServiceImplTest.java @@ -20,7 +20,6 @@ import org.ays.auth.port.AysPermissionReadPort; import org.ays.auth.port.AysRoleReadPort; import org.ays.auth.port.AysRoleSavePort; -import org.ays.common.util.AysRandomUtil; import org.ays.institution.model.Institution; import org.ays.institution.model.InstitutionBuilder; import org.junit.jupiter.api.Assertions; @@ -57,23 +56,28 @@ class AysRoleUpdateServiceImplTest extends AysUnitTest { @Test void givenIdAndRoleUpdateRequest_whenValuesValid_thenUpdateRoleWithSuperPermissions() { // Given - String mockId = AysRandomUtil.generateUUID(); + String mockId = "1390ac31-53df-4ded-b2a5-e7322fb02c4b"; AysRoleUpdateRequest mockUpdateRequest = new AysRoleUpdateRequestBuilder() .withValidValues() .build(); // When + Institution mockInstitution = new InstitutionBuilder() + .withValidValues() + .withId("efaf3cfe-196e-4d45-846b-659a90f416e6") + .build(); + Mockito.when(identity.getInstitutionId()) + .thenReturn(mockInstitution.getId()); + AysRole mockRole = new AysRoleBuilder() .withValidValues() .withId(mockId) + .withInstitution(mockInstitution) .build(); Mockito.when(roleReadPort.findById(Mockito.anyString())) .thenReturn(Optional.of(mockRole)); - Mockito.when(identity.getInstitutionId()) - .thenReturn(mockRole.getInstitution().getId()); - - Mockito.when(roleReadPort.findByName(Mockito.anyString())) + Mockito.when(roleReadPort.findByNameAndInstitutionId(Mockito.anyString(), Mockito.anyString())) .thenReturn(Optional.empty()); List mockPermissions = new ArrayList<>(); @@ -98,14 +102,14 @@ void givenIdAndRoleUpdateRequest_whenValuesValid_thenUpdateRoleWithSuperPermissi roleUpdateService.update(mockId, mockUpdateRequest); // Verify - Mockito.verify(roleReadPort, Mockito.times(1)) - .findById(Mockito.anyString()); - Mockito.verify(identity, Mockito.times(1)) .getInstitutionId(); Mockito.verify(roleReadPort, Mockito.times(1)) - .findByName(Mockito.anyString()); + .findById(Mockito.anyString()); + + Mockito.verify(roleReadPort, Mockito.times(1)) + .findByNameAndInstitutionId(Mockito.anyString(), Mockito.anyString()); Mockito.verify(permissionReadPort, Mockito.times(1)) .findAllByIds(Mockito.anySet()); @@ -123,23 +127,28 @@ void givenIdAndRoleUpdateRequest_whenValuesValid_thenUpdateRoleWithSuperPermissi @Test void givenIdAndRoleUpdateRequest_whenValuesValid_thenUpdateRole() { // Given - String mockId = AysRandomUtil.generateUUID(); + String mockId = "7e85eaf9-f96b-46b6-bcf0-bb883a890010"; AysRoleUpdateRequest mockUpdateRequest = new AysRoleUpdateRequestBuilder() .withValidValues() .build(); // When + Institution mockInstitution = new InstitutionBuilder() + .withValidValues() + .withId("c3678b17-4d06-47f8-be75-663535f02c7b") + .build(); + Mockito.when(identity.getInstitutionId()) + .thenReturn(mockInstitution.getId()); + AysRole mockRole = new AysRoleBuilder() .withValidValues() .withId(mockId) + .withInstitution(mockInstitution) .build(); Mockito.when(roleReadPort.findById(Mockito.anyString())) .thenReturn(Optional.of(mockRole)); - Mockito.when(identity.getInstitutionId()) - .thenReturn(mockRole.getInstitution().getId()); - - Mockito.when(roleReadPort.findByName(Mockito.anyString())) + Mockito.when(roleReadPort.findByNameAndInstitutionId(Mockito.anyString(), Mockito.anyString())) .thenReturn(Optional.empty()); List mockPermissions = new ArrayList<>(); @@ -158,7 +167,7 @@ void givenIdAndRoleUpdateRequest_whenValuesValid_thenUpdateRole() { .thenReturn(false); Mockito.when(identity.getUserId()) - .thenReturn("mockUpdatedUser"); + .thenReturn("148b1d65-a0a6-458d-b98c-20fad8594487"); Mockito.when(roleSavePort.save(Mockito.any(AysRole.class))) .thenReturn(Mockito.mock(AysRole.class)); @@ -167,14 +176,14 @@ void givenIdAndRoleUpdateRequest_whenValuesValid_thenUpdateRole() { roleUpdateService.update(mockId, mockUpdateRequest); // Verify - Mockito.verify(roleReadPort, Mockito.times(1)) - .findById(Mockito.anyString()); - Mockito.verify(identity, Mockito.times(1)) .getInstitutionId(); Mockito.verify(roleReadPort, Mockito.times(1)) - .findByName(Mockito.anyString()); + .findById(Mockito.anyString()); + + Mockito.verify(roleReadPort, Mockito.times(1)) + .findByNameAndInstitutionId(Mockito.anyString(), Mockito.anyString()); Mockito.verify(permissionReadPort, Mockito.times(1)) .findAllByIds(Mockito.anySet()); @@ -192,51 +201,57 @@ void givenIdAndRoleUpdateRequest_whenValuesValid_thenUpdateRole() { @Test void givenIdAndRoleUpdateRequest_whenPermissionsUpdatedAndNameUnchanged_thenUpdateRole() { // Given - String mockId = AysRandomUtil.generateUUID(); + String mockId = "73854263-649b-47af-af56-43962ab77087"; AysRoleUpdateRequest mockUpdateRequest = new AysRoleUpdateRequestBuilder() .withName("ExistingName") .withPermissionIds(Set.of("b8d3ddce-45ca-4017-b52f-5826e330a1e6")) .build(); + // When + Institution mockInstitution = new InstitutionBuilder() + .withValidValues() + .withId("2d47c593-129f-4c32-a282-d9f132cebc55") + .build(); + Mockito.when(identity.getInstitutionId()) + .thenReturn(mockInstitution.getId()); + + List mockOldPermissions = List.of( + new AysPermissionBuilder() + .withValidValues() + .withName("institution:page") + .withCategory(AysPermissionCategory.PAGE) + .build() + ); AysRole mockRole = new AysRoleBuilder() - .withName("ExistingName") - .withPermissions(List.of( - new AysPermissionBuilder().withValidValues() - .withName("institution:page") - .withCategory(AysPermissionCategory.PAGE) - .build() - )) + .withValidValues() .withId(mockId) + .withName("ExistingName") + .withPermissions(mockOldPermissions) + .withInstitution(mockInstitution) .build(); - - // When Mockito.when(roleReadPort.findById(Mockito.anyString())) .thenReturn(Optional.of(mockRole)); - Mockito.when(identity.getInstitutionId()) - .thenReturn(mockRole.getInstitution().getId()); - - Mockito.when(roleReadPort.findByName(Mockito.anyString())). - thenReturn(Optional.of(mockRole)); - + Mockito.when(roleReadPort.findByNameAndInstitutionId(Mockito.anyString(), Mockito.anyString())) + .thenReturn(Optional.of(mockRole)); - List mockPermissions = new ArrayList<>(); + List mockNewPermissions = new ArrayList<>(); mockUpdateRequest.getPermissionIds().forEach(permissionId -> { AysPermission mockPermission = new AysPermissionBuilder() .withValidValues() .withId(permissionId) .withIsSuper(false) .build(); - mockPermissions.add(mockPermission); + mockNewPermissions.add(mockPermission); }); Mockito.when(permissionReadPort.findAllByIds(Mockito.anySet())) - .thenReturn(mockPermissions); + .thenReturn(mockNewPermissions); Mockito.when(identity.isSuperAdmin()) .thenReturn(false); Mockito.when(identity.getUserId()) - .thenReturn("mockUserId"); + .thenReturn("8a11623c-8ab4-4af9-a55c-5d3d338126d7"); Mockito.when(roleSavePort.save(Mockito.any(AysRole.class))) .thenReturn(Mockito.mock(AysRole.class)); @@ -245,15 +260,14 @@ void givenIdAndRoleUpdateRequest_whenPermissionsUpdatedAndNameUnchanged_thenUpda roleUpdateService.update(mockId, mockUpdateRequest); // Verify - Mockito.verify(roleReadPort, Mockito.times(1)) - .findById(Mockito.anyString()); - Mockito.verify(identity, Mockito.times(1)) .getInstitutionId(); - Mockito.verify(roleReadPort, Mockito.never()) - .findByName(Mockito.anyString()); + Mockito.verify(roleReadPort, Mockito.times(1)) + .findById(Mockito.anyString()); + Mockito.verify(roleReadPort, Mockito.never()) + .findByNameAndInstitutionId(Mockito.anyString(), Mockito.anyString()); Mockito.verify(permissionReadPort, Mockito.times(1)) .findAllByIds(Mockito.anySet()); @@ -261,7 +275,6 @@ void givenIdAndRoleUpdateRequest_whenPermissionsUpdatedAndNameUnchanged_thenUpda Mockito.verify(identity, Mockito.times(1)) .isSuperAdmin(); - Mockito.verify(identity, Mockito.times(1)) .getUserId(); @@ -270,14 +283,17 @@ void givenIdAndRoleUpdateRequest_whenPermissionsUpdatedAndNameUnchanged_thenUpda } @Test - void givenValidIdAndRoleUpdateRequest_whenRoleNotFound_thenThrowAysRoleNotExistByIdException() { + void givenValidIdAndRoleUpdateRequest_whenRoleNotFound_thenThrowRoleNotExistByIdException() { // Given - String mockId = AysRandomUtil.generateUUID(); + String mockId = "9b06ab7e-602b-48e6-95cb-fb20cb883f9e"; AysRoleUpdateRequest mockUpdateRequest = new AysRoleUpdateRequestBuilder() .withValidValues() .build(); // When + Mockito.when(identity.getInstitutionId()) + .thenReturn("39ad1713-5ee1-4fcd-b93e-bae1f77d03d1"); + Mockito.when(roleReadPort.findById(Mockito.anyString())) .thenReturn(Optional.empty()); @@ -288,14 +304,14 @@ void givenValidIdAndRoleUpdateRequest_whenRoleNotFound_thenThrowAysRoleNotExistB ); // Verify + Mockito.verify(identity, Mockito.times(1)) + .getInstitutionId(); + Mockito.verify(roleReadPort, Mockito.times(1)) .findById(Mockito.anyString()); - Mockito.verify(identity, Mockito.never()) - .getInstitutionId(); - Mockito.verify(roleReadPort, Mockito.never()) - .findByName(Mockito.anyString()); + .findByNameAndInstitutionId(Mockito.anyString(), Mockito.anyString()); Mockito.verify(permissionReadPort, Mockito.never()) .findAllByIds(Mockito.anySet()); @@ -311,24 +327,33 @@ void givenValidIdAndRoleUpdateRequest_whenRoleNotFound_thenThrowAysRoleNotExistB } @Test - void givenValidIdAndRoleUpdateRequest_whenRoleNotMatchedWithInstitution_thenThrowAysRoleNotExistByIdException() { + void givenValidIdAndRoleUpdateRequest_whenRoleNotMatchedWithInstitution_thenThrowRoleNotExistByIdException() { // Given - String mockId = AysRandomUtil.generateUUID(); + String mockId = "ddfbb4c9-d74a-4fcd-9312-4c4a336f7882"; AysRoleUpdateRequest mockUpdateRequest = new AysRoleUpdateRequestBuilder() .withValidValues() .build(); // When + Institution mockFirstInstitution = new InstitutionBuilder() + .withValidValues() + .withId("fe22a00a-3ba0-4c76-a6f9-a627e044a641") + .build(); + Mockito.when(identity.getInstitutionId()) + .thenReturn(mockFirstInstitution.getId()); + + Institution mockSecondInstitution = new InstitutionBuilder() + .withValidValues() + .withId("134742f1-2c60-41c0-9b89-eca72647e15a") + .build(); AysRole mockRole = new AysRoleBuilder() .withValidValues() .withId(mockId) + .withInstitution(mockSecondInstitution) .build(); Mockito.when(roleReadPort.findById(Mockito.anyString())) .thenReturn(Optional.of(mockRole)); - Mockito.when(identity.getInstitutionId()) - .thenReturn("becd3813-4d7a-4e40-a6d4-6dea4c037a7d"); - // Then Assertions.assertThrows( AysRoleNotExistByIdException.class, @@ -336,14 +361,14 @@ void givenValidIdAndRoleUpdateRequest_whenRoleNotMatchedWithInstitution_thenThro ); // Verify - Mockito.verify(roleReadPort, Mockito.times(1)) - .findById(Mockito.anyString()); - Mockito.verify(identity, Mockito.times(1)) .getInstitutionId(); + Mockito.verify(roleReadPort, Mockito.times(1)) + .findById(Mockito.anyString()); + Mockito.verify(roleReadPort, Mockito.never()) - .findByName(Mockito.anyString()); + .findByNameAndInstitutionId(Mockito.anyString(), Mockito.anyString()); Mockito.verify(permissionReadPort, Mockito.never()) .findAllByIds(Mockito.anySet()); @@ -359,25 +384,30 @@ void givenValidIdAndRoleUpdateRequest_whenRoleNotMatchedWithInstitution_thenThro } @Test - void givenValidIdAndRoleUpdateRequest_whenNameAlreadyExist_thenThrowAysRoleAlreadyExistsByNameException() { + void givenValidIdAndRoleUpdateRequest_whenNameAlreadyExist_thenThrowRoleAlreadyExistsByNameException() { // Given - String mockId = AysRandomUtil.generateUUID(); + String mockId = "dd750c12-00b3-46ef-9aa3-b6e312bbafdb"; AysRoleUpdateRequest mockUpdateRequest = new AysRoleUpdateRequestBuilder() .withValidValues() .build(); // When + Institution mockInstitution = new InstitutionBuilder() + .withValidValues() + .withId("95d6acfc-5ded-41e2-82f5-44c28325e62d") + .build(); + Mockito.when(identity.getInstitutionId()) + .thenReturn(mockInstitution.getId()); + AysRole mockRole = new AysRoleBuilder() .withValidValues() .withId(mockId) + .withInstitution(mockInstitution) .build(); Mockito.when(roleReadPort.findById(Mockito.anyString())) .thenReturn(Optional.of(mockRole)); - Mockito.when(identity.getInstitutionId()) - .thenReturn(mockRole.getInstitution().getId()); - - Mockito.when(roleReadPort.findByName(Mockito.anyString())) + Mockito.when(roleReadPort.findByNameAndInstitutionId(Mockito.anyString(), Mockito.anyString())) .thenReturn(Optional.of(Mockito.mock(AysRole.class))); // Then @@ -387,14 +417,14 @@ void givenValidIdAndRoleUpdateRequest_whenNameAlreadyExist_thenThrowAysRoleAlrea ); // Verify - Mockito.verify(roleReadPort, Mockito.times(1)) - .findById(Mockito.anyString()); - Mockito.verify(identity, Mockito.times(1)) .getInstitutionId(); Mockito.verify(roleReadPort, Mockito.times(1)) - .findByName(Mockito.anyString()); + .findById(Mockito.anyString()); + + Mockito.verify(roleReadPort, Mockito.times(1)) + .findByNameAndInstitutionId(Mockito.anyString(), Mockito.anyString()); Mockito.verify(permissionReadPort, Mockito.never()) .findAllByIds(Mockito.anySet()); @@ -410,25 +440,30 @@ void givenValidIdAndRoleUpdateRequest_whenNameAlreadyExist_thenThrowAysRoleAlrea } @Test - void givenValidIdAndRoleUpdateRequest_whenRequestHasSuperPermissionsAndUserIsNotSuperAdmin_thenThrowAysUserNotSuperAdminException() { + void givenValidIdAndRoleUpdateRequest_whenRequestHasSuperPermissionsAndUserIsNotSuperAdmin_thenThrowUserNotSuperAdminException() { // Given - String mockId = AysRandomUtil.generateUUID(); + String mockId = "9fc336e5-5ea7-4c6f-8e3e-7c74c7717a26"; AysRoleUpdateRequest mockUpdateRequest = new AysRoleUpdateRequestBuilder() .withValidValues() .build(); // When + Institution mockInstitution = new InstitutionBuilder() + .withValidValues() + .withId("7174a550-9bbb-413e-aba7-7c79cf51a553") + .build(); + Mockito.when(identity.getInstitutionId()) + .thenReturn(mockInstitution.getId()); + AysRole mockRole = new AysRoleBuilder() .withValidValues() .withId(mockId) + .withInstitution(mockInstitution) .build(); Mockito.when(roleReadPort.findById(Mockito.anyString())) .thenReturn(Optional.of(mockRole)); - Mockito.when(identity.getInstitutionId()) - .thenReturn(mockRole.getInstitution().getId()); - - Mockito.when(roleReadPort.findByName(Mockito.anyString())) + Mockito.when(roleReadPort.findByNameAndInstitutionId(Mockito.anyString(), Mockito.anyString())) .thenReturn(Optional.empty()); List mockPermissions = new ArrayList<>(); @@ -446,9 +481,6 @@ void givenValidIdAndRoleUpdateRequest_whenRequestHasSuperPermissionsAndUserIsNot Mockito.when(identity.isSuperAdmin()) .thenReturn(false); - Mockito.when(identity.getUserId()) - .thenReturn(AysRandomUtil.generateUUID()); - // Then Assertions.assertThrows( AysUserNotSuperAdminException.class, @@ -456,14 +488,14 @@ void givenValidIdAndRoleUpdateRequest_whenRequestHasSuperPermissionsAndUserIsNot ); // Verify - Mockito.verify(roleReadPort, Mockito.times(1)) - .findById(Mockito.anyString()); - Mockito.verify(identity, Mockito.times(1)) .getInstitutionId(); Mockito.verify(roleReadPort, Mockito.times(1)) - .findByName(Mockito.anyString()); + .findById(Mockito.anyString()); + + Mockito.verify(roleReadPort, Mockito.times(1)) + .findByNameAndInstitutionId(Mockito.anyString(), Mockito.anyString()); Mockito.verify(permissionReadPort, Mockito.times(1)) .findAllByIds(Mockito.anySet()); @@ -480,25 +512,30 @@ void givenValidIdAndRoleUpdateRequest_whenRequestHasSuperPermissionsAndUserIsNot @Test - void givenValidIdAndRoleUpdateRequest_whenPermissionsNotExists_thenThrowAysPermissionNotExistException() { + void givenValidIdAndRoleUpdateRequest_whenPermissionsNotExists_thenThrowPermissionNotExistException() { // Given - String mockId = AysRandomUtil.generateUUID(); + String mockId = "a2431a45-4632-4374-8c09-2a403ddbfd3a"; AysRoleUpdateRequest mockUpdateRequest = new AysRoleUpdateRequestBuilder() .withValidValues() .build(); // When + Institution mockInstitution = new InstitutionBuilder() + .withValidValues() + .withId("abe738b5-55e4-45e1-b487-cd0f20995623") + .build(); + Mockito.when(identity.getInstitutionId()) + .thenReturn(mockInstitution.getId()); + AysRole mockRole = new AysRoleBuilder() .withValidValues() .withId(mockId) + .withInstitution(mockInstitution) .build(); Mockito.when(roleReadPort.findById(Mockito.anyString())) .thenReturn(Optional.of(mockRole)); - Mockito.when(identity.getInstitutionId()) - .thenReturn(mockRole.getInstitution().getId()); - - Mockito.when(roleReadPort.findByName(Mockito.anyString())) + Mockito.when(roleReadPort.findByNameAndInstitutionId(Mockito.anyString(), Mockito.anyString())) .thenReturn(Optional.empty()); Mockito.when(permissionReadPort.findAllByIds(Mockito.anySet())) @@ -511,14 +548,14 @@ void givenValidIdAndRoleUpdateRequest_whenPermissionsNotExists_thenThrowAysPermi ); // Verify - Mockito.verify(roleReadPort, Mockito.times(1)) - .findById(Mockito.anyString()); - Mockito.verify(identity, Mockito.times(1)) .getInstitutionId(); Mockito.verify(roleReadPort, Mockito.times(1)) - .findByName(Mockito.anyString()); + .findById(Mockito.anyString()); + + Mockito.verify(roleReadPort, Mockito.times(1)) + .findByNameAndInstitutionId(Mockito.anyString(), Mockito.anyString()); Mockito.verify(permissionReadPort, Mockito.times(1)) .findAllByIds(Mockito.anySet()); @@ -580,7 +617,7 @@ void givenValidId_whenRoleIsPassive_thenActivateRole() { "ACTIVE", "DELETED" }) - void givenValidId_whenRoleIsNotPassive_thenThrowAysInvalidRoleStatusException(String roleStatus) { + void givenValidId_whenRoleIsNotPassive_thenThrowInvalidRoleStatusException(String roleStatus) { // Initialize AysRoleStatus status = AysRoleStatus.valueOf(roleStatus); @@ -619,11 +656,10 @@ void givenValidId_whenRoleIsNotPassive_thenThrowAysInvalidRoleStatusException(St Mockito.verify(roleSavePort, Mockito.never()) .save(Mockito.any(AysRole.class)); - } @Test - void givenValidId_whenRoleNotFoundForActivation_thenThrowAysRoleNotExistByIdException() { + void givenValidId_whenRoleNotFoundForActivation_thenThrowRoleNotExistByIdException() { // Given String mockId = "f6ecfa12-17e0-4294-a8fb-6598224fcd93"; @@ -696,7 +732,7 @@ void givenValidId_whenRoleIsActive_thenPassivateRole() { "PASSIVE", "DELETED" }) - void givenValidId_whenRoleIsNotActive_thenThrowAysInvalidRoleStatusException(String roleStatus) { + void givenValidId_whenRoleIsNotActive_thenThrowInvalidRoleStatusException(String roleStatus) { // Initialize AysRoleStatus status = AysRoleStatus.valueOf(roleStatus); @@ -740,7 +776,7 @@ void givenValidId_whenRoleIsNotActive_thenThrowAysInvalidRoleStatusException(Str } @Test - void givenValidId_whenRoleNotFoundForPassivation_thenThrowAysRoleNotExistByIdException() { + void givenValidId_whenRoleNotFoundForPassivation_thenThrowRoleNotExistByIdException() { // Given String mockId = "d0dc24fc-a2d2-4e31-b482-489f64b0cbf6"; @@ -767,7 +803,7 @@ void givenValidId_whenRoleNotFoundForPassivation_thenThrowAysRoleNotExistByIdExc } @Test - void givenValidId_whenInstitutionIdDoesNotMatch_thenThrowAysRoleNotExistByIdException() { + void givenValidId_whenInstitutionIdDoesNotMatch_thenThrowRoleNotExistByIdException() { // Given String mockId = "666e4d1b-58ac-486e-b373-189b4f354e36"; @@ -890,7 +926,7 @@ void givenValidId_whenRoleFound_thenDeleteRole() { } @Test - void givenValidId_whenRoleAlreadyDeleted_thenThrowAysRoleAlreadyDeletedException() { + void givenValidId_whenRoleAlreadyDeleted_thenThrowRoleAlreadyDeletedException() { // Given String mockId = "15c417ce-37cf-4136-b3fb-d9b71c3ce06a"; @@ -926,7 +962,7 @@ void givenValidId_whenRoleAlreadyDeleted_thenThrowAysRoleAlreadyDeletedException } @Test - void givenValidId_whenRoleDoesNotFound_thenThrowAysRoleNotExistByIdException() { + void givenValidId_whenRoleDoesNotFound_thenThrowRoleNotExistByIdException() { // Given String mockId = "c4dd8650-e616-4aa0-8127-b2944689817d"; @@ -950,7 +986,7 @@ void givenValidId_whenRoleDoesNotFound_thenThrowAysRoleNotExistByIdException() { } @Test - void givenValidId_whenRoleUsing_thenThrowAysRoleAssignedToUserException() { + void givenValidId_whenRoleUsing_thenThrowRoleAssignedToUserException() { // Given String mockId = "ac046642-5e33-49b2-b198-9607625a6ec5"; @@ -991,7 +1027,7 @@ void givenValidId_whenRoleUsing_thenThrowAysRoleAssignedToUserException() { } @Test - void givenValidId_whenRoleNotMatchedWithInstitution_thenThrowAysRoleNotExistByIdException() { + void givenValidId_whenRoleNotMatchedWithInstitution_thenThrowRoleNotExistByIdException() { // Given String mockId = "32657ecb-5172-401d-8b29-a8e4454e8243"; diff --git a/src/test/java/org/ays/institution/model/InstitutionBuilder.java b/src/test/java/org/ays/institution/model/InstitutionBuilder.java index 393e2b879..0a1c36408 100644 --- a/src/test/java/org/ays/institution/model/InstitutionBuilder.java +++ b/src/test/java/org/ays/institution/model/InstitutionBuilder.java @@ -13,6 +13,7 @@ public InstitutionBuilder() { public InstitutionBuilder withValidValues() { return this .withId(AysRandomUtil.generateUUID()) + .withName(AysRandomUtil.generateText(20)) .withStatus(InstitutionStatus.ACTIVE); } @@ -26,6 +27,11 @@ public InstitutionBuilder withoutId() { return this; } + public InstitutionBuilder withName(String name) { + data.setName(name); + return this; + } + public InstitutionBuilder withStatus(InstitutionStatus status) { data.setStatus(status); return this;