Skip to content

Commit

Permalink
PUB-2681 - Add unit and integration tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ChrisS1512 committed Dec 4, 2024
1 parent 6bbed03 commit aecbd63
Show file tree
Hide file tree
Showing 5 changed files with 115 additions and 61 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ class SystemAdminB2CAccountTest {

private static final String ISSUER_ID = "1234-1234-1234-1234";
private static final String SYSTEM_ADMIN_ISSUER_ID = "87f907d2-eb28-42cc-b6e1-ae2b03f7bba2";
private static final String SUPER_ADMIN_ISSUER_ID = "87f907d2-eb28-42cc-b6e1-ae2b03f7bba3";
private static final String ISSUER_HEADER = "x-issuer-id";
private static final String GIVEN_NAME = "Given Name";
private static final String ID = "1234";
Expand Down Expand Up @@ -232,4 +233,26 @@ void testUnauthorizedCreateSystemAdminAccount() throws Exception {
FORBIDDEN_STATUS_CODE
);
}

@Test
void testCreateSystemAdminUserWhenNotSystemAdmin() throws Exception {
SystemAdminAccount systemAdmin = new SystemAdminAccount();
systemAdmin.setFirstName(TEST_SYS_ADMIN_FIRSTNAME);
systemAdmin.setSurname(TEST_SYS_ADMIN_SURNAME);
systemAdmin.setEmail(TEST_SYS_ADMIN_EMAIL);

MockHttpServletRequestBuilder createRequest =
MockMvcRequestBuilders
.post(CREATE_SYSTEM_ADMIN_URL)
.content(OBJECT_MAPPER.writeValueAsString(systemAdmin))
.header(ISSUER_HEADER, SUPER_ADMIN_ISSUER_ID)
.contentType(MediaType.APPLICATION_JSON);

MvcResult responseCreateSystemAdminUser = mockMvc.perform(createRequest)
.andExpect(status().isForbidden()).andReturn();

assertEquals(FORBIDDEN.value(), responseCreateSystemAdminUser.getResponse().getStatus(),
FORBIDDEN_STATUS_CODE
);
}
}
3 changes: 1 addition & 2 deletions src/integrationTest/resources/add-admin-users.sql
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
INSERT INTO pi_user (user_id, email, provenance_user_id,user_provenance,roles,forenames,surname) VALUES
('87f907d2-eb28-42cc-b6e1-ae2b03f7bba2', 'SyestemAdmin@justice.gov.uk', 'e5f1cc77-6e9a-40ab-8da0-a9666b328464','PI_AAD','SYSTEM_ADMIN','System','Admin'),
('87f907d2-eb28-42cc-b6e1-ae2b03f7bba2', 'SystemAdmin@justice.gov.uk', 'e5f1cc77-6e9a-40ab-8da0-a9666b328464','PI_AAD','SYSTEM_ADMIN','System','Admin'),
('87f907d2-eb28-42cc-b6e1-ae2b03f7bba3', 'SuperAdminCtsc@justice.gov.uk', 'e5f1cc77-6e9a-40ab-8da0-a9666b328465','PI_AAD','INTERNAL_SUPER_ADMIN_CTSC','Super','Admin'),
('87f907d2-eb28-42cc-b6e1-ae2b03f7bba4', 'SyestemAdminSso@justice.gov.uk', 'e5f1cc77-6e9a-40ab-8da0-a9666b328466','SSO','SYSTEM_ADMIN','System','Admin');

Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import uk.gov.hmcts.reform.pip.model.system.admin.CreateSystemAdminAction;

import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import java.util.Optional;
import java.util.UUID;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.verifyNoInteractions;
Expand Down Expand Up @@ -667,4 +668,45 @@ void testExceptionThrowIfAdminUserNotFound() {
.isInstanceOf(NotFoundException.class)
.hasMessage(String.format("User with supplied user id: %s could not be found", ADMIN_USER_ID));
}

@Test
void testUserCanCreateSystemAdmin() {
UUID userId = UUID.randomUUID();
PiUser user = new PiUser();
user.setRoles(Roles.SYSTEM_ADMIN);

when(userRepository.findByUserId(userId)).thenReturn(Optional.of(user));

assertThat(authorisationService.userCanCreateSystemAdmin(userId)).isTrue();
}

@Test
void testUserCannotCreateSystemAdminIfAccountNotFound() {
UUID userId = UUID.randomUUID();

when(userRepository.findByUserId(userId)).thenReturn(Optional.empty());

try (LogCaptor logCaptor = LogCaptor.forClass(AuthorisationService.class)) {
assertThat(authorisationService.userCanCreateSystemAdmin(userId)).isFalse();

assertThat(logCaptor.getErrorLogs().get(0)).contains(
String.format("User with ID %s is forbidden to create a B2C system admin", userId));
}
}

@Test
void testUserCannotCreateSystemAdminIfUserIsNotSystemAdmin() {
UUID userId = UUID.randomUUID();
PiUser user = new PiUser();
user.setRoles(Roles.INTERNAL_ADMIN_LOCAL);

when(userRepository.findByUserId(userId)).thenReturn(Optional.of(user));

try (LogCaptor logCaptor = LogCaptor.forClass(AuthorisationService.class)) {
assertThat(authorisationService.userCanCreateSystemAdmin(userId)).isFalse();

assertThat(logCaptor.getErrorLogs().get(0)).contains(
String.format("User with ID %s is forbidden to create a B2C system admin", userId));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ class SystemAdminB2CAccountServiceTest {
private PublicationService publicationService;

@Mock
private AzureAccountService azureAccountService;
private AccountService accountService;

@Mock
private UserRepository userRepository;
Expand All @@ -62,7 +62,7 @@ class SystemAdminB2CAccountServiceTest {

private SystemAdminB2CAccountService systemAdminAccountService;

private static final String ID = UUID.randomUUID().toString();
private static final UUID ID = UUID.randomUUID();
private static final String EMAIL = "test@email.com";
private static final String FORENAME = "Test";
private static final String SURNAME = "Surname";
Expand All @@ -74,16 +74,17 @@ class SystemAdminB2CAccountServiceTest {
private final User expectedUser = new User();
private final PiUser expectedPiUser = new PiUser();
private final PiUser ssoUser = new PiUser();
private final PiUser systemAdminUser = new PiUser();

@BeforeEach
void setup() {
expectedUser.setGivenName(FORENAME);
expectedUser.setId(ID);
expectedUser.setId(ID.toString());
expectedUser.setSurname(SURNAME);

expectedPiUser.setUserId(UUID.randomUUID());
expectedPiUser.setEmail(EMAIL);
expectedPiUser.setProvenanceUserId(ID);
expectedPiUser.setProvenanceUserId(ID.toString());
expectedPiUser.setRoles(Roles.SYSTEM_ADMIN);
expectedPiUser.setUserProvenance(UserProvenances.PI_AAD);

Expand All @@ -93,9 +94,13 @@ void setup() {
ssoUser.setRoles(Roles.SYSTEM_ADMIN);
ssoUser.setUserProvenance(UserProvenances.SSO);

systemAdminUser.setRoles(Roles.SYSTEM_ADMIN);
systemAdminUser.setUserId(ID);
systemAdminUser.setEmail(EMAIL);

systemAdminAccountService = new SystemAdminB2CAccountService(validator, azureUserService, userRepository,
publicationService, 4,
azureAccountService);
accountService);

}

Expand All @@ -107,14 +112,16 @@ void testAddSystemAdminAccount() throws AzureCustomException {
when(azureUserService.createUser(argThat(user -> EMAIL.equals(user.getEmail())), anyBoolean()))
.thenReturn(expectedUser);
when(userRepository.save(any())).thenReturn(expectedPiUser);
when(azureAccountService.retrieveAzureAccount(any()))
.thenReturn(azUser);
when(publicationService.sendNotificationEmail(EMAIL, FORENAME, SURNAME)).thenReturn(Boolean.TRUE);
when(userRepository.findByUserId(any())).thenReturn(Optional.ofNullable(expectedPiUser));

doNothing().when(publicationService)
.sendSystemAdminAccountAction(argThat(arg -> EMAIL.equals(arg.getRequesterEmail())));

when(accountService.getUserById(ID)).thenReturn(systemAdminUser);
when(validator.validate(SYSTEM_ADMIN_ACCOUNT)).thenReturn(Set.of());
when(userRepository.findByRoles(Roles.SYSTEM_ADMIN)).thenReturn(List.of(expectedPiUser));

PiUser returnedUser = systemAdminAccountService.addSystemAdminAccount(SYSTEM_ADMIN_ACCOUNT, ID);
PiUser returnedUser = systemAdminAccountService.addSystemAdminAccount(SYSTEM_ADMIN_ACCOUNT, ID.toString());

assertEquals(expectedPiUser, returnedUser, USER_MESSAGE);
}
Expand All @@ -124,16 +131,13 @@ void testAddSystemAdminAccountThrowsException() throws AzureCustomException {
AzureAccount azUser = new AzureAccount();
azUser.setDisplayName(FORENAME);

when(userRepository.findByUserId(any()))
.thenReturn(Optional.ofNullable(expectedPiUser));
when(azureAccountService.retrieveAzureAccount(any()))
.thenReturn(azUser);
when(accountService.getUserById(ID)).thenReturn(systemAdminUser);
when(azureUserService.createUser(argThat(user -> EMAIL.equals(user.getEmail())), anyBoolean()))
.thenThrow(new AzureCustomException("Test error"));

SystemAdminAccountException systemAdminAccountException =
assertThrows(SystemAdminAccountException.class, () ->
systemAdminAccountService.addSystemAdminAccount(SYSTEM_ADMIN_ACCOUNT, ID));
systemAdminAccountService.addSystemAdminAccount(SYSTEM_ADMIN_ACCOUNT, ID.toString()));


assertEquals("Test error",
Expand All @@ -146,41 +150,22 @@ void testConstraintViolationException() {
AzureAccount azUser = new AzureAccount();
azUser.setDisplayName(FORENAME);

when(userRepository.findByUserId(any()))
.thenReturn(Optional.ofNullable(expectedPiUser));
when(azureAccountService.retrieveAzureAccount(any()))
.thenReturn(azUser);
when(accountService.getUserById(ID)).thenReturn(systemAdminUser);
when(validator.validate(any())).thenReturn(Set.of(constraintViolation));
when(constraintViolation.getMessage()).thenReturn("This is a message");
when(constraintViolation.getPropertyPath()).thenReturn(path);

doNothing().when(publicationService)
.sendSystemAdminAccountAction(argThat(arg -> EMAIL.equals(arg.getRequesterEmail())));

SystemAdminAccountException systemAdminAccountException =
assertThrows(SystemAdminAccountException.class, () ->
systemAdminAccountService.addSystemAdminAccount(ERRORED_SYSTEM_ADMIN_ACCOUNT, ID));
systemAdminAccountService.addSystemAdminAccount(ERRORED_SYSTEM_ADMIN_ACCOUNT, ID.toString()));

assertNotEquals(0, systemAdminAccountException.getErroredSystemAdminAccount().getErrorMessages().size(),
"Constraint violation error messages not displayed");
}

@Test
void testAddSystemAdminAccountNotVerified() throws AzureCustomException {
AzureAccount azUser = new AzureAccount();
azUser.setDisplayName(FORENAME);

expectedPiUser.setRoles(Roles.VERIFIED);
when(azureUserService.createUser(argThat(user -> EMAIL.equals(user.getEmail())), anyBoolean()))
.thenReturn(expectedUser);
when(userRepository.save(any())).thenReturn(expectedPiUser);
when(publicationService.sendNotificationEmail(EMAIL, FORENAME, SURNAME)).thenReturn(Boolean.FALSE);
when(userRepository.findByUserId(any())).thenReturn(Optional.ofNullable(expectedPiUser));
when(validator.validate(SYSTEM_ADMIN_ACCOUNT)).thenReturn(Set.of());
when(userRepository.findByRoles(Roles.SYSTEM_ADMIN)).thenReturn(List.of(expectedPiUser));

PiUser returnedUser = systemAdminAccountService.addSystemAdminAccount(SYSTEM_ADMIN_ACCOUNT, ID);

assertEquals(expectedPiUser, returnedUser, USER_MESSAGE);
}

@Test
void testAddSystemAdminAccountNotExists() throws AzureCustomException {
AzureAccount azUser = new AzureAccount();
Expand All @@ -191,11 +176,13 @@ void testAddSystemAdminAccountNotExists() throws AzureCustomException {
.thenReturn(expectedUser);
when(userRepository.save(any())).thenReturn(expectedPiUser);
when(publicationService.sendNotificationEmail(EMAIL, FORENAME, SURNAME)).thenReturn(Boolean.FALSE);
when(userRepository.findByUserId(any())).thenReturn(Optional.empty());
when(accountService.getUserById(ID)).thenReturn(new PiUser());
when(validator.validate(SYSTEM_ADMIN_ACCOUNT)).thenReturn(Set.of());
when(userRepository.findByRoles(Roles.SYSTEM_ADMIN)).thenReturn(List.of(expectedPiUser));
doNothing().when(publicationService)
.sendSystemAdminAccountAction(argThat(arg -> arg.getRequesterEmail() == null));

PiUser returnedUser = systemAdminAccountService.addSystemAdminAccount(SYSTEM_ADMIN_ACCOUNT, ID);
PiUser returnedUser = systemAdminAccountService.addSystemAdminAccount(SYSTEM_ADMIN_ACCOUNT, ID.toString());

assertEquals(expectedPiUser, returnedUser, USER_MESSAGE);
}
Expand All @@ -206,14 +193,14 @@ void testUserAlreadyExists() {
azUser.setDisplayName(FORENAME);
when(userRepository.findByEmailAndUserProvenance(EMAIL, UserProvenances.PI_AAD))
.thenReturn(Optional.of(expectedPiUser));
when(userRepository.findByUserId(any()))
.thenReturn(Optional.ofNullable(expectedPiUser));
when(azureAccountService.retrieveAzureAccount(any()))
.thenReturn(azUser);
doNothing().when(publicationService)
.sendSystemAdminAccountAction(argThat(arg -> EMAIL.equals(arg.getRequesterEmail())));
when(accountService.getUserById(ID))
.thenReturn(systemAdminUser);

SystemAdminAccountException systemAdminAccountException =
assertThrows(SystemAdminAccountException.class, () ->
systemAdminAccountService.addSystemAdminAccount(SYSTEM_ADMIN_ACCOUNT, ID));
systemAdminAccountService.addSystemAdminAccount(SYSTEM_ADMIN_ACCOUNT, ID.toString()));

assertTrue(systemAdminAccountException.getErroredSystemAdminAccount().isDuplicate(), "Duplicate account flag "
+ "not set");
Expand All @@ -225,16 +212,17 @@ void testAboveMaxAllowsUsersWithAllAadUsers() {
azUser.setDisplayName(FORENAME);
when(userRepository.findByEmailAndUserProvenance(EMAIL, UserProvenances.PI_AAD))
.thenReturn(Optional.empty());
when(userRepository.findByUserId(any()))
.thenReturn(Optional.ofNullable(expectedPiUser));
when(azureAccountService.retrieveAzureAccount(any()))
.thenReturn(azUser);
when(accountService.getUserById(ID))
.thenReturn(systemAdminUser);
when(userRepository.findByRoles(Roles.SYSTEM_ADMIN)).thenReturn(List.of(expectedPiUser, expectedPiUser,
expectedPiUser, expectedPiUser));

doNothing().when(publicationService)
.sendSystemAdminAccountAction(argThat(arg -> EMAIL.equals(arg.getRequesterEmail())));

SystemAdminAccountException systemAdminAccountException =
assertThrows(SystemAdminAccountException.class, () ->
systemAdminAccountService.addSystemAdminAccount(SYSTEM_ADMIN_ACCOUNT, ID));
systemAdminAccountService.addSystemAdminAccount(SYSTEM_ADMIN_ACCOUNT, ID.toString()));

assertTrue(systemAdminAccountException.getErroredSystemAdminAccount().isAboveMaxSystemAdmin(), "Max system "
+ "admin flag not set");
Expand All @@ -246,17 +234,18 @@ void testAboveMaxAllowsUsersNotIncludingSsoUser() throws AzureCustomException {
azUser.setDisplayName(FORENAME);
when(userRepository.findByEmailAndUserProvenance(EMAIL, UserProvenances.PI_AAD))
.thenReturn(Optional.empty());
when(userRepository.findByUserId(any()))
.thenReturn(Optional.ofNullable(expectedPiUser));
when(azureAccountService.retrieveAzureAccount(any()))
.thenReturn(azUser);
when(accountService.getUserById(ID))
.thenReturn(systemAdminUser);
when(userRepository.findByRoles(Roles.SYSTEM_ADMIN)).thenReturn(List.of(expectedPiUser, expectedPiUser,
expectedPiUser, ssoUser));
doNothing().when(publicationService)
.sendSystemAdminAccountAction(argThat(arg -> EMAIL.equals(arg.getRequesterEmail())));

when(azureUserService.createUser(argThat(user -> EMAIL.equals(user.getEmail())), anyBoolean()))
.thenReturn(expectedUser);
when(userRepository.save(any())).thenReturn(expectedPiUser);

PiUser returnedUser = systemAdminAccountService.addSystemAdminAccount(SYSTEM_ADMIN_ACCOUNT, ID);
PiUser returnedUser = systemAdminAccountService.addSystemAdminAccount(SYSTEM_ADMIN_ACCOUNT, ID.toString());

assertEquals(expectedPiUser, returnedUser, USER_MESSAGE);
}
Expand All @@ -270,13 +259,15 @@ void testHandleNewSystemAdminAccountAction() {

doNothing().when(publicationService).sendSystemAdminAccountAction(systemAdminAccountArgumentCaptor.capture());

systemAdminAccountService.handleNewSystemAdminAccountAction(SYSTEM_ADMIN_ACCOUNT, ID, ActionResult.ATTEMPTED,
FORENAME);
systemAdminAccountService.handleNewSystemAdminAccountAction(SYSTEM_ADMIN_ACCOUNT,
ID.toString(),
ActionResult.ATTEMPTED,
EMAIL);

CreateSystemAdminAction createSystemAdminAction = systemAdminAccountArgumentCaptor.getValue();

assertEquals(EMAIL, createSystemAdminAction.getAccountEmail(), "Unknown email retrieved");
assertEquals(FORENAME, createSystemAdminAction.getRequesterName(), "Unknown requester name retrieved");
assertEquals(EMAIL, createSystemAdminAction.getRequesterEmail(), "Unknown requester name retrieved");
assertEquals(List.of(EMAIL, EMAIL), createSystemAdminAction.getEmailList(), "Unknown email list retrieved");
assertEquals(ActionResult.ATTEMPTED, createSystemAdminAction.getActionResult(),
"Action result not as expected");
Expand Down

0 comments on commit aecbd63

Please sign in to comment.