feat(server-impl): refactoring resources JAX-RS, corrections AuditService/SyncService/UserService, ajout entites Sync et scripts Docker
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -1,37 +1,35 @@
|
||||
package dev.lions.user.manager.client;
|
||||
|
||||
import jakarta.ws.rs.client.Client;
|
||||
import jakarta.ws.rs.client.ClientBuilder;
|
||||
import jakarta.ws.rs.client.Invocation;
|
||||
import jakarta.ws.rs.client.WebTarget;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.keycloak.admin.client.Keycloak;
|
||||
import org.keycloak.admin.client.resource.RealmResource;
|
||||
import org.keycloak.admin.client.resource.RolesResource;
|
||||
import org.keycloak.admin.client.resource.UsersResource;
|
||||
import org.keycloak.admin.client.token.TokenManager;
|
||||
import org.keycloak.representations.info.ServerInfoRepresentation;
|
||||
import org.keycloak.admin.client.resource.ServerInfoResource;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import jakarta.ws.rs.NotFoundException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* Tests complets pour KeycloakAdminClientImpl pour atteindre 100% de couverture
|
||||
* Couvre init(), getAllRealms(), reconnect(), et tous les cas limites
|
||||
* Tests complets pour KeycloakAdminClientImpl
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class KeycloakAdminClientImplCompleteTest {
|
||||
|
||||
@Mock
|
||||
Keycloak mockKeycloak;
|
||||
|
||||
@InjectMocks
|
||||
KeycloakAdminClientImpl client;
|
||||
|
||||
@@ -43,315 +41,123 @@ class KeycloakAdminClientImplCompleteTest {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
// Set all config fields to null/empty for testing
|
||||
setField("serverUrl", "");
|
||||
setField("serverUrl", "http://localhost:8180");
|
||||
setField("adminRealm", "master");
|
||||
setField("adminClientId", "admin-cli");
|
||||
setField("adminUsername", "admin");
|
||||
setField("adminPassword", "");
|
||||
setField("connectionPoolSize", 10);
|
||||
setField("timeoutSeconds", 30);
|
||||
setField("keycloak", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testInit_WithServerUrl() throws Exception {
|
||||
setField("serverUrl", "http://localhost:8080");
|
||||
setField("adminRealm", "master");
|
||||
setField("adminClientId", "admin-cli");
|
||||
setField("adminUsername", "admin");
|
||||
setField("adminPassword", "password");
|
||||
|
||||
// Mock KeycloakBuilder to avoid actual connection
|
||||
// This will likely throw an exception, but that's ok - we test the exception path
|
||||
try {
|
||||
java.lang.reflect.Method initMethod = KeycloakAdminClientImpl.class.getDeclaredMethod("init");
|
||||
initMethod.setAccessible(true);
|
||||
initMethod.invoke(client);
|
||||
} catch (Exception e) {
|
||||
// Expected - KeycloakBuilder will fail without actual Keycloak server
|
||||
}
|
||||
|
||||
// The init method will set keycloak to null on exception
|
||||
Field keycloakField = KeycloakAdminClientImpl.class.getDeclaredField("keycloak");
|
||||
keycloakField.setAccessible(true);
|
||||
Keycloak result = (Keycloak) keycloakField.get(client);
|
||||
// Result will be null due to exception, which is the expected behavior
|
||||
// This test covers the exception path in init()
|
||||
void testGetInstance() {
|
||||
Keycloak result = client.getInstance();
|
||||
assertSame(mockKeycloak, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testInit_WithException() throws Exception {
|
||||
setField("serverUrl", "http://localhost:8080");
|
||||
setField("adminRealm", "master");
|
||||
setField("adminClientId", "admin-cli");
|
||||
setField("adminUsername", "admin");
|
||||
setField("adminPassword", "password");
|
||||
void testGetRealm_Success() {
|
||||
RealmResource mockRealmResource = mock(RealmResource.class);
|
||||
when(mockKeycloak.realm("test-realm")).thenReturn(mockRealmResource);
|
||||
|
||||
// Call init via reflection - will throw exception without actual Keycloak
|
||||
// This test covers the exception handling path in init()
|
||||
try {
|
||||
java.lang.reflect.Method initMethod = KeycloakAdminClientImpl.class.getDeclaredMethod("init");
|
||||
initMethod.setAccessible(true);
|
||||
initMethod.invoke(client);
|
||||
} catch (Exception e) {
|
||||
// Expected - KeycloakBuilder may fail
|
||||
}
|
||||
|
||||
// Verify keycloak is null after exception
|
||||
Field keycloakField = KeycloakAdminClientImpl.class.getDeclaredField("keycloak");
|
||||
keycloakField.setAccessible(true);
|
||||
Keycloak result = (Keycloak) keycloakField.get(client);
|
||||
// Result may be null due to exception, which is the expected behavior
|
||||
// This test covers the exception handling path in init()
|
||||
RealmResource result = client.getRealm("test-realm");
|
||||
assertSame(mockRealmResource, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testInit_WithNullServerUrl() throws Exception {
|
||||
setField("serverUrl", null);
|
||||
void testGetRealm_Exception() {
|
||||
when(mockKeycloak.realm("bad-realm")).thenThrow(new RuntimeException("Connection error"));
|
||||
|
||||
// Call init via reflection
|
||||
java.lang.reflect.Method initMethod = KeycloakAdminClientImpl.class.getDeclaredMethod("init");
|
||||
initMethod.setAccessible(true);
|
||||
initMethod.invoke(client);
|
||||
|
||||
// Verify keycloak is null
|
||||
Field keycloakField = KeycloakAdminClientImpl.class.getDeclaredField("keycloak");
|
||||
keycloakField.setAccessible(true);
|
||||
Keycloak result = (Keycloak) keycloakField.get(client);
|
||||
assertNull(result);
|
||||
assertThrows(RuntimeException.class, () -> client.getRealm("bad-realm"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testInit_WithEmptyServerUrl() throws Exception {
|
||||
setField("serverUrl", "");
|
||||
void testGetUsers() {
|
||||
RealmResource mockRealmResource = mock(RealmResource.class);
|
||||
UsersResource mockUsersResource = mock(UsersResource.class);
|
||||
when(mockKeycloak.realm("test-realm")).thenReturn(mockRealmResource);
|
||||
when(mockRealmResource.users()).thenReturn(mockUsersResource);
|
||||
|
||||
// Call init via reflection
|
||||
java.lang.reflect.Method initMethod = KeycloakAdminClientImpl.class.getDeclaredMethod("init");
|
||||
initMethod.setAccessible(true);
|
||||
initMethod.invoke(client);
|
||||
|
||||
// Verify keycloak is null
|
||||
Field keycloakField = KeycloakAdminClientImpl.class.getDeclaredField("keycloak");
|
||||
keycloakField.setAccessible(true);
|
||||
Keycloak result = (Keycloak) keycloakField.get(client);
|
||||
assertNull(result);
|
||||
UsersResource result = client.getUsers("test-realm");
|
||||
assertSame(mockUsersResource, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testReconnect() throws Exception {
|
||||
Keycloak mockKeycloak = mock(Keycloak.class);
|
||||
setField("keycloak", mockKeycloak);
|
||||
setField("serverUrl", "");
|
||||
void testGetRoles() {
|
||||
RealmResource mockRealmResource = mock(RealmResource.class);
|
||||
RolesResource mockRolesResource = mock(RolesResource.class);
|
||||
when(mockKeycloak.realm("test-realm")).thenReturn(mockRealmResource);
|
||||
when(mockRealmResource.roles()).thenReturn(mockRolesResource);
|
||||
|
||||
// reconnect calls close() then init()
|
||||
client.reconnect();
|
||||
|
||||
// Verify close was called
|
||||
verify(mockKeycloak).close();
|
||||
|
||||
// Verify keycloak is null after close
|
||||
Field keycloakField = KeycloakAdminClientImpl.class.getDeclaredField("keycloak");
|
||||
keycloakField.setAccessible(true);
|
||||
Keycloak result = (Keycloak) keycloakField.get(client);
|
||||
assertNull(result);
|
||||
RolesResource result = client.getRoles("test-realm");
|
||||
assertSame(mockRolesResource, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_Success() throws Exception {
|
||||
Keycloak mockKeycloak = mock(Keycloak.class);
|
||||
TokenManager mockTokenManager = mock(TokenManager.class);
|
||||
setField("keycloak", mockKeycloak);
|
||||
setField("serverUrl", "http://localhost:8080");
|
||||
void testIsConnected_True() {
|
||||
ServerInfoResource mockServerInfoResource = mock(ServerInfoResource.class);
|
||||
when(mockKeycloak.serverInfo()).thenReturn(mockServerInfoResource);
|
||||
when(mockServerInfoResource.getInfo()).thenReturn(mock(ServerInfoRepresentation.class));
|
||||
|
||||
when(mockKeycloak.tokenManager()).thenReturn(mockTokenManager);
|
||||
when(mockTokenManager.getAccessTokenString()).thenReturn("test-token");
|
||||
|
||||
// Mock ClientBuilder
|
||||
try (MockedStatic<ClientBuilder> mockedClientBuilder = mockStatic(ClientBuilder.class)) {
|
||||
Client mockClient = mock(Client.class);
|
||||
WebTarget mockWebTarget = mock(WebTarget.class);
|
||||
Invocation.Builder mockBuilder = mock(Invocation.Builder.class);
|
||||
Response mockResponse = mock(Response.class);
|
||||
|
||||
mockedClientBuilder.when(ClientBuilder::newClient).thenReturn(mockClient);
|
||||
when(mockClient.target("http://localhost:8080/admin/realms")).thenReturn(mockWebTarget);
|
||||
when(mockWebTarget.request(jakarta.ws.rs.core.MediaType.APPLICATION_JSON)).thenReturn(mockBuilder);
|
||||
when(mockBuilder.header(anyString(), anyString())).thenReturn(mockBuilder);
|
||||
|
||||
// Mock response with realm data
|
||||
Map<String, Object> realm1 = new HashMap<>();
|
||||
realm1.put("realm", "realm1");
|
||||
Map<String, Object> realm2 = new HashMap<>();
|
||||
realm2.put("realm", "realm2");
|
||||
List<Map<String, Object>> realmsJson = new ArrayList<>();
|
||||
realmsJson.add(realm1);
|
||||
realmsJson.add(realm2);
|
||||
|
||||
when(mockBuilder.get(List.class)).thenReturn(realmsJson);
|
||||
|
||||
List<String> result = client.getAllRealms();
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(2, result.size());
|
||||
assertTrue(result.contains("realm1"));
|
||||
assertTrue(result.contains("realm2"));
|
||||
verify(mockClient).close();
|
||||
}
|
||||
assertTrue(client.isConnected());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_WithNullRealmsJson() throws Exception {
|
||||
Keycloak mockKeycloak = mock(Keycloak.class);
|
||||
TokenManager mockTokenManager = mock(TokenManager.class);
|
||||
setField("keycloak", mockKeycloak);
|
||||
setField("serverUrl", "http://localhost:8080");
|
||||
void testIsConnected_False() {
|
||||
when(mockKeycloak.serverInfo()).thenThrow(new RuntimeException("Connection refused"));
|
||||
|
||||
when(mockKeycloak.tokenManager()).thenReturn(mockTokenManager);
|
||||
when(mockTokenManager.getAccessTokenString()).thenReturn("test-token");
|
||||
|
||||
try (MockedStatic<ClientBuilder> mockedClientBuilder = mockStatic(ClientBuilder.class)) {
|
||||
Client mockClient = mock(Client.class);
|
||||
WebTarget mockWebTarget = mock(WebTarget.class);
|
||||
Invocation.Builder mockBuilder = mock(Invocation.Builder.class);
|
||||
|
||||
mockedClientBuilder.when(ClientBuilder::newClient).thenReturn(mockClient);
|
||||
when(mockClient.target("http://localhost:8080/admin/realms")).thenReturn(mockWebTarget);
|
||||
when(mockWebTarget.request(jakarta.ws.rs.core.MediaType.APPLICATION_JSON)).thenReturn(mockBuilder);
|
||||
when(mockBuilder.header(anyString(), anyString())).thenReturn(mockBuilder);
|
||||
when(mockBuilder.get(List.class)).thenReturn(null);
|
||||
|
||||
List<String> result = client.getAllRealms();
|
||||
|
||||
assertNotNull(result);
|
||||
assertTrue(result.isEmpty());
|
||||
verify(mockClient).close();
|
||||
}
|
||||
assertFalse(client.isConnected());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_WithEmptyRealmName() throws Exception {
|
||||
Keycloak mockKeycloak = mock(Keycloak.class);
|
||||
TokenManager mockTokenManager = mock(TokenManager.class);
|
||||
setField("keycloak", mockKeycloak);
|
||||
setField("serverUrl", "http://localhost:8080");
|
||||
void testRealmExists_True() {
|
||||
RealmResource mockRealmResource = mock(RealmResource.class);
|
||||
RolesResource mockRolesResource = mock(RolesResource.class);
|
||||
when(mockKeycloak.realm("test-realm")).thenReturn(mockRealmResource);
|
||||
when(mockRealmResource.roles()).thenReturn(mockRolesResource);
|
||||
when(mockRolesResource.list()).thenReturn(List.of());
|
||||
|
||||
when(mockKeycloak.tokenManager()).thenReturn(mockTokenManager);
|
||||
when(mockTokenManager.getAccessTokenString()).thenReturn("test-token");
|
||||
|
||||
try (MockedStatic<ClientBuilder> mockedClientBuilder = mockStatic(ClientBuilder.class)) {
|
||||
Client mockClient = mock(Client.class);
|
||||
WebTarget mockWebTarget = mock(WebTarget.class);
|
||||
Invocation.Builder mockBuilder = mock(Invocation.Builder.class);
|
||||
|
||||
mockedClientBuilder.when(ClientBuilder::newClient).thenReturn(mockClient);
|
||||
when(mockClient.target("http://localhost:8080/admin/realms")).thenReturn(mockWebTarget);
|
||||
when(mockWebTarget.request(jakarta.ws.rs.core.MediaType.APPLICATION_JSON)).thenReturn(mockBuilder);
|
||||
when(mockBuilder.header(anyString(), anyString())).thenReturn(mockBuilder);
|
||||
|
||||
// Mock response with empty realm name
|
||||
Map<String, Object> realm1 = new HashMap<>();
|
||||
realm1.put("realm", "");
|
||||
Map<String, Object> realm2 = new HashMap<>();
|
||||
realm2.put("realm", "realm2");
|
||||
List<Map<String, Object>> realmsJson = new ArrayList<>();
|
||||
realmsJson.add(realm1);
|
||||
realmsJson.add(realm2);
|
||||
|
||||
when(mockBuilder.get(List.class)).thenReturn(realmsJson);
|
||||
|
||||
List<String> result = client.getAllRealms();
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.size()); // Empty realm name should be filtered out
|
||||
assertTrue(result.contains("realm2"));
|
||||
verify(mockClient).close();
|
||||
}
|
||||
assertTrue(client.realmExists("test-realm"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_WithNullRealmName() throws Exception {
|
||||
Keycloak mockKeycloak = mock(Keycloak.class);
|
||||
TokenManager mockTokenManager = mock(TokenManager.class);
|
||||
setField("keycloak", mockKeycloak);
|
||||
setField("serverUrl", "http://localhost:8080");
|
||||
void testRealmExists_NotFound() {
|
||||
RealmResource mockRealmResource = mock(RealmResource.class);
|
||||
RolesResource mockRolesResource = mock(RolesResource.class);
|
||||
when(mockKeycloak.realm("missing")).thenReturn(mockRealmResource);
|
||||
when(mockRealmResource.roles()).thenReturn(mockRolesResource);
|
||||
when(mockRolesResource.list()).thenThrow(new NotFoundException("Not found"));
|
||||
|
||||
when(mockKeycloak.tokenManager()).thenReturn(mockTokenManager);
|
||||
when(mockTokenManager.getAccessTokenString()).thenReturn("test-token");
|
||||
|
||||
try (MockedStatic<ClientBuilder> mockedClientBuilder = mockStatic(ClientBuilder.class)) {
|
||||
Client mockClient = mock(Client.class);
|
||||
WebTarget mockWebTarget = mock(WebTarget.class);
|
||||
Invocation.Builder mockBuilder = mock(Invocation.Builder.class);
|
||||
|
||||
mockedClientBuilder.when(ClientBuilder::newClient).thenReturn(mockClient);
|
||||
when(mockClient.target("http://localhost:8080/admin/realms")).thenReturn(mockWebTarget);
|
||||
when(mockWebTarget.request(jakarta.ws.rs.core.MediaType.APPLICATION_JSON)).thenReturn(mockBuilder);
|
||||
when(mockBuilder.header(anyString(), anyString())).thenReturn(mockBuilder);
|
||||
|
||||
// Mock response with null realm name
|
||||
Map<String, Object> realm1 = new HashMap<>();
|
||||
realm1.put("realm", null);
|
||||
Map<String, Object> realm2 = new HashMap<>();
|
||||
realm2.put("realm", "realm2");
|
||||
List<Map<String, Object>> realmsJson = new ArrayList<>();
|
||||
realmsJson.add(realm1);
|
||||
realmsJson.add(realm2);
|
||||
|
||||
when(mockBuilder.get(List.class)).thenReturn(realmsJson);
|
||||
|
||||
List<String> result = client.getAllRealms();
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.size()); // Null realm name should be filtered out
|
||||
assertTrue(result.contains("realm2"));
|
||||
verify(mockClient).close();
|
||||
}
|
||||
assertFalse(client.realmExists("missing"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_WithException() throws Exception {
|
||||
Keycloak mockKeycloak = mock(Keycloak.class);
|
||||
TokenManager mockTokenManager = mock(TokenManager.class);
|
||||
setField("keycloak", mockKeycloak);
|
||||
setField("serverUrl", "http://localhost:8080");
|
||||
void testRealmExists_OtherException() {
|
||||
when(mockKeycloak.realm("error-realm")).thenThrow(new RuntimeException("Other error"));
|
||||
|
||||
when(mockKeycloak.tokenManager()).thenReturn(mockTokenManager);
|
||||
when(mockTokenManager.getAccessTokenString()).thenThrow(new RuntimeException("Error"));
|
||||
|
||||
List<String> result = client.getAllRealms();
|
||||
|
||||
assertNotNull(result);
|
||||
assertTrue(result.isEmpty()); // Should return empty list on exception
|
||||
assertTrue(client.realmExists("error-realm"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_WithExceptionInClient() throws Exception {
|
||||
Keycloak mockKeycloak = mock(Keycloak.class);
|
||||
TokenManager mockTokenManager = mock(TokenManager.class);
|
||||
setField("keycloak", mockKeycloak);
|
||||
setField("serverUrl", "http://localhost:8080");
|
||||
void testGetAllRealms_TokenError() {
|
||||
// When token retrieval fails, getAllRealms should throw
|
||||
when(mockKeycloak.tokenManager()).thenThrow(new RuntimeException("Token error"));
|
||||
|
||||
when(mockKeycloak.tokenManager()).thenReturn(mockTokenManager);
|
||||
when(mockTokenManager.getAccessTokenString()).thenReturn("test-token");
|
||||
assertThrows(RuntimeException.class, () -> client.getAllRealms());
|
||||
}
|
||||
|
||||
try (MockedStatic<ClientBuilder> mockedClientBuilder = mockStatic(ClientBuilder.class)) {
|
||||
Client mockClient = mock(Client.class);
|
||||
WebTarget mockWebTarget = mock(WebTarget.class);
|
||||
Invocation.Builder mockBuilder = mock(Invocation.Builder.class);
|
||||
@Test
|
||||
void testGetAllRealms_NullTokenManager() {
|
||||
when(mockKeycloak.tokenManager()).thenReturn(null);
|
||||
|
||||
mockedClientBuilder.when(ClientBuilder::newClient).thenReturn(mockClient);
|
||||
when(mockClient.target("http://localhost:8080/admin/realms")).thenReturn(mockWebTarget);
|
||||
when(mockWebTarget.request(jakarta.ws.rs.core.MediaType.APPLICATION_JSON)).thenReturn(mockBuilder);
|
||||
when(mockBuilder.header(anyString(), anyString())).thenReturn(mockBuilder);
|
||||
when(mockBuilder.get(List.class)).thenThrow(new RuntimeException("Connection error"));
|
||||
assertThrows(RuntimeException.class, () -> client.getAllRealms());
|
||||
}
|
||||
|
||||
List<String> result = client.getAllRealms();
|
||||
@Test
|
||||
void testClose() {
|
||||
assertDoesNotThrow(() -> client.close());
|
||||
}
|
||||
|
||||
assertNotNull(result);
|
||||
assertTrue(result.isEmpty()); // Should return empty list on exception
|
||||
verify(mockClient).close(); // Should still close client in finally block
|
||||
}
|
||||
@Test
|
||||
void testReconnect() {
|
||||
assertDoesNotThrow(() -> client.reconnect());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -40,18 +40,20 @@ class KeycloakAdminClientImplTest {
|
||||
@Mock
|
||||
ServerInfoResource serverInfoResource;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
// Inject the mock keycloak instance
|
||||
setField(client, "keycloak", keycloak);
|
||||
}
|
||||
|
||||
private void setField(Object target, String fieldName, Object value) throws Exception {
|
||||
Field field = target.getClass().getDeclaredField(fieldName);
|
||||
field.setAccessible(true);
|
||||
field.set(target, value);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
setField(client, "serverUrl", "http://localhost:8180");
|
||||
setField(client, "adminRealm", "master");
|
||||
setField(client, "adminClientId", "admin-cli");
|
||||
setField(client, "adminUsername", "admin");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetInstance() {
|
||||
Keycloak result = client.getInstance();
|
||||
@@ -59,18 +61,6 @@ class KeycloakAdminClientImplTest {
|
||||
assertEquals(keycloak, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetInstanceReInitWhenNull() throws Exception {
|
||||
// Set keycloak to null
|
||||
setField(client, "keycloak", null);
|
||||
|
||||
// Should attempt to reinitialize (will fail without config, but that's ok)
|
||||
// The method should return null since init() will fail without proper config
|
||||
Keycloak result = client.getInstance();
|
||||
// Since config values are null, keycloak will still be null
|
||||
assertNull(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRealm() {
|
||||
when(keycloak.realm("test-realm")).thenReturn(realmResource);
|
||||
@@ -125,13 +115,6 @@ class KeycloakAdminClientImplTest {
|
||||
assertFalse(client.isConnected());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsConnected_false_null() throws Exception {
|
||||
setField(client, "keycloak", null);
|
||||
|
||||
assertFalse(client.isConnected());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRealmExists_true() {
|
||||
when(keycloak.realm("test-realm")).thenReturn(realmResource);
|
||||
@@ -156,22 +139,16 @@ class KeycloakAdminClientImplTest {
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.list()).thenThrow(new RuntimeException("Some other error"));
|
||||
|
||||
// Should return true assuming realm exists but has issues
|
||||
assertTrue(client.realmExists("problem-realm"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testClose() {
|
||||
client.close();
|
||||
|
||||
verify(keycloak).close();
|
||||
assertDoesNotThrow(() -> client.close());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCloseWhenNull() throws Exception {
|
||||
setField(client, "keycloak", null);
|
||||
|
||||
// Should not throw
|
||||
client.close();
|
||||
void testReconnect() {
|
||||
assertDoesNotThrow(() -> client.reconnect());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
package dev.lions.user.manager.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.quarkus.jackson.ObjectMapperCustomizer;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Tests unitaires pour JacksonConfig
|
||||
*/
|
||||
class JacksonConfigTest {
|
||||
|
||||
private JacksonConfig jacksonConfig;
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
jacksonConfig = new JacksonConfig();
|
||||
objectMapper = new ObjectMapper();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCustomize() {
|
||||
// Avant la personnalisation, FAIL_ON_UNKNOWN_PROPERTIES devrait être true par défaut
|
||||
assertTrue(objectMapper.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
|
||||
|
||||
// Appliquer la personnalisation
|
||||
jacksonConfig.customize(objectMapper);
|
||||
|
||||
// Après la personnalisation, FAIL_ON_UNKNOWN_PROPERTIES devrait être false
|
||||
assertFalse(objectMapper.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testImplementsObjectMapperCustomizer() {
|
||||
assertTrue(jacksonConfig instanceof ObjectMapperCustomizer);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package dev.lions.user.manager.resource;
|
||||
|
||||
import dev.lions.user.manager.dto.audit.AuditLogDTO;
|
||||
import dev.lions.user.manager.dto.common.CountDTO;
|
||||
import dev.lions.user.manager.enums.audit.TypeActionAudit;
|
||||
import dev.lions.user.manager.service.AuditService;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
@@ -10,7 +11,6 @@ import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -32,33 +32,11 @@ class AuditResourceTest {
|
||||
void testSearchLogs() {
|
||||
List<AuditLogDTO> logs = Collections.singletonList(
|
||||
AuditLogDTO.builder().acteurUsername("admin").typeAction(TypeActionAudit.USER_CREATE).build());
|
||||
when(auditService.findByActeur(eq("admin"), isNull(), isNull(), eq(0), eq(50))).thenReturn(logs);
|
||||
when(auditService.findByActeur(eq("admin"), any(), any(), eq(0), eq(50))).thenReturn(logs);
|
||||
|
||||
Response response = auditResource.searchLogs("admin", null, null, null, null, null, 0, 50);
|
||||
List<AuditLogDTO> result = auditResource.searchLogs("admin", null, null, null, null, null, 0, 50);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals(logs, response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSearchLogsWithDates() {
|
||||
List<AuditLogDTO> logs = Collections.emptyList();
|
||||
when(auditService.findByRealm(eq("master"), any(), any(), eq(0), eq(50))).thenReturn(logs);
|
||||
|
||||
Response response = auditResource.searchLogs(null, "2024-01-01T00:00:00", "2024-12-31T23:59:59",
|
||||
TypeActionAudit.USER_CREATE, null, true, 0, 50);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSearchLogsError() {
|
||||
when(auditService.findByRealm(eq("master"), isNull(), isNull(), eq(0), eq(50)))
|
||||
.thenThrow(new RuntimeException("Error"));
|
||||
|
||||
Response response = auditResource.searchLogs(null, null, null, null, null, null, 0, 50);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
assertEquals(logs, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -67,204 +45,89 @@ class AuditResourceTest {
|
||||
AuditLogDTO.builder().acteurUsername("admin").build());
|
||||
when(auditService.findByActeur(eq("admin"), isNull(), isNull(), eq(0), eq(100))).thenReturn(logs);
|
||||
|
||||
Response response = auditResource.getLogsByActor("admin", 100);
|
||||
List<AuditLogDTO> result = auditResource.getLogsByActor("admin", 100);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals(logs, response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetLogsByActorError() {
|
||||
when(auditService.findByActeur(eq("admin"), isNull(), isNull(), eq(0), eq(100)))
|
||||
.thenThrow(new RuntimeException("Error"));
|
||||
|
||||
Response response = auditResource.getLogsByActor("admin", 100);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
assertEquals(logs, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetLogsByResource() {
|
||||
List<AuditLogDTO> logs = Collections.emptyList();
|
||||
when(auditService.findByRessource(eq("USER"), eq("1"), isNull(), isNull(), eq(0), eq(100)))
|
||||
when(auditService.findByRessource(eq("USER"), eq("1"), any(), any(), eq(0), eq(100)))
|
||||
.thenReturn(logs);
|
||||
|
||||
Response response = auditResource.getLogsByResource("USER", "1", 100);
|
||||
List<AuditLogDTO> result = auditResource.getLogsByResource("USER", "1", 100);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals(logs, response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetLogsByResourceError() {
|
||||
when(auditService.findByRessource(eq("USER"), eq("1"), isNull(), isNull(), eq(0), eq(100)))
|
||||
.thenThrow(new RuntimeException("Error"));
|
||||
|
||||
Response response = auditResource.getLogsByResource("USER", "1", 100);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
assertEquals(logs, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetLogsByAction() {
|
||||
List<AuditLogDTO> logs = Collections.emptyList();
|
||||
when(auditService.findByTypeAction(eq(TypeActionAudit.USER_CREATE), eq("master"), isNull(), isNull(), eq(0), eq(100)))
|
||||
when(auditService.findByTypeAction(eq(TypeActionAudit.USER_CREATE), eq("master"), any(), any(), eq(0), eq(100)))
|
||||
.thenReturn(logs);
|
||||
|
||||
Response response = auditResource.getLogsByAction(TypeActionAudit.USER_CREATE, null, null, 100);
|
||||
List<AuditLogDTO> result = auditResource.getLogsByAction(TypeActionAudit.USER_CREATE, null, null, 100);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetLogsByActionWithDates() {
|
||||
List<AuditLogDTO> logs = Collections.emptyList();
|
||||
when(auditService.findByTypeAction(eq(TypeActionAudit.USER_UPDATE), eq("master"), any(), any(), eq(0), eq(50)))
|
||||
.thenReturn(logs);
|
||||
|
||||
Response response = auditResource.getLogsByAction(TypeActionAudit.USER_UPDATE,
|
||||
"2024-01-01T00:00:00", "2024-12-31T23:59:59", 50);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetLogsByActionError() {
|
||||
when(auditService.findByTypeAction(any(), eq("master"), any(), any(), anyInt(), anyInt()))
|
||||
.thenThrow(new RuntimeException("Error"));
|
||||
|
||||
Response response = auditResource.getLogsByAction(TypeActionAudit.USER_CREATE, null, null, 100);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
assertEquals(logs, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetActionStatistics() {
|
||||
Map<TypeActionAudit, Long> stats = Map.of(TypeActionAudit.USER_CREATE, 10L);
|
||||
when(auditService.countByActionType(eq("master"), isNull(), isNull())).thenReturn(stats);
|
||||
when(auditService.countByActionType(eq("master"), any(), any())).thenReturn(stats);
|
||||
|
||||
Response response = auditResource.getActionStatistics(null, null);
|
||||
Map<TypeActionAudit, Long> result = auditResource.getActionStatistics(null, null);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals(stats, response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetActionStatisticsError() {
|
||||
when(auditService.countByActionType(eq("master"), any(), any())).thenThrow(new RuntimeException("Error"));
|
||||
|
||||
Response response = auditResource.getActionStatistics(null, null);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
assertEquals(stats, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetUserActivityStatistics() {
|
||||
Map<String, Long> stats = Map.of("admin", 100L);
|
||||
when(auditService.countByActeur(eq("master"), isNull(), isNull())).thenReturn(stats);
|
||||
when(auditService.countByActeur(eq("master"), any(), any())).thenReturn(stats);
|
||||
|
||||
Response response = auditResource.getUserActivityStatistics(null, null);
|
||||
Map<String, Long> result = auditResource.getUserActivityStatistics(null, null);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals(stats, response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetUserActivityStatisticsError() {
|
||||
when(auditService.countByActeur(eq("master"), any(), any())).thenThrow(new RuntimeException("Error"));
|
||||
|
||||
Response response = auditResource.getUserActivityStatistics(null, null);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
assertEquals(stats, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetFailureCount() {
|
||||
Map<String, Long> successVsFailure = Map.of("failure", 5L, "success", 100L);
|
||||
when(auditService.countSuccessVsFailure(eq("master"), isNull(), isNull())).thenReturn(successVsFailure);
|
||||
when(auditService.countSuccessVsFailure(eq("master"), any(), any())).thenReturn(successVsFailure);
|
||||
|
||||
Response response = auditResource.getFailureCount(null, null);
|
||||
CountDTO result = auditResource.getFailureCount(null, null);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertNotNull(response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetFailureCountError() {
|
||||
when(auditService.countSuccessVsFailure(eq("master"), any(), any())).thenThrow(new RuntimeException("Error"));
|
||||
|
||||
Response response = auditResource.getFailureCount(null, null);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
assertEquals(5L, result.getCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetSuccessCount() {
|
||||
Map<String, Long> successVsFailure = Map.of("failure", 5L, "success", 100L);
|
||||
when(auditService.countSuccessVsFailure(eq("master"), isNull(), isNull())).thenReturn(successVsFailure);
|
||||
when(auditService.countSuccessVsFailure(eq("master"), any(), any())).thenReturn(successVsFailure);
|
||||
|
||||
Response response = auditResource.getSuccessCount(null, null);
|
||||
CountDTO result = auditResource.getSuccessCount(null, null);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertNotNull(response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetSuccessCountError() {
|
||||
when(auditService.countSuccessVsFailure(eq("master"), any(), any())).thenThrow(new RuntimeException("Error"));
|
||||
|
||||
Response response = auditResource.getSuccessCount(null, null);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
assertEquals(100L, result.getCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExportLogsToCSV() {
|
||||
when(auditService.exportToCSV(eq("master"), isNull(), isNull())).thenReturn("csv,data");
|
||||
when(auditService.exportToCSV(eq("master"), any(), any())).thenReturn("csv,data");
|
||||
|
||||
Response response = auditResource.exportLogsToCSV(null, null);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExportLogsToCSVError() {
|
||||
when(auditService.exportToCSV(eq("master"), any(), any())).thenThrow(new RuntimeException("Error"));
|
||||
|
||||
Response response = auditResource.exportLogsToCSV(null, null);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
assertEquals("csv,data", response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPurgeOldLogs() {
|
||||
when(auditService.purgeOldLogs(any())).thenReturn(50L);
|
||||
doNothing().when(auditService).purgeOldLogs(any());
|
||||
|
||||
Response response = auditResource.purgeOldLogs(90);
|
||||
auditResource.purgeOldLogs(90);
|
||||
|
||||
assertEquals(204, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPurgeOldLogsError() {
|
||||
when(auditService.purgeOldLogs(any())).thenThrow(new RuntimeException("Error"));
|
||||
|
||||
Response response = auditResource.purgeOldLogs(90);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
}
|
||||
|
||||
// ============== Inner Class Tests ==============
|
||||
|
||||
@Test
|
||||
void testCountResponseClass() {
|
||||
AuditResource.CountResponse response = new AuditResource.CountResponse(42);
|
||||
assertEquals(42, response.count);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testErrorResponseClass() {
|
||||
AuditResource.ErrorResponse response = new AuditResource.ErrorResponse("Error message");
|
||||
assertEquals("Error message", response.message);
|
||||
verify(auditService).purgeOldLogs(any());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package dev.lions.user.manager.resource;
|
||||
|
||||
import dev.lions.user.manager.dto.realm.AuthorizedRealmsDTO;
|
||||
import dev.lions.user.manager.dto.realm.RealmAccessCheckDTO;
|
||||
import dev.lions.user.manager.dto.realm.RealmAssignmentDTO;
|
||||
import dev.lions.user.manager.service.RealmAuthorizationService;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
@@ -14,7 +16,6 @@ import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import java.security.Principal;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@@ -45,16 +46,16 @@ class RealmAssignmentResourceTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
assignment = RealmAssignmentDTO.builder()
|
||||
.id("assignment-1")
|
||||
.userId("user-1")
|
||||
.username("testuser")
|
||||
.email("test@example.com")
|
||||
.realmName("realm1")
|
||||
.isSuperAdmin(false)
|
||||
.active(true)
|
||||
.assignedAt(LocalDateTime.now())
|
||||
.assignedBy("admin")
|
||||
.build();
|
||||
.id("assignment-1")
|
||||
.userId("user-1")
|
||||
.username("testuser")
|
||||
.email("test@example.com")
|
||||
.realmName("realm1")
|
||||
.isSuperAdmin(false)
|
||||
.active(true)
|
||||
.assignedAt(LocalDateTime.now())
|
||||
.assignedBy("admin")
|
||||
.build();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -62,21 +63,9 @@ class RealmAssignmentResourceTest {
|
||||
List<RealmAssignmentDTO> assignments = Arrays.asList(assignment);
|
||||
when(realmAuthorizationService.getAllAssignments()).thenReturn(assignments);
|
||||
|
||||
Response response = realmAssignmentResource.getAllAssignments();
|
||||
List<RealmAssignmentDTO> result = realmAssignmentResource.getAllAssignments();
|
||||
|
||||
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
|
||||
@SuppressWarnings("unchecked")
|
||||
List<RealmAssignmentDTO> responseAssignments = (List<RealmAssignmentDTO>) response.getEntity();
|
||||
assertEquals(1, responseAssignments.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllAssignments_Error() {
|
||||
when(realmAuthorizationService.getAllAssignments()).thenThrow(new RuntimeException("Error"));
|
||||
|
||||
Response response = realmAssignmentResource.getAllAssignments();
|
||||
|
||||
assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus());
|
||||
assertEquals(1, result.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -84,9 +73,9 @@ class RealmAssignmentResourceTest {
|
||||
List<RealmAssignmentDTO> assignments = Arrays.asList(assignment);
|
||||
when(realmAuthorizationService.getAssignmentsByUser("user-1")).thenReturn(assignments);
|
||||
|
||||
Response response = realmAssignmentResource.getAssignmentsByUser("user-1");
|
||||
List<RealmAssignmentDTO> result = realmAssignmentResource.getAssignmentsByUser("user-1");
|
||||
|
||||
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
|
||||
assertEquals(1, result.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -94,38 +83,35 @@ class RealmAssignmentResourceTest {
|
||||
List<RealmAssignmentDTO> assignments = Arrays.asList(assignment);
|
||||
when(realmAuthorizationService.getAssignmentsByRealm("realm1")).thenReturn(assignments);
|
||||
|
||||
Response response = realmAssignmentResource.getAssignmentsByRealm("realm1");
|
||||
List<RealmAssignmentDTO> result = realmAssignmentResource.getAssignmentsByRealm("realm1");
|
||||
|
||||
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
|
||||
assertEquals(1, result.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAssignmentById_Success() {
|
||||
when(realmAuthorizationService.getAssignmentById("assignment-1")).thenReturn(Optional.of(assignment));
|
||||
|
||||
Response response = realmAssignmentResource.getAssignmentById("assignment-1");
|
||||
RealmAssignmentDTO result = realmAssignmentResource.getAssignmentById("assignment-1");
|
||||
|
||||
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
|
||||
assertNotNull(result);
|
||||
assertEquals("assignment-1", result.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAssignmentById_NotFound() {
|
||||
when(realmAuthorizationService.getAssignmentById("non-existent")).thenReturn(Optional.empty());
|
||||
|
||||
Response response = realmAssignmentResource.getAssignmentById("non-existent");
|
||||
|
||||
assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus());
|
||||
assertThrows(RuntimeException.class, () -> realmAssignmentResource.getAssignmentById("non-existent"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCanManageRealm_Success() {
|
||||
when(realmAuthorizationService.canManageRealm("user-1", "realm1")).thenReturn(true);
|
||||
|
||||
Response response = realmAssignmentResource.canManageRealm("user-1", "realm1");
|
||||
RealmAccessCheckDTO result = realmAssignmentResource.canManageRealm("user-1", "realm1");
|
||||
|
||||
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
|
||||
RealmAssignmentResource.CheckResponse checkResponse = (RealmAssignmentResource.CheckResponse) response.getEntity();
|
||||
assertTrue(checkResponse.canManage);
|
||||
assertTrue(result.isCanManage());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -134,91 +120,70 @@ class RealmAssignmentResourceTest {
|
||||
when(realmAuthorizationService.getAuthorizedRealms("user-1")).thenReturn(realms);
|
||||
when(realmAuthorizationService.isSuperAdmin("user-1")).thenReturn(false);
|
||||
|
||||
Response response = realmAssignmentResource.getAuthorizedRealms("user-1");
|
||||
AuthorizedRealmsDTO result = realmAssignmentResource.getAuthorizedRealms("user-1");
|
||||
|
||||
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
|
||||
RealmAssignmentResource.AuthorizedRealmsResponse authResponse =
|
||||
(RealmAssignmentResource.AuthorizedRealmsResponse) response.getEntity();
|
||||
assertEquals(2, authResponse.realms.size());
|
||||
assertFalse(authResponse.isSuperAdmin);
|
||||
assertEquals(2, result.getRealms().size());
|
||||
assertFalse(result.isSuperAdmin());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAssignRealmToUser_Success() {
|
||||
// En Quarkus, @Context SecurityContext injecté peut être simulé via Mockito
|
||||
// Mais dans RealmAssignmentResource, l'admin est récupéré du SecurityContext.
|
||||
// Puisque c'est un test unitaire @ExtendWith(MockitoExtension.class),
|
||||
// @Inject SecurityContext securityContext est mocké.
|
||||
|
||||
when(securityContext.getUserPrincipal()).thenReturn(principal);
|
||||
when(principal.getName()).thenReturn("admin");
|
||||
when(realmAuthorizationService.assignRealmToUser(any(RealmAssignmentDTO.class))).thenReturn(assignment);
|
||||
|
||||
Response response = realmAssignmentResource.assignRealmToUser(assignment);
|
||||
|
||||
assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAssignRealmToUser_Conflict() {
|
||||
when(securityContext.getUserPrincipal()).thenReturn(principal);
|
||||
when(principal.getName()).thenReturn("admin");
|
||||
when(realmAuthorizationService.assignRealmToUser(any(RealmAssignmentDTO.class)))
|
||||
.thenThrow(new IllegalArgumentException("Already exists"));
|
||||
|
||||
Response response = realmAssignmentResource.assignRealmToUser(assignment);
|
||||
|
||||
assertEquals(Response.Status.CONFLICT.getStatusCode(), response.getStatus());
|
||||
assertEquals(201, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRevokeRealmFromUser_Success() {
|
||||
doNothing().when(realmAuthorizationService).revokeRealmFromUser("user-1", "realm1");
|
||||
|
||||
Response response = realmAssignmentResource.revokeRealmFromUser("user-1", "realm1");
|
||||
realmAssignmentResource.revokeRealmFromUser("user-1", "realm1");
|
||||
|
||||
assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus());
|
||||
verify(realmAuthorizationService).revokeRealmFromUser("user-1", "realm1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRevokeAllRealmsFromUser_Success() {
|
||||
doNothing().when(realmAuthorizationService).revokeAllRealmsFromUser("user-1");
|
||||
|
||||
Response response = realmAssignmentResource.revokeAllRealmsFromUser("user-1");
|
||||
realmAssignmentResource.revokeAllRealmsFromUser("user-1");
|
||||
|
||||
assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus());
|
||||
verify(realmAuthorizationService).revokeAllRealmsFromUser("user-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeactivateAssignment_Success() {
|
||||
doNothing().when(realmAuthorizationService).deactivateAssignment("assignment-1");
|
||||
|
||||
Response response = realmAssignmentResource.deactivateAssignment("assignment-1");
|
||||
realmAssignmentResource.deactivateAssignment("assignment-1");
|
||||
|
||||
assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeactivateAssignment_NotFound() {
|
||||
doThrow(new IllegalArgumentException("Not found"))
|
||||
.when(realmAuthorizationService).deactivateAssignment("non-existent");
|
||||
|
||||
Response response = realmAssignmentResource.deactivateAssignment("non-existent");
|
||||
|
||||
assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus());
|
||||
verify(realmAuthorizationService).deactivateAssignment("assignment-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testActivateAssignment_Success() {
|
||||
doNothing().when(realmAuthorizationService).activateAssignment("assignment-1");
|
||||
|
||||
Response response = realmAssignmentResource.activateAssignment("assignment-1");
|
||||
realmAssignmentResource.activateAssignment("assignment-1");
|
||||
|
||||
assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus());
|
||||
verify(realmAuthorizationService).activateAssignment("assignment-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSetSuperAdmin_Success() {
|
||||
doNothing().when(realmAuthorizationService).setSuperAdmin("user-1", true);
|
||||
|
||||
Response response = realmAssignmentResource.setSuperAdmin("user-1", true);
|
||||
realmAssignmentResource.setSuperAdmin("user-1", true);
|
||||
|
||||
assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus());
|
||||
verify(realmAuthorizationService).setSuperAdmin("user-1", true);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,8 +2,6 @@ package dev.lions.user.manager.resource;
|
||||
|
||||
import dev.lions.user.manager.client.KeycloakAdminClient;
|
||||
import io.quarkus.security.identity.SecurityIdentity;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
@@ -31,43 +29,31 @@ class RealmResourceAdditionalTest {
|
||||
@InjectMocks
|
||||
private RealmResource realmResource;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// Setup
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_Success() {
|
||||
List<String> realms = Arrays.asList("master", "lions-user-manager", "test-realm");
|
||||
when(keycloakAdminClient.getAllRealms()).thenReturn(realms);
|
||||
|
||||
Response response = realmResource.getAllRealms();
|
||||
List<String> result = realmResource.getAllRealms();
|
||||
|
||||
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
|
||||
@SuppressWarnings("unchecked")
|
||||
List<String> responseRealms = (List<String>) response.getEntity();
|
||||
assertEquals(3, responseRealms.size());
|
||||
assertNotNull(result);
|
||||
assertEquals(3, result.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_Empty() {
|
||||
when(keycloakAdminClient.getAllRealms()).thenReturn(List.of());
|
||||
|
||||
Response response = realmResource.getAllRealms();
|
||||
List<String> result = realmResource.getAllRealms();
|
||||
|
||||
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
|
||||
@SuppressWarnings("unchecked")
|
||||
List<String> responseRealms = (List<String>) response.getEntity();
|
||||
assertTrue(responseRealms.isEmpty());
|
||||
assertNotNull(result);
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_Exception() {
|
||||
when(keycloakAdminClient.getAllRealms()).thenThrow(new RuntimeException("Connection error"));
|
||||
|
||||
Response response = realmResource.getAllRealms();
|
||||
|
||||
assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus());
|
||||
assertThrows(RuntimeException.class, () -> realmResource.getAllRealms());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,14 +2,12 @@ package dev.lions.user.manager.resource;
|
||||
|
||||
import dev.lions.user.manager.client.KeycloakAdminClient;
|
||||
import io.quarkus.security.identity.SecurityIdentity;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
@@ -32,24 +30,16 @@ class RealmResourceTest {
|
||||
@InjectMocks
|
||||
private RealmResource realmResource;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// Setup initial
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_Success() {
|
||||
List<String> realms = Arrays.asList("master", "lions-user-manager", "btpxpress");
|
||||
when(keycloakAdminClient.getAllRealms()).thenReturn(realms);
|
||||
|
||||
Response response = realmResource.getAllRealms();
|
||||
List<String> result = realmResource.getAllRealms();
|
||||
|
||||
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
|
||||
@SuppressWarnings("unchecked")
|
||||
List<String> responseRealms = (List<String>) response.getEntity();
|
||||
assertNotNull(responseRealms);
|
||||
assertEquals(3, responseRealms.size());
|
||||
assertEquals("master", responseRealms.get(0));
|
||||
assertNotNull(result);
|
||||
assertEquals(3, result.size());
|
||||
assertEquals("master", result.get(0));
|
||||
verify(keycloakAdminClient).getAllRealms();
|
||||
}
|
||||
|
||||
@@ -57,34 +47,16 @@ class RealmResourceTest {
|
||||
void testGetAllRealms_EmptyList() {
|
||||
when(keycloakAdminClient.getAllRealms()).thenReturn(Collections.emptyList());
|
||||
|
||||
Response response = realmResource.getAllRealms();
|
||||
List<String> result = realmResource.getAllRealms();
|
||||
|
||||
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
|
||||
@SuppressWarnings("unchecked")
|
||||
List<String> responseRealms = (List<String>) response.getEntity();
|
||||
assertNotNull(responseRealms);
|
||||
assertTrue(responseRealms.isEmpty());
|
||||
assertNotNull(result);
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_Exception() {
|
||||
when(keycloakAdminClient.getAllRealms()).thenThrow(new RuntimeException("Keycloak connection error"));
|
||||
|
||||
Response response = realmResource.getAllRealms();
|
||||
|
||||
assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus());
|
||||
RealmResource.ErrorResponse errorResponse = (RealmResource.ErrorResponse) response.getEntity();
|
||||
assertNotNull(errorResponse);
|
||||
assertTrue(errorResponse.getMessage().contains("Erreur lors de la récupération des realms"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testErrorResponse() {
|
||||
RealmResource.ErrorResponse errorResponse = new RealmResource.ErrorResponse("Test error");
|
||||
assertEquals("Test error", errorResponse.getMessage());
|
||||
|
||||
errorResponse.setMessage("New error");
|
||||
assertEquals("New error", errorResponse.getMessage());
|
||||
assertThrows(RuntimeException.class, () -> realmResource.getAllRealms());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package dev.lions.user.manager.resource;
|
||||
|
||||
import dev.lions.user.manager.dto.role.RoleAssignmentDTO;
|
||||
import dev.lions.user.manager.dto.role.RoleAssignmentRequestDTO;
|
||||
import dev.lions.user.manager.dto.role.RoleDTO;
|
||||
import dev.lions.user.manager.enums.role.TypeRole;
|
||||
import dev.lions.user.manager.service.RoleService;
|
||||
@@ -58,28 +59,15 @@ class RoleResourceTest {
|
||||
assertEquals(409, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateRealmRoleError() {
|
||||
RoleDTO input = RoleDTO.builder().name("role").build();
|
||||
|
||||
when(roleService.createRealmRole(any(), eq(REALM)))
|
||||
.thenThrow(new RuntimeException("Error"));
|
||||
|
||||
Response response = roleResource.createRealmRole(input, REALM);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRealmRole() {
|
||||
RoleDTO role = RoleDTO.builder().id("1").name("role").build();
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(Optional.of(role));
|
||||
|
||||
Response response = roleResource.getRealmRole("role", REALM);
|
||||
RoleDTO result = roleResource.getRealmRole("role", REALM);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals(role, response.getEntity());
|
||||
assertEquals(role, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -87,19 +75,7 @@ class RoleResourceTest {
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
Response response = roleResource.getRealmRole("role", REALM);
|
||||
|
||||
assertEquals(404, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRealmRoleError() {
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenThrow(new RuntimeException("Error"));
|
||||
|
||||
Response response = roleResource.getRealmRole("role", REALM);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
assertThrows(RuntimeException.class, () -> roleResource.getRealmRole("role", REALM));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -107,19 +83,9 @@ class RoleResourceTest {
|
||||
List<RoleDTO> roles = Collections.singletonList(RoleDTO.builder().name("role").build());
|
||||
when(roleService.getAllRealmRoles(REALM)).thenReturn(roles);
|
||||
|
||||
Response response = roleResource.getAllRealmRoles(REALM);
|
||||
List<RoleDTO> result = roleResource.getAllRealmRoles(REALM);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals(roles, response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealmRolesError() {
|
||||
when(roleService.getAllRealmRoles(REALM)).thenThrow(new RuntimeException("Error"));
|
||||
|
||||
Response response = roleResource.getAllRealmRoles(REALM);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
assertEquals(roles, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -133,37 +99,9 @@ class RoleResourceTest {
|
||||
when(roleService.updateRole(eq("1"), any(), eq(REALM), eq(TypeRole.REALM_ROLE), isNull()))
|
||||
.thenReturn(updated);
|
||||
|
||||
Response response = roleResource.updateRealmRole("role", input, REALM);
|
||||
RoleDTO result = roleResource.updateRealmRole("role", input, REALM);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals(updated, response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateRealmRoleNotFound() {
|
||||
RoleDTO input = RoleDTO.builder().description("updated").build();
|
||||
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
Response response = roleResource.updateRealmRole("role", input, REALM);
|
||||
|
||||
assertEquals(404, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateRealmRoleError() {
|
||||
RoleDTO existingRole = RoleDTO.builder().id("1").name("role").build();
|
||||
RoleDTO input = RoleDTO.builder().description("updated").build();
|
||||
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(Optional.of(existingRole));
|
||||
when(roleService.updateRole(eq("1"), any(), eq(REALM), eq(TypeRole.REALM_ROLE), isNull()))
|
||||
.thenThrow(new RuntimeException("Error"));
|
||||
|
||||
Response response = roleResource.updateRealmRole("role", input, REALM);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
assertEquals(updated, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -173,32 +111,9 @@ class RoleResourceTest {
|
||||
.thenReturn(Optional.of(existingRole));
|
||||
doNothing().when(roleService).deleteRole(eq("1"), eq(REALM), eq(TypeRole.REALM_ROLE), isNull());
|
||||
|
||||
Response response = roleResource.deleteRealmRole("role", REALM);
|
||||
roleResource.deleteRealmRole("role", REALM);
|
||||
|
||||
assertEquals(204, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteRealmRoleNotFound() {
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
Response response = roleResource.deleteRealmRole("role", REALM);
|
||||
|
||||
assertEquals(404, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteRealmRoleError() {
|
||||
RoleDTO existingRole = RoleDTO.builder().id("1").name("role").build();
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(Optional.of(existingRole));
|
||||
doThrow(new RuntimeException("Error")).when(roleService)
|
||||
.deleteRole(eq("1"), eq(REALM), eq(TypeRole.REALM_ROLE), isNull());
|
||||
|
||||
Response response = roleResource.deleteRealmRole("role", REALM);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
verify(roleService).deleteRole(eq("1"), eq(REALM), eq(TypeRole.REALM_ROLE), isNull());
|
||||
}
|
||||
|
||||
// ============== Client Role Tests ==============
|
||||
@@ -208,7 +123,7 @@ class RoleResourceTest {
|
||||
RoleDTO input = RoleDTO.builder().name("role").build();
|
||||
RoleDTO created = RoleDTO.builder().id("1").name("role").build();
|
||||
|
||||
when(roleService.createClientRole(any(RoleDTO.class), eq(REALM), eq(CLIENT_ID))).thenReturn(created);
|
||||
when(roleService.createClientRole(any(RoleDTO.class), eq(CLIENT_ID), eq(REALM))).thenReturn(created);
|
||||
|
||||
Response response = roleResource.createClientRole(CLIENT_ID, input, REALM);
|
||||
|
||||
@@ -216,48 +131,15 @@ class RoleResourceTest {
|
||||
assertEquals(created, response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateClientRoleError() {
|
||||
RoleDTO input = RoleDTO.builder().name("role").build();
|
||||
|
||||
when(roleService.createClientRole(any(RoleDTO.class), eq(REALM), eq(CLIENT_ID)))
|
||||
.thenThrow(new RuntimeException("Error"));
|
||||
|
||||
Response response = roleResource.createClientRole(CLIENT_ID, input, REALM);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetClientRole() {
|
||||
RoleDTO role = RoleDTO.builder().id("1").name("role").build();
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.CLIENT_ROLE, CLIENT_ID))
|
||||
.thenReturn(Optional.of(role));
|
||||
|
||||
Response response = roleResource.getClientRole(CLIENT_ID, "role", REALM);
|
||||
RoleDTO result = roleResource.getClientRole(CLIENT_ID, "role", REALM);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals(role, response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetClientRoleNotFound() {
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.CLIENT_ROLE, CLIENT_ID))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
Response response = roleResource.getClientRole(CLIENT_ID, "role", REALM);
|
||||
|
||||
assertEquals(404, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetClientRoleError() {
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.CLIENT_ROLE, CLIENT_ID))
|
||||
.thenThrow(new RuntimeException("Error"));
|
||||
|
||||
Response response = roleResource.getClientRole(CLIENT_ID, "role", REALM);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
assertEquals(role, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -265,19 +147,9 @@ class RoleResourceTest {
|
||||
List<RoleDTO> roles = Collections.singletonList(RoleDTO.builder().name("role").build());
|
||||
when(roleService.getAllClientRoles(REALM, CLIENT_ID)).thenReturn(roles);
|
||||
|
||||
Response response = roleResource.getAllClientRoles(CLIENT_ID, REALM);
|
||||
List<RoleDTO> result = roleResource.getAllClientRoles(CLIENT_ID, REALM);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals(roles, response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllClientRolesError() {
|
||||
when(roleService.getAllClientRoles(REALM, CLIENT_ID)).thenThrow(new RuntimeException("Error"));
|
||||
|
||||
Response response = roleResource.getAllClientRoles(CLIENT_ID, REALM);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
assertEquals(roles, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -287,32 +159,9 @@ class RoleResourceTest {
|
||||
.thenReturn(Optional.of(existingRole));
|
||||
doNothing().when(roleService).deleteRole(eq("1"), eq(REALM), eq(TypeRole.CLIENT_ROLE), eq(CLIENT_ID));
|
||||
|
||||
Response response = roleResource.deleteClientRole(CLIENT_ID, "role", REALM);
|
||||
roleResource.deleteClientRole(CLIENT_ID, "role", REALM);
|
||||
|
||||
assertEquals(204, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteClientRoleNotFound() {
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.CLIENT_ROLE, CLIENT_ID))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
Response response = roleResource.deleteClientRole(CLIENT_ID, "role", REALM);
|
||||
|
||||
assertEquals(404, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteClientRoleError() {
|
||||
RoleDTO existingRole = RoleDTO.builder().id("1").name("role").build();
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.CLIENT_ROLE, CLIENT_ID))
|
||||
.thenReturn(Optional.of(existingRole));
|
||||
doThrow(new RuntimeException("Error")).when(roleService)
|
||||
.deleteRole(eq("1"), eq(REALM), eq(TypeRole.CLIENT_ROLE), eq(CLIENT_ID));
|
||||
|
||||
Response response = roleResource.deleteClientRole(CLIENT_ID, "role", REALM);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
verify(roleService).deleteRole(eq("1"), eq(REALM), eq(TypeRole.CLIENT_ROLE), eq(CLIENT_ID));
|
||||
}
|
||||
|
||||
// ============== Role Assignment Tests ==============
|
||||
@@ -321,95 +170,49 @@ class RoleResourceTest {
|
||||
void testAssignRealmRoles() {
|
||||
doNothing().when(roleService).assignRolesToUser(any(RoleAssignmentDTO.class));
|
||||
|
||||
RoleResource.RoleAssignmentRequest request = new RoleResource.RoleAssignmentRequest();
|
||||
request.roleNames = Collections.singletonList("role");
|
||||
RoleAssignmentRequestDTO request = RoleAssignmentRequestDTO.builder()
|
||||
.roleNames(Collections.singletonList("role"))
|
||||
.build();
|
||||
|
||||
Response response = roleResource.assignRealmRoles("user1", REALM, request);
|
||||
roleResource.assignRealmRoles("user1", REALM, request);
|
||||
|
||||
assertEquals(204, response.getStatus());
|
||||
verify(roleService).assignRolesToUser(any(RoleAssignmentDTO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAssignRealmRolesError() {
|
||||
doThrow(new RuntimeException("Error")).when(roleService).assignRolesToUser(any(RoleAssignmentDTO.class));
|
||||
|
||||
RoleResource.RoleAssignmentRequest request = new RoleResource.RoleAssignmentRequest();
|
||||
request.roleNames = Collections.singletonList("role");
|
||||
|
||||
Response response = roleResource.assignRealmRoles("user1", REALM, request);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRevokeRealmRoles() {
|
||||
doNothing().when(roleService).revokeRolesFromUser(any(RoleAssignmentDTO.class));
|
||||
|
||||
RoleResource.RoleAssignmentRequest request = new RoleResource.RoleAssignmentRequest();
|
||||
request.roleNames = Collections.singletonList("role");
|
||||
RoleAssignmentRequestDTO request = RoleAssignmentRequestDTO.builder()
|
||||
.roleNames(Collections.singletonList("role"))
|
||||
.build();
|
||||
|
||||
Response response = roleResource.revokeRealmRoles("user1", REALM, request);
|
||||
roleResource.revokeRealmRoles("user1", REALM, request);
|
||||
|
||||
assertEquals(204, response.getStatus());
|
||||
verify(roleService).revokeRolesFromUser(any(RoleAssignmentDTO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRevokeRealmRolesError() {
|
||||
doThrow(new RuntimeException("Error")).when(roleService).revokeRolesFromUser(any(RoleAssignmentDTO.class));
|
||||
|
||||
RoleResource.RoleAssignmentRequest request = new RoleResource.RoleAssignmentRequest();
|
||||
request.roleNames = Collections.singletonList("role");
|
||||
|
||||
Response response = roleResource.revokeRealmRoles("user1", REALM, request);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAssignClientRoles() {
|
||||
doNothing().when(roleService).assignRolesToUser(any(RoleAssignmentDTO.class));
|
||||
|
||||
RoleResource.RoleAssignmentRequest request = new RoleResource.RoleAssignmentRequest();
|
||||
request.roleNames = Collections.singletonList("role");
|
||||
RoleAssignmentRequestDTO request = RoleAssignmentRequestDTO.builder()
|
||||
.roleNames(Collections.singletonList("role"))
|
||||
.build();
|
||||
|
||||
Response response = roleResource.assignClientRoles(CLIENT_ID, "user1", REALM, request);
|
||||
roleResource.assignClientRoles(CLIENT_ID, "user1", REALM, request);
|
||||
|
||||
assertEquals(204, response.getStatus());
|
||||
verify(roleService).assignRolesToUser(any(RoleAssignmentDTO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAssignClientRolesError() {
|
||||
doThrow(new RuntimeException("Error")).when(roleService).assignRolesToUser(any(RoleAssignmentDTO.class));
|
||||
|
||||
RoleResource.RoleAssignmentRequest request = new RoleResource.RoleAssignmentRequest();
|
||||
request.roleNames = Collections.singletonList("role");
|
||||
|
||||
Response response = roleResource.assignClientRoles(CLIENT_ID, "user1", REALM, request);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetUserRealmRoles() {
|
||||
List<RoleDTO> roles = Collections.singletonList(RoleDTO.builder().name("role").build());
|
||||
when(roleService.getUserRealmRoles("user1", REALM)).thenReturn(roles);
|
||||
|
||||
Response response = roleResource.getUserRealmRoles("user1", REALM);
|
||||
List<RoleDTO> result = roleResource.getUserRealmRoles("user1", REALM);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals(roles, response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetUserRealmRolesError() {
|
||||
when(roleService.getUserRealmRoles("user1", REALM)).thenThrow(new RuntimeException("Error"));
|
||||
|
||||
Response response = roleResource.getUserRealmRoles("user1", REALM);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
assertEquals(roles, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -417,19 +220,9 @@ class RoleResourceTest {
|
||||
List<RoleDTO> roles = Collections.singletonList(RoleDTO.builder().name("role").build());
|
||||
when(roleService.getUserClientRoles("user1", CLIENT_ID, REALM)).thenReturn(roles);
|
||||
|
||||
Response response = roleResource.getUserClientRoles(CLIENT_ID, "user1", REALM);
|
||||
List<RoleDTO> result = roleResource.getUserClientRoles(CLIENT_ID, "user1", REALM);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals(roles, response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetUserClientRolesError() {
|
||||
when(roleService.getUserClientRoles("user1", CLIENT_ID, REALM)).thenThrow(new RuntimeException("Error"));
|
||||
|
||||
Response response = roleResource.getUserClientRoles(CLIENT_ID, "user1", REALM);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
assertEquals(roles, result);
|
||||
}
|
||||
|
||||
// ============== Composite Role Tests ==============
|
||||
@@ -438,104 +231,36 @@ class RoleResourceTest {
|
||||
void testAddComposites() {
|
||||
RoleDTO parentRole = RoleDTO.builder().id("parent-1").name("role").build();
|
||||
RoleDTO childRole = RoleDTO.builder().id("child-1").name("composite").build();
|
||||
|
||||
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(Optional.of(parentRole));
|
||||
when(roleService.getRoleByName("composite", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(Optional.of(childRole));
|
||||
doNothing().when(roleService).addCompositeRoles(eq("parent-1"), anyList(), eq(REALM),
|
||||
doNothing().when(roleService).addCompositeRoles(eq("parent-1"), anyList(), eq(REALM),
|
||||
eq(TypeRole.REALM_ROLE), isNull());
|
||||
|
||||
RoleResource.RoleAssignmentRequest request = new RoleResource.RoleAssignmentRequest();
|
||||
request.roleNames = Collections.singletonList("composite");
|
||||
RoleAssignmentRequestDTO request = RoleAssignmentRequestDTO.builder()
|
||||
.roleNames(Collections.singletonList("composite"))
|
||||
.build();
|
||||
|
||||
Response response = roleResource.addComposites("role", REALM, request);
|
||||
roleResource.addComposites("role", REALM, request);
|
||||
|
||||
assertEquals(204, response.getStatus());
|
||||
verify(roleService).addCompositeRoles(eq("parent-1"), anyList(), eq(REALM),
|
||||
verify(roleService).addCompositeRoles(eq("parent-1"), anyList(), eq(REALM),
|
||||
eq(TypeRole.REALM_ROLE), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAddCompositesParentNotFound() {
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
RoleResource.RoleAssignmentRequest request = new RoleResource.RoleAssignmentRequest();
|
||||
request.roleNames = Collections.singletonList("composite");
|
||||
|
||||
Response response = roleResource.addComposites("role", REALM, request);
|
||||
|
||||
assertEquals(404, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAddCompositesError() {
|
||||
RoleDTO parentRole = RoleDTO.builder().id("parent-1").name("role").build();
|
||||
RoleDTO childRole = RoleDTO.builder().id("child-1").name("composite").build();
|
||||
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(Optional.of(parentRole));
|
||||
when(roleService.getRoleByName("composite", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(Optional.of(childRole));
|
||||
doThrow(new RuntimeException("Error")).when(roleService).addCompositeRoles(eq("parent-1"), anyList(),
|
||||
eq(REALM), eq(TypeRole.REALM_ROLE), isNull());
|
||||
|
||||
RoleResource.RoleAssignmentRequest request = new RoleResource.RoleAssignmentRequest();
|
||||
request.roleNames = Collections.singletonList("composite");
|
||||
|
||||
Response response = roleResource.addComposites("role", REALM, request);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetComposites() {
|
||||
RoleDTO role = RoleDTO.builder().id("1").name("role").build();
|
||||
List<RoleDTO> composites = Collections.singletonList(RoleDTO.builder().name("composite").build());
|
||||
|
||||
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(Optional.of(role));
|
||||
when(roleService.getCompositeRoles("1", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(composites);
|
||||
|
||||
Response response = roleResource.getComposites("role", REALM);
|
||||
List<RoleDTO> result = roleResource.getComposites("role", REALM);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals(composites, response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetCompositesNotFound() {
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
Response response = roleResource.getComposites("role", REALM);
|
||||
|
||||
assertEquals(404, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetCompositesError() {
|
||||
RoleDTO role = RoleDTO.builder().id("1").name("role").build();
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(Optional.of(role));
|
||||
when(roleService.getCompositeRoles("1", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenThrow(new RuntimeException("Error"));
|
||||
|
||||
Response response = roleResource.getComposites("role", REALM);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
}
|
||||
|
||||
// ============== Inner Class Tests ==============
|
||||
|
||||
@Test
|
||||
void testRoleAssignmentRequestClass() {
|
||||
RoleResource.RoleAssignmentRequest request = new RoleResource.RoleAssignmentRequest();
|
||||
request.roleNames = List.of("role1", "role2");
|
||||
|
||||
assertEquals(2, request.roleNames.size());
|
||||
assertTrue(request.roleNames.contains("role1"));
|
||||
assertEquals(composites, result);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
package dev.lions.user.manager.resource;
|
||||
|
||||
import dev.lions.user.manager.api.SyncResourceApi;
|
||||
import dev.lions.user.manager.dto.sync.HealthStatusDTO;
|
||||
import dev.lions.user.manager.dto.sync.SyncResultDTO;
|
||||
import dev.lions.user.manager.service.SyncService;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
@@ -26,228 +26,57 @@ class SyncResourceTest {
|
||||
SyncResource syncResource;
|
||||
|
||||
private static final String REALM = "test-realm";
|
||||
private static final String CLIENT_ID = "test-client";
|
||||
|
||||
@Test
|
||||
void testCheckKeycloakHealth() {
|
||||
when(syncService.isKeycloakAvailable()).thenReturn(true);
|
||||
when(syncService.getKeycloakHealthInfo()).thenReturn(Map.of("version", "23.0.0"));
|
||||
|
||||
HealthStatusDTO status = syncResource.checkKeycloakHealth();
|
||||
|
||||
assertTrue(status.isKeycloakAccessible());
|
||||
assertTrue(status.isOverallHealthy());
|
||||
assertEquals("23.0.0", status.getKeycloakVersion());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCheckKeycloakHealthError() {
|
||||
when(syncService.isKeycloakAvailable()).thenThrow(new RuntimeException("Connection refused"));
|
||||
|
||||
HealthStatusDTO status = syncResource.checkKeycloakHealth();
|
||||
|
||||
assertFalse(status.isOverallHealthy());
|
||||
assertTrue(status.getErrorMessage().contains("Connection refused"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSyncUsers() {
|
||||
when(syncService.syncUsersFromRealm(REALM)).thenReturn(10);
|
||||
|
||||
Response response = syncResource.syncUsers(REALM);
|
||||
SyncResultDTO result = syncResource.syncUsers(REALM);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertNotNull(response.getEntity());
|
||||
assertTrue(result.isSuccess());
|
||||
assertEquals(10, result.getUsersCount());
|
||||
assertEquals(REALM, result.getRealmName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSyncUsersError() {
|
||||
when(syncService.syncUsersFromRealm(REALM)).thenThrow(new RuntimeException("Error"));
|
||||
when(syncService.syncUsersFromRealm(REALM)).thenThrow(new RuntimeException("Sync failed"));
|
||||
|
||||
Response response = syncResource.syncUsers(REALM);
|
||||
SyncResultDTO result = syncResource.syncUsers(REALM);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
assertFalse(result.isSuccess());
|
||||
assertEquals("Sync failed", result.getErrorMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSyncRealmRoles() {
|
||||
void testSyncRoles() {
|
||||
when(syncService.syncRolesFromRealm(REALM)).thenReturn(5);
|
||||
|
||||
Response response = syncResource.syncRealmRoles(REALM);
|
||||
SyncResultDTO result = syncResource.syncRoles(REALM, null);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertNotNull(response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSyncRealmRolesError() {
|
||||
when(syncService.syncRolesFromRealm(REALM)).thenThrow(new RuntimeException("Error"));
|
||||
|
||||
Response response = syncResource.syncRealmRoles(REALM);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSyncClientRoles() {
|
||||
when(syncService.syncRolesFromRealm(REALM)).thenReturn(3);
|
||||
|
||||
Response response = syncResource.syncClientRoles(CLIENT_ID, REALM);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertNotNull(response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSyncClientRolesError() {
|
||||
when(syncService.syncRolesFromRealm(REALM)).thenThrow(new RuntimeException("Error"));
|
||||
|
||||
Response response = syncResource.syncClientRoles(CLIENT_ID, REALM);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSyncAll() {
|
||||
Map<String, Object> result = Map.of(
|
||||
"realmName", REALM,
|
||||
"usersSynced", 10,
|
||||
"rolesSynced", 5,
|
||||
"success", true
|
||||
);
|
||||
when(syncService.forceSyncRealm(REALM)).thenReturn(result);
|
||||
|
||||
Response response = syncResource.syncAll(REALM);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals(result, response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSyncAllError() {
|
||||
when(syncService.forceSyncRealm(REALM)).thenThrow(new RuntimeException("Error"));
|
||||
|
||||
Response response = syncResource.syncAll(REALM);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCheckHealthHealthy() {
|
||||
when(syncService.isKeycloakAvailable()).thenReturn(true);
|
||||
|
||||
Response response = syncResource.checkHealth();
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertNotNull(response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCheckHealthUnhealthy() {
|
||||
when(syncService.isKeycloakAvailable()).thenReturn(false);
|
||||
|
||||
Response response = syncResource.checkHealth();
|
||||
|
||||
assertEquals(503, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCheckHealthError() {
|
||||
when(syncService.isKeycloakAvailable()).thenThrow(new RuntimeException("Error"));
|
||||
|
||||
Response response = syncResource.checkHealth();
|
||||
|
||||
assertEquals(503, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetDetailedHealthStatus() {
|
||||
Map<String, Object> status = Map.of(
|
||||
"keycloakAvailable", true,
|
||||
"keycloakVersion", "21.0.0"
|
||||
);
|
||||
when(syncService.getKeycloakHealthInfo()).thenReturn(status);
|
||||
|
||||
Response response = syncResource.getDetailedHealthStatus();
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals(status, response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetDetailedHealthStatusError() {
|
||||
when(syncService.getKeycloakHealthInfo()).thenThrow(new RuntimeException("Error"));
|
||||
|
||||
Response response = syncResource.getDetailedHealthStatus();
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCheckRealmExistsTrue() {
|
||||
when(syncService.syncUsersFromRealm(REALM)).thenReturn(5);
|
||||
|
||||
Response response = syncResource.checkRealmExists(REALM);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertNotNull(response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCheckRealmExistsFalse() {
|
||||
when(syncService.syncUsersFromRealm(REALM)).thenThrow(new RuntimeException("Realm not found"));
|
||||
|
||||
Response response = syncResource.checkRealmExists(REALM);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertNotNull(response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCheckRealmExistsError() {
|
||||
when(syncService.syncUsersFromRealm(REALM)).thenThrow(new RuntimeException("Unexpected error"));
|
||||
|
||||
Response response = syncResource.checkRealmExists(REALM);
|
||||
|
||||
// checkRealmExists catches all exceptions and returns 200 with exists=false
|
||||
assertEquals(200, response.getStatus());
|
||||
assertNotNull(response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCheckUserExists() {
|
||||
// La méthode checkUserExists retourne toujours false dans l'implémentation actuelle
|
||||
Response response = syncResource.checkUserExists("user1", REALM);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertNotNull(response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCheckUserExistsError() {
|
||||
// Test d'erreur si une exception est levée
|
||||
// Note: L'implémentation actuelle ne lève pas d'exception, mais testons quand même
|
||||
Response response = syncResource.checkUserExists("user1", REALM);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
}
|
||||
|
||||
// ============== Inner Class Tests ==============
|
||||
|
||||
@Test
|
||||
void testSyncUsersResponseClass() {
|
||||
SyncResource.SyncUsersResponse response = new SyncResource.SyncUsersResponse(1, null);
|
||||
|
||||
assertEquals(1, response.count);
|
||||
assertNull(response.users);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSyncRolesResponseClass() {
|
||||
SyncResource.SyncRolesResponse response = new SyncResource.SyncRolesResponse(1, null);
|
||||
|
||||
assertEquals(1, response.count);
|
||||
assertNull(response.roles);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testHealthCheckResponseClass() {
|
||||
SyncResource.HealthCheckResponse response = new SyncResource.HealthCheckResponse(true, "OK");
|
||||
|
||||
assertTrue(response.healthy);
|
||||
assertEquals("OK", response.message);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExistsCheckResponseClass() {
|
||||
SyncResource.ExistsCheckResponse response = new SyncResource.ExistsCheckResponse(true, "realm", "test");
|
||||
|
||||
assertTrue(response.exists);
|
||||
assertEquals("realm", response.resourceType);
|
||||
assertEquals("test", response.resourceId);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testErrorResponseClass() {
|
||||
SyncResource.ErrorResponse response = new SyncResource.ErrorResponse("Error");
|
||||
assertEquals("Error", response.message);
|
||||
assertTrue(result.isSuccess());
|
||||
assertEquals(5, result.getRealmRolesCount());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
package dev.lions.user.manager.resource;
|
||||
|
||||
import dev.lions.user.manager.client.KeycloakAdminClient;
|
||||
import dev.lions.user.manager.dto.common.UserSessionStatsDTO;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.keycloak.admin.client.resource.RealmResource;
|
||||
import org.keycloak.admin.client.resource.UserResource;
|
||||
import org.keycloak.admin.client.resource.UsersResource;
|
||||
import org.keycloak.representations.idm.UserRepresentation;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class UserMetricsResourceTest {
|
||||
|
||||
@Mock
|
||||
KeycloakAdminClient keycloakAdminClient;
|
||||
|
||||
@Mock
|
||||
RealmResource realmResource;
|
||||
|
||||
@Mock
|
||||
UsersResource usersResource;
|
||||
|
||||
@Mock
|
||||
UserResource userResource1;
|
||||
|
||||
@Mock
|
||||
UserResource userResource2;
|
||||
|
||||
@InjectMocks
|
||||
UserMetricsResource userMetricsResource;
|
||||
|
||||
@Test
|
||||
void testGetUserSessionStats() {
|
||||
// Préparer deux utilisateurs avec des sessions différentes
|
||||
UserRepresentation u1 = new UserRepresentation();
|
||||
u1.setId("u1");
|
||||
UserRepresentation u2 = new UserRepresentation();
|
||||
u2.setId("u2");
|
||||
|
||||
when(keycloakAdminClient.getRealm("test-realm")).thenReturn(realmResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
when(usersResource.list()).thenReturn(List.of(u1, u2));
|
||||
|
||||
// u1 a 2 sessions, u2 en a 0
|
||||
when(usersResource.get("u1")).thenReturn(userResource1);
|
||||
when(usersResource.get("u2")).thenReturn(userResource2);
|
||||
when(userResource1.getUserSessions()).thenReturn(List.of(new org.keycloak.representations.idm.UserSessionRepresentation(),
|
||||
new org.keycloak.representations.idm.UserSessionRepresentation()));
|
||||
when(userResource2.getUserSessions()).thenReturn(List.of());
|
||||
|
||||
UserSessionStatsDTO stats = userMetricsResource.getUserSessionStats("test-realm");
|
||||
|
||||
assertNotNull(stats);
|
||||
assertEquals("test-realm", stats.getRealmName());
|
||||
assertEquals(2L, stats.getTotalUsers());
|
||||
assertEquals(2L, stats.getActiveSessions()); // 2 sessions au total
|
||||
assertEquals(1L, stats.getOnlineUsers()); // 1 utilisateur avec au moins une session
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetUserSessionStats_DefaultRealm() {
|
||||
when(keycloakAdminClient.getRealm("master")).thenReturn(realmResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
when(usersResource.list()).thenReturn(List.of());
|
||||
|
||||
UserSessionStatsDTO stats = userMetricsResource.getUserSessionStats(null);
|
||||
|
||||
assertNotNull(stats);
|
||||
assertEquals("master", stats.getRealmName());
|
||||
assertEquals(0L, stats.getTotalUsers());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetUserSessionStats_OnError() {
|
||||
when(keycloakAdminClient.getRealm(anyString()))
|
||||
.thenThrow(new RuntimeException("KC error"));
|
||||
|
||||
Assertions.assertThrows(RuntimeException.class,
|
||||
() -> userMetricsResource.getUserSessionStats("realm"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
package dev.lions.user.manager.resource;
|
||||
|
||||
import dev.lions.user.manager.dto.user.UserDTO;
|
||||
import dev.lions.user.manager.dto.user.UserSearchCriteriaDTO;
|
||||
import dev.lions.user.manager.dto.user.UserSearchResultDTO;
|
||||
import dev.lions.user.manager.dto.user.*;
|
||||
import dev.lions.user.manager.service.UserService;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -12,6 +10,7 @@ import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
@@ -45,23 +44,10 @@ class UserResourceTest {
|
||||
|
||||
when(userService.searchUsers(any())).thenReturn(mockResult);
|
||||
|
||||
Response response = userResource.searchUsers(criteria);
|
||||
UserSearchResultDTO result = userResource.searchUsers(criteria);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertNotNull(response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSearchUsersError() {
|
||||
UserSearchCriteriaDTO criteria = UserSearchCriteriaDTO.builder()
|
||||
.realmName(REALM)
|
||||
.build();
|
||||
|
||||
when(userService.searchUsers(any())).thenThrow(new RuntimeException("Search failed"));
|
||||
|
||||
Response response = userResource.searchUsers(criteria);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.getTotalCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -69,28 +55,17 @@ class UserResourceTest {
|
||||
UserDTO user = UserDTO.builder().id("1").username("testuser").build();
|
||||
when(userService.getUserById("1", REALM)).thenReturn(Optional.of(user));
|
||||
|
||||
Response response = userResource.getUserById("1", REALM);
|
||||
UserDTO result = userResource.getUserById("1", REALM);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals(user, response.getEntity());
|
||||
assertNotNull(result);
|
||||
assertEquals(user, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetUserByIdNotFound() {
|
||||
when(userService.getUserById("1", REALM)).thenReturn(Optional.empty());
|
||||
|
||||
Response response = userResource.getUserById("1", REALM);
|
||||
|
||||
assertEquals(404, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetUserByIdError() {
|
||||
when(userService.getUserById("1", REALM)).thenThrow(new RuntimeException("Error"));
|
||||
|
||||
Response response = userResource.getUserById("1", REALM);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
assertThrows(RuntimeException.class, () -> userResource.getUserById("1", REALM));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -101,18 +76,10 @@ class UserResourceTest {
|
||||
.build();
|
||||
when(userService.getAllUsers(REALM, 0, 20)).thenReturn(mockResult);
|
||||
|
||||
Response response = userResource.getAllUsers(REALM, 0, 20);
|
||||
UserSearchResultDTO result = userResource.getAllUsers(REALM, 0, 20);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllUsersError() {
|
||||
when(userService.getAllUsers(REALM, 0, 20)).thenThrow(new RuntimeException("Error"));
|
||||
|
||||
Response response = userResource.getAllUsers(REALM, 0, 20);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
assertNotNull(result);
|
||||
assertEquals(0, result.getTotalCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -128,17 +95,6 @@ class UserResourceTest {
|
||||
assertEquals(createdUser, response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateUserError() {
|
||||
UserDTO newUser = UserDTO.builder().username("newuser").email("new@test.com").build();
|
||||
|
||||
when(userService.createUser(any(), eq(REALM))).thenThrow(new RuntimeException("Create failed"));
|
||||
|
||||
Response response = userResource.createUser(newUser, REALM);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateUser() {
|
||||
UserDTO updateUser = UserDTO.builder()
|
||||
@@ -157,197 +113,80 @@ class UserResourceTest {
|
||||
|
||||
when(userService.updateUser(eq("1"), any(), eq(REALM))).thenReturn(updatedUser);
|
||||
|
||||
Response response = userResource.updateUser("1", updateUser, REALM);
|
||||
UserDTO result = userResource.updateUser("1", updateUser, REALM);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals(updatedUser, response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateUserError() {
|
||||
UserDTO updateUser = UserDTO.builder()
|
||||
.username("updated")
|
||||
.prenom("John")
|
||||
.nom("Doe")
|
||||
.email("john.doe@test.com")
|
||||
.build();
|
||||
|
||||
when(userService.updateUser(eq("1"), any(), eq(REALM))).thenThrow(new RuntimeException("Update failed"));
|
||||
|
||||
Response response = userResource.updateUser("1", updateUser, REALM);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
assertNotNull(result);
|
||||
assertEquals(updatedUser, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteUser() {
|
||||
doNothing().when(userService).deleteUser("1", REALM, false);
|
||||
|
||||
Response response = userResource.deleteUser("1", REALM, false);
|
||||
userResource.deleteUser("1", REALM, false);
|
||||
|
||||
assertEquals(204, response.getStatus());
|
||||
verify(userService).deleteUser("1", REALM, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteUserHard() {
|
||||
doNothing().when(userService).deleteUser("1", REALM, true);
|
||||
|
||||
Response response = userResource.deleteUser("1", REALM, true);
|
||||
|
||||
assertEquals(204, response.getStatus());
|
||||
verify(userService).deleteUser("1", REALM, true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteUserError() {
|
||||
doThrow(new RuntimeException("Delete failed")).when(userService).deleteUser("1", REALM, false);
|
||||
|
||||
Response response = userResource.deleteUser("1", REALM, false);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testActivateUser() {
|
||||
doNothing().when(userService).activateUser("1", REALM);
|
||||
|
||||
Response response = userResource.activateUser("1", REALM);
|
||||
userResource.activateUser("1", REALM);
|
||||
|
||||
assertEquals(204, response.getStatus());
|
||||
verify(userService).activateUser("1", REALM);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testActivateUserError() {
|
||||
doThrow(new RuntimeException("Activate failed")).when(userService).activateUser("1", REALM);
|
||||
|
||||
Response response = userResource.activateUser("1", REALM);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeactivateUser() {
|
||||
doNothing().when(userService).deactivateUser("1", REALM, "reason");
|
||||
|
||||
Response response = userResource.deactivateUser("1", REALM, "reason");
|
||||
userResource.deactivateUser("1", REALM, "reason");
|
||||
|
||||
assertEquals(204, response.getStatus());
|
||||
verify(userService).deactivateUser("1", REALM, "reason");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeactivateUserError() {
|
||||
doThrow(new RuntimeException("Deactivate failed")).when(userService).deactivateUser("1", REALM, null);
|
||||
|
||||
Response response = userResource.deactivateUser("1", REALM, null);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testResetPassword() {
|
||||
doNothing().when(userService).resetPassword("1", REALM, "newpassword", true);
|
||||
|
||||
UserResource.PasswordResetRequest request = new UserResource.PasswordResetRequest();
|
||||
request.password = "newpassword";
|
||||
request.temporary = true;
|
||||
PasswordResetRequestDTO request = PasswordResetRequestDTO.builder()
|
||||
.password("newpassword")
|
||||
.temporary(true)
|
||||
.build();
|
||||
|
||||
Response response = userResource.resetPassword("1", REALM, request);
|
||||
userResource.resetPassword("1", REALM, request);
|
||||
|
||||
assertEquals(204, response.getStatus());
|
||||
verify(userService).resetPassword("1", REALM, "newpassword", true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testResetPasswordError() {
|
||||
doThrow(new RuntimeException("Reset failed")).when(userService).resetPassword(any(), any(), any(),
|
||||
anyBoolean());
|
||||
|
||||
UserResource.PasswordResetRequest request = new UserResource.PasswordResetRequest();
|
||||
request.password = "newpassword";
|
||||
|
||||
Response response = userResource.resetPassword("1", REALM, request);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSendVerificationEmail() {
|
||||
doNothing().when(userService).sendVerificationEmail("1", REALM);
|
||||
|
||||
Response response = userResource.sendVerificationEmail("1", REALM);
|
||||
userResource.sendVerificationEmail("1", REALM);
|
||||
|
||||
assertEquals(204, response.getStatus());
|
||||
verify(userService).sendVerificationEmail("1", REALM);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSendVerificationEmailError() {
|
||||
doThrow(new RuntimeException("Email failed")).when(userService).sendVerificationEmail("1", REALM);
|
||||
|
||||
Response response = userResource.sendVerificationEmail("1", REALM);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testLogoutAllSessions() {
|
||||
when(userService.logoutAllSessions("1", REALM)).thenReturn(5);
|
||||
|
||||
Response response = userResource.logoutAllSessions("1", REALM);
|
||||
SessionsRevokedDTO result = userResource.logoutAllSessions("1", REALM);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertNotNull(response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testLogoutAllSessionsError() {
|
||||
when(userService.logoutAllSessions("1", REALM)).thenThrow(new RuntimeException("Logout failed"));
|
||||
|
||||
Response response = userResource.logoutAllSessions("1", REALM);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
assertNotNull(result);
|
||||
assertEquals(5, result.getCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetActiveSessions() {
|
||||
when(userService.getActiveSessions("1", REALM)).thenReturn(Collections.emptyList());
|
||||
when(userService.getActiveSessions("1", REALM)).thenReturn(Collections.singletonList("session-1"));
|
||||
|
||||
Response response = userResource.getActiveSessions("1", REALM);
|
||||
List<String> result = userResource.getActiveSessions("1", REALM);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetActiveSessionsError() {
|
||||
when(userService.getActiveSessions("1", REALM)).thenThrow(new RuntimeException("Sessions failed"));
|
||||
|
||||
Response response = userResource.getActiveSessions("1", REALM);
|
||||
|
||||
assertEquals(500, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPasswordResetRequestClass() {
|
||||
UserResource.PasswordResetRequest request = new UserResource.PasswordResetRequest();
|
||||
request.password = "password123";
|
||||
request.temporary = false;
|
||||
|
||||
assertEquals("password123", request.password);
|
||||
assertFalse(request.temporary);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSessionsRevokedResponseClass() {
|
||||
UserResource.SessionsRevokedResponse response = new UserResource.SessionsRevokedResponse(5);
|
||||
assertEquals(5, response.count);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testErrorResponseClass() {
|
||||
UserResource.ErrorResponse response = new UserResource.ErrorResponse("Error message");
|
||||
assertEquals("Error message", response.message);
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.size());
|
||||
assertEquals("session-1", result.get(0));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,21 +2,44 @@ package dev.lions.user.manager.service.impl;
|
||||
|
||||
import dev.lions.user.manager.dto.audit.AuditLogDTO;
|
||||
import dev.lions.user.manager.enums.audit.TypeActionAudit;
|
||||
import dev.lions.user.manager.server.impl.entity.AuditLogEntity;
|
||||
import dev.lions.user.manager.server.impl.mapper.AuditLogMapper;
|
||||
import dev.lions.user.manager.server.impl.repository.AuditLogRepository;
|
||||
import io.quarkus.hibernate.orm.panache.PanacheQuery;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class AuditServiceImplTest {
|
||||
|
||||
@Mock
|
||||
AuditLogRepository auditLogRepository;
|
||||
|
||||
@Mock
|
||||
AuditLogMapper auditLogMapper;
|
||||
|
||||
@InjectMocks
|
||||
AuditServiceImpl auditService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
auditService = new AuditServiceImpl();
|
||||
auditService.auditEnabled = true; // manually injecting config property
|
||||
auditService.logToDatabase = false;
|
||||
auditService.auditEnabled = true;
|
||||
auditService.logToDatabase = true;
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -25,11 +48,11 @@ class AuditServiceImplTest {
|
||||
log.setTypeAction(TypeActionAudit.USER_CREATE);
|
||||
log.setActeurUsername("admin");
|
||||
|
||||
when(auditLogMapper.toEntity(any(AuditLogDTO.class))).thenReturn(new AuditLogEntity());
|
||||
|
||||
auditService.logAction(log);
|
||||
|
||||
assertEquals(1, auditService.getTotalCount());
|
||||
assertNotNull(log.getId());
|
||||
assertNotNull(log.getDateAction());
|
||||
verify(auditLogRepository).persist(any(AuditLogEntity.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -38,41 +61,58 @@ class AuditServiceImplTest {
|
||||
AuditLogDTO log = new AuditLogDTO();
|
||||
|
||||
auditService.logAction(log);
|
||||
assertEquals(0, auditService.getTotalCount());
|
||||
|
||||
verify(auditLogRepository, never()).persist(any(AuditLogEntity.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testLogSuccess() {
|
||||
when(auditLogMapper.toEntity(any(AuditLogDTO.class))).thenReturn(new AuditLogEntity());
|
||||
|
||||
auditService.logSuccess(TypeActionAudit.USER_CREATE, "USER", "1", "user", "realm", "admin", "desc");
|
||||
assertEquals(1, auditService.getTotalCount());
|
||||
|
||||
verify(auditLogRepository).persist(any(AuditLogEntity.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testLogFailure() {
|
||||
when(auditLogMapper.toEntity(any(AuditLogDTO.class))).thenReturn(new AuditLogEntity());
|
||||
|
||||
auditService.logFailure(TypeActionAudit.USER_CREATE, "USER", "1", "user", "realm", "admin", "ERR", "Error");
|
||||
assertEquals(1, auditService.getTotalCount());
|
||||
|
||||
verify(auditLogRepository).persist(any(AuditLogEntity.class));
|
||||
|
||||
// Test findFailures mock logic
|
||||
when(auditLogRepository.search(anyString(), any(), any(), any(), any(), eq(false), anyInt(), anyInt()))
|
||||
.thenReturn(Collections.singletonList(new AuditLogEntity()));
|
||||
when(auditLogMapper.toDTOList(anyList())).thenReturn(Collections.singletonList(new AuditLogDTO()));
|
||||
|
||||
List<AuditLogDTO> failures = auditService.findFailures("realm", null, null, 0, 10);
|
||||
assertEquals(1, failures.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSearchLogs() {
|
||||
auditService.logSuccess(TypeActionAudit.USER_CREATE, "USER", "1", "user1", "realm", "admin1", "");
|
||||
auditService.logSuccess(TypeActionAudit.USER_UPDATE, "USER", "1", "user1", "realm", "admin1", "");
|
||||
auditService.logSuccess(TypeActionAudit.ROLE_CREATE, "ROLE", "r", "role", "realm", "admin2", "");
|
||||
// Mocking repo results
|
||||
when(auditLogRepository.search(any(), anyString(), any(), any(), any(), any(), anyInt(), anyInt()))
|
||||
.thenReturn(Collections.singletonList(new AuditLogEntity()));
|
||||
when(auditLogMapper.toDTOList(anyList())).thenReturn(Collections.singletonList(new AuditLogDTO()));
|
||||
|
||||
List<AuditLogDTO> byActeur = auditService.findByActeur("admin1", null, null, 0, 10);
|
||||
assertEquals(2, byActeur.size());
|
||||
assertNotNull(byActeur);
|
||||
assertFalse(byActeur.isEmpty());
|
||||
|
||||
when(auditLogRepository.search(anyString(), any(), any(), any(), anyString(), any(), anyInt(), anyInt()))
|
||||
.thenReturn(Collections.singletonList(new AuditLogEntity()));
|
||||
|
||||
List<AuditLogDTO> byType = auditService.findByTypeAction(TypeActionAudit.ROLE_CREATE, "realm", null, null, 0,
|
||||
10);
|
||||
assertEquals(1, byType.size());
|
||||
assertNotNull(byType);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testClearAll() {
|
||||
auditService.logAction(new AuditLogDTO());
|
||||
auditService.clearAll();
|
||||
assertEquals(0, auditService.getTotalCount());
|
||||
verify(auditLogRepository).deleteAll();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,11 @@ import java.util.Map;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
import org.mockito.quality.Strictness;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class SyncServiceImplTest {
|
||||
|
||||
@Mock
|
||||
@@ -45,6 +49,15 @@ class SyncServiceImplTest {
|
||||
@Mock
|
||||
ServerInfoResource serverInfoResource;
|
||||
|
||||
@Mock
|
||||
dev.lions.user.manager.server.impl.repository.SyncHistoryRepository syncHistoryRepository;
|
||||
|
||||
@Mock
|
||||
dev.lions.user.manager.server.impl.repository.SyncedUserRepository syncedUserRepository;
|
||||
|
||||
@Mock
|
||||
dev.lions.user.manager.server.impl.repository.SyncedRoleRepository syncedRoleRepository;
|
||||
|
||||
@InjectMocks
|
||||
SyncServiceImpl syncService;
|
||||
|
||||
@@ -116,9 +129,6 @@ class SyncServiceImplTest {
|
||||
|
||||
when(serverInfoResource.getInfo()).thenReturn(info);
|
||||
|
||||
when(keycloakInstance.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.findAll()).thenReturn(Collections.emptyList());
|
||||
|
||||
Map<String, Object> health = syncService.getKeycloakHealthInfo();
|
||||
assertTrue((Boolean) health.get("overallHealthy"));
|
||||
assertEquals("1.0", health.get("keycloakVersion"));
|
||||
@@ -173,7 +183,8 @@ class SyncServiceImplTest {
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
// Note: checkDataConsistency doesn't actually throw exceptions in the current implementation
|
||||
// Note: checkDataConsistency doesn't actually throw exceptions in the current
|
||||
// implementation
|
||||
// The try-catch block is there for future use, but currently always succeeds
|
||||
// So we test the success path in testCheckDataConsistency_Success
|
||||
|
||||
@@ -211,32 +222,22 @@ class SyncServiceImplTest {
|
||||
assertNotNull(health.get("errorMessage"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetKeycloakHealthInfo_RealmsException() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.serverInfo()).thenReturn(serverInfoResource);
|
||||
|
||||
ServerInfoRepresentation info = new ServerInfoRepresentation();
|
||||
SystemInfoRepresentation systemInfo = new SystemInfoRepresentation();
|
||||
systemInfo.setVersion("1.0");
|
||||
info.setSystemInfo(systemInfo);
|
||||
|
||||
when(serverInfoResource.getInfo()).thenReturn(info);
|
||||
|
||||
when(keycloakInstance.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.findAll()).thenThrow(new RuntimeException("Realms error"));
|
||||
|
||||
Map<String, Object> health = syncService.getKeycloakHealthInfo();
|
||||
assertTrue((Boolean) health.get("overallHealthy")); // Still healthy if server is accessible
|
||||
assertFalse((Boolean) health.get("realmsAccessible"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCheckDataConsistency_Success() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm("realm")).thenReturn(realmResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
when(usersResource.list()).thenReturn(Collections.emptyList());
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.list()).thenReturn(Collections.emptyList());
|
||||
|
||||
when(syncedUserRepository.list(anyString(), anyString())).thenReturn(Collections.emptyList());
|
||||
when(syncedRoleRepository.list(anyString(), anyString())).thenReturn(Collections.emptyList());
|
||||
|
||||
Map<String, Object> report = syncService.checkDataConsistency("realm");
|
||||
|
||||
assertEquals("realm", report.get("realmName"));
|
||||
assertEquals("ok", report.get("status"));
|
||||
assertEquals("Cohérence vérifiée", report.get("message"));
|
||||
assertEquals("OK", report.get("status"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
Reference in New Issue
Block a user