chore(quarkus-327): bump to Quarkus 3.27.3 LTS, make pom autonomous, fix UserServiceImpl tests (search → searchByUsername), rename deprecated config keys
Some checks failed
CI/CD Pipeline / pipeline (push) Failing after 1m57s
Some checks failed
CI/CD Pipeline / pipeline (push) Failing after 1m57s
This commit is contained in:
@@ -1,265 +1,265 @@
|
||||
package dev.lions.user.manager.client;
|
||||
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
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.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import jakarta.ws.rs.NotFoundException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* Tests complets pour KeycloakAdminClientImpl
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class KeycloakAdminClientImplCompleteTest {
|
||||
|
||||
@Mock
|
||||
Keycloak mockKeycloak;
|
||||
|
||||
@Mock
|
||||
TokenManager mockTokenManager;
|
||||
|
||||
@InjectMocks
|
||||
KeycloakAdminClientImpl client;
|
||||
|
||||
private HttpServer localServer;
|
||||
private int localPort;
|
||||
|
||||
private void setField(String fieldName, Object value) throws Exception {
|
||||
Field field = KeycloakAdminClientImpl.class.getDeclaredField(fieldName);
|
||||
field.setAccessible(true);
|
||||
field.set(client, value);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
setField("serverUrl", "http://localhost:8180");
|
||||
setField("adminRealm", "master");
|
||||
setField("adminClientId", "admin-cli");
|
||||
setField("adminUsername", "admin");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
if (localServer != null) {
|
||||
localServer.stop(0);
|
||||
localServer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private int startLocalServer(String path, String responseBody, int statusCode) throws Exception {
|
||||
localServer = HttpServer.create(new InetSocketAddress(0), 0);
|
||||
localServer.createContext(path, exchange -> {
|
||||
byte[] bytes = responseBody.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(statusCode, bytes.length);
|
||||
exchange.getResponseBody().write(bytes);
|
||||
exchange.getResponseBody().close();
|
||||
});
|
||||
localServer.start();
|
||||
return localServer.getAddress().getPort();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetInstance() {
|
||||
Keycloak result = client.getInstance();
|
||||
assertSame(mockKeycloak, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRealm_Success() {
|
||||
RealmResource mockRealmResource = mock(RealmResource.class);
|
||||
when(mockKeycloak.realm("test-realm")).thenReturn(mockRealmResource);
|
||||
|
||||
RealmResource result = client.getRealm("test-realm");
|
||||
assertSame(mockRealmResource, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRealm_Exception() {
|
||||
when(mockKeycloak.realm("bad-realm")).thenThrow(new RuntimeException("Connection error"));
|
||||
|
||||
assertThrows(RuntimeException.class, () -> client.getRealm("bad-realm"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetUsers() {
|
||||
RealmResource mockRealmResource = mock(RealmResource.class);
|
||||
UsersResource mockUsersResource = mock(UsersResource.class);
|
||||
when(mockKeycloak.realm("test-realm")).thenReturn(mockRealmResource);
|
||||
when(mockRealmResource.users()).thenReturn(mockUsersResource);
|
||||
|
||||
UsersResource result = client.getUsers("test-realm");
|
||||
assertSame(mockUsersResource, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRoles() {
|
||||
RealmResource mockRealmResource = mock(RealmResource.class);
|
||||
RolesResource mockRolesResource = mock(RolesResource.class);
|
||||
when(mockKeycloak.realm("test-realm")).thenReturn(mockRealmResource);
|
||||
when(mockRealmResource.roles()).thenReturn(mockRolesResource);
|
||||
|
||||
RolesResource result = client.getRoles("test-realm");
|
||||
assertSame(mockRolesResource, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsConnected_True() {
|
||||
when(mockKeycloak.tokenManager()).thenReturn(mockTokenManager);
|
||||
when(mockTokenManager.getAccessTokenString()).thenReturn("fake-token");
|
||||
|
||||
assertTrue(client.isConnected());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsConnected_False() {
|
||||
when(mockKeycloak.tokenManager()).thenThrow(new RuntimeException("Connection refused"));
|
||||
|
||||
assertFalse(client.isConnected());
|
||||
}
|
||||
|
||||
@Test
|
||||
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());
|
||||
|
||||
assertTrue(client.realmExists("test-realm"));
|
||||
}
|
||||
|
||||
@Test
|
||||
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"));
|
||||
|
||||
assertFalse(client.realmExists("missing"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRealmExists_OtherException() {
|
||||
when(mockKeycloak.realm("error-realm")).thenThrow(new RuntimeException("Other error"));
|
||||
|
||||
assertTrue(client.realmExists("error-realm"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_TokenError() {
|
||||
// When token retrieval fails, getAllRealms should throw
|
||||
when(mockKeycloak.tokenManager()).thenThrow(new RuntimeException("Token error"));
|
||||
|
||||
assertThrows(RuntimeException.class, () -> client.getAllRealms());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_NullTokenManager() {
|
||||
when(mockKeycloak.tokenManager()).thenReturn(null);
|
||||
|
||||
assertThrows(RuntimeException.class, () -> client.getAllRealms());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testClose() {
|
||||
assertDoesNotThrow(() -> client.close());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testReconnect() {
|
||||
assertDoesNotThrow(() -> client.reconnect());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testInit() throws Exception {
|
||||
// init() est appelé @PostConstruct — l'appeler via réflexion pour couvrir la méthode
|
||||
Method initMethod = KeycloakAdminClientImpl.class.getDeclaredMethod("init");
|
||||
initMethod.setAccessible(true);
|
||||
assertDoesNotThrow(() -> initMethod.invoke(client));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_Success() throws Exception {
|
||||
// Démarrer un serveur HTTP local qui retourne une liste de realms JSON
|
||||
String realmsJson = "[{\"realm\":\"master\",\"id\":\"1\"},{\"realm\":\"lions\",\"id\":\"2\"}]";
|
||||
localPort = startLocalServer("/admin/realms", realmsJson, 200);
|
||||
setField("serverUrl", "http://localhost:" + localPort);
|
||||
|
||||
when(mockKeycloak.tokenManager()).thenReturn(mockTokenManager);
|
||||
when(mockTokenManager.getAccessTokenString()).thenReturn("fake-token");
|
||||
|
||||
List<String> realms = client.getAllRealms();
|
||||
|
||||
assertNotNull(realms);
|
||||
assertEquals(2, realms.size());
|
||||
assertTrue(realms.contains("master"));
|
||||
assertTrue(realms.contains("lions"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_NonOkResponse() throws Exception {
|
||||
localPort = startLocalServer("/admin/realms", "Forbidden", 403);
|
||||
setField("serverUrl", "http://localhost:" + localPort);
|
||||
|
||||
when(mockKeycloak.tokenManager()).thenReturn(mockTokenManager);
|
||||
when(mockTokenManager.getAccessTokenString()).thenReturn("fake-token");
|
||||
|
||||
assertThrows(RuntimeException.class, () -> client.getAllRealms());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRealmClients_Success() throws Exception {
|
||||
String clientsJson = "[{\"clientId\":\"admin-cli\",\"id\":\"1\"},{\"clientId\":\"account\",\"id\":\"2\"}]";
|
||||
localPort = startLocalServer("/admin/realms/master/clients", clientsJson, 200);
|
||||
setField("serverUrl", "http://localhost:" + localPort);
|
||||
|
||||
when(mockKeycloak.tokenManager()).thenReturn(mockTokenManager);
|
||||
when(mockTokenManager.getAccessTokenString()).thenReturn("fake-token");
|
||||
|
||||
List<String> clients = client.getRealmClients("master");
|
||||
|
||||
assertNotNull(clients);
|
||||
assertEquals(2, clients.size());
|
||||
assertTrue(clients.contains("admin-cli"));
|
||||
assertTrue(clients.contains("account"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRealmClients_NonOkResponse() throws Exception {
|
||||
localPort = startLocalServer("/admin/realms/bad/clients", "Not Found", 404);
|
||||
setField("serverUrl", "http://localhost:" + localPort);
|
||||
|
||||
when(mockKeycloak.tokenManager()).thenReturn(mockTokenManager);
|
||||
when(mockTokenManager.getAccessTokenString()).thenReturn("fake-token");
|
||||
|
||||
assertThrows(RuntimeException.class, () -> client.getRealmClients("bad"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRealmClients_TokenError() {
|
||||
when(mockKeycloak.tokenManager()).thenThrow(new RuntimeException("Token error"));
|
||||
|
||||
assertThrows(RuntimeException.class, () -> client.getRealmClients("master"));
|
||||
}
|
||||
}
|
||||
package dev.lions.user.manager.client;
|
||||
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
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.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import jakarta.ws.rs.NotFoundException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* Tests complets pour KeycloakAdminClientImpl
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class KeycloakAdminClientImplCompleteTest {
|
||||
|
||||
@Mock
|
||||
Keycloak mockKeycloak;
|
||||
|
||||
@Mock
|
||||
TokenManager mockTokenManager;
|
||||
|
||||
@InjectMocks
|
||||
KeycloakAdminClientImpl client;
|
||||
|
||||
private HttpServer localServer;
|
||||
private int localPort;
|
||||
|
||||
private void setField(String fieldName, Object value) throws Exception {
|
||||
Field field = KeycloakAdminClientImpl.class.getDeclaredField(fieldName);
|
||||
field.setAccessible(true);
|
||||
field.set(client, value);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
setField("serverUrl", "http://localhost:8180");
|
||||
setField("adminRealm", "master");
|
||||
setField("adminClientId", "admin-cli");
|
||||
setField("adminUsername", "admin");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
if (localServer != null) {
|
||||
localServer.stop(0);
|
||||
localServer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private int startLocalServer(String path, String responseBody, int statusCode) throws Exception {
|
||||
localServer = HttpServer.create(new InetSocketAddress(0), 0);
|
||||
localServer.createContext(path, exchange -> {
|
||||
byte[] bytes = responseBody.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.sendResponseHeaders(statusCode, bytes.length);
|
||||
exchange.getResponseBody().write(bytes);
|
||||
exchange.getResponseBody().close();
|
||||
});
|
||||
localServer.start();
|
||||
return localServer.getAddress().getPort();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetInstance() {
|
||||
Keycloak result = client.getInstance();
|
||||
assertSame(mockKeycloak, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRealm_Success() {
|
||||
RealmResource mockRealmResource = mock(RealmResource.class);
|
||||
when(mockKeycloak.realm("test-realm")).thenReturn(mockRealmResource);
|
||||
|
||||
RealmResource result = client.getRealm("test-realm");
|
||||
assertSame(mockRealmResource, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRealm_Exception() {
|
||||
when(mockKeycloak.realm("bad-realm")).thenThrow(new RuntimeException("Connection error"));
|
||||
|
||||
assertThrows(RuntimeException.class, () -> client.getRealm("bad-realm"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetUsers() {
|
||||
RealmResource mockRealmResource = mock(RealmResource.class);
|
||||
UsersResource mockUsersResource = mock(UsersResource.class);
|
||||
when(mockKeycloak.realm("test-realm")).thenReturn(mockRealmResource);
|
||||
when(mockRealmResource.users()).thenReturn(mockUsersResource);
|
||||
|
||||
UsersResource result = client.getUsers("test-realm");
|
||||
assertSame(mockUsersResource, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRoles() {
|
||||
RealmResource mockRealmResource = mock(RealmResource.class);
|
||||
RolesResource mockRolesResource = mock(RolesResource.class);
|
||||
when(mockKeycloak.realm("test-realm")).thenReturn(mockRealmResource);
|
||||
when(mockRealmResource.roles()).thenReturn(mockRolesResource);
|
||||
|
||||
RolesResource result = client.getRoles("test-realm");
|
||||
assertSame(mockRolesResource, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsConnected_True() {
|
||||
when(mockKeycloak.tokenManager()).thenReturn(mockTokenManager);
|
||||
when(mockTokenManager.getAccessTokenString()).thenReturn("fake-token");
|
||||
|
||||
assertTrue(client.isConnected());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsConnected_False() {
|
||||
when(mockKeycloak.tokenManager()).thenThrow(new RuntimeException("Connection refused"));
|
||||
|
||||
assertFalse(client.isConnected());
|
||||
}
|
||||
|
||||
@Test
|
||||
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());
|
||||
|
||||
assertTrue(client.realmExists("test-realm"));
|
||||
}
|
||||
|
||||
@Test
|
||||
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"));
|
||||
|
||||
assertFalse(client.realmExists("missing"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRealmExists_OtherException() {
|
||||
when(mockKeycloak.realm("error-realm")).thenThrow(new RuntimeException("Other error"));
|
||||
|
||||
assertTrue(client.realmExists("error-realm"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_TokenError() {
|
||||
// When token retrieval fails, getAllRealms should throw
|
||||
when(mockKeycloak.tokenManager()).thenThrow(new RuntimeException("Token error"));
|
||||
|
||||
assertThrows(RuntimeException.class, () -> client.getAllRealms());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_NullTokenManager() {
|
||||
when(mockKeycloak.tokenManager()).thenReturn(null);
|
||||
|
||||
assertThrows(RuntimeException.class, () -> client.getAllRealms());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testClose() {
|
||||
assertDoesNotThrow(() -> client.close());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testReconnect() {
|
||||
assertDoesNotThrow(() -> client.reconnect());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testInit() throws Exception {
|
||||
// init() est appelé @PostConstruct — l'appeler via réflexion pour couvrir la méthode
|
||||
Method initMethod = KeycloakAdminClientImpl.class.getDeclaredMethod("init");
|
||||
initMethod.setAccessible(true);
|
||||
assertDoesNotThrow(() -> initMethod.invoke(client));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_Success() throws Exception {
|
||||
// Démarrer un serveur HTTP local qui retourne une liste de realms JSON
|
||||
String realmsJson = "[{\"realm\":\"master\",\"id\":\"1\"},{\"realm\":\"lions\",\"id\":\"2\"}]";
|
||||
localPort = startLocalServer("/admin/realms", realmsJson, 200);
|
||||
setField("serverUrl", "http://localhost:" + localPort);
|
||||
|
||||
when(mockKeycloak.tokenManager()).thenReturn(mockTokenManager);
|
||||
when(mockTokenManager.getAccessTokenString()).thenReturn("fake-token");
|
||||
|
||||
List<String> realms = client.getAllRealms();
|
||||
|
||||
assertNotNull(realms);
|
||||
assertEquals(2, realms.size());
|
||||
assertTrue(realms.contains("master"));
|
||||
assertTrue(realms.contains("lions"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_NonOkResponse() throws Exception {
|
||||
localPort = startLocalServer("/admin/realms", "Forbidden", 403);
|
||||
setField("serverUrl", "http://localhost:" + localPort);
|
||||
|
||||
when(mockKeycloak.tokenManager()).thenReturn(mockTokenManager);
|
||||
when(mockTokenManager.getAccessTokenString()).thenReturn("fake-token");
|
||||
|
||||
assertThrows(RuntimeException.class, () -> client.getAllRealms());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRealmClients_Success() throws Exception {
|
||||
String clientsJson = "[{\"clientId\":\"admin-cli\",\"id\":\"1\"},{\"clientId\":\"account\",\"id\":\"2\"}]";
|
||||
localPort = startLocalServer("/admin/realms/master/clients", clientsJson, 200);
|
||||
setField("serverUrl", "http://localhost:" + localPort);
|
||||
|
||||
when(mockKeycloak.tokenManager()).thenReturn(mockTokenManager);
|
||||
when(mockTokenManager.getAccessTokenString()).thenReturn("fake-token");
|
||||
|
||||
List<String> clients = client.getRealmClients("master");
|
||||
|
||||
assertNotNull(clients);
|
||||
assertEquals(2, clients.size());
|
||||
assertTrue(clients.contains("admin-cli"));
|
||||
assertTrue(clients.contains("account"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRealmClients_NonOkResponse() throws Exception {
|
||||
localPort = startLocalServer("/admin/realms/bad/clients", "Not Found", 404);
|
||||
setField("serverUrl", "http://localhost:" + localPort);
|
||||
|
||||
when(mockKeycloak.tokenManager()).thenReturn(mockTokenManager);
|
||||
when(mockTokenManager.getAccessTokenString()).thenReturn("fake-token");
|
||||
|
||||
assertThrows(RuntimeException.class, () -> client.getRealmClients("bad"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRealmClients_TokenError() {
|
||||
when(mockKeycloak.tokenManager()).thenThrow(new RuntimeException("Token error"));
|
||||
|
||||
assertThrows(RuntimeException.class, () -> client.getRealmClients("master"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,158 +1,158 @@
|
||||
package dev.lions.user.manager.client;
|
||||
|
||||
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.ServerInfoResource;
|
||||
import org.keycloak.admin.client.resource.UsersResource;
|
||||
import org.keycloak.admin.client.token.TokenManager;
|
||||
import org.keycloak.representations.info.ServerInfoRepresentation;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import jakarta.ws.rs.NotFoundException;
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class KeycloakAdminClientImplTest {
|
||||
|
||||
@InjectMocks
|
||||
KeycloakAdminClientImpl client;
|
||||
|
||||
@Mock
|
||||
Keycloak keycloak;
|
||||
|
||||
@Mock
|
||||
RealmResource realmResource;
|
||||
|
||||
@Mock
|
||||
UsersResource usersResource;
|
||||
|
||||
@Mock
|
||||
RolesResource rolesResource;
|
||||
|
||||
@Mock
|
||||
ServerInfoResource serverInfoResource;
|
||||
|
||||
@Mock
|
||||
TokenManager tokenManager;
|
||||
|
||||
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();
|
||||
assertNotNull(result);
|
||||
assertEquals(keycloak, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRealm() {
|
||||
when(keycloak.realm("test-realm")).thenReturn(realmResource);
|
||||
|
||||
RealmResource result = client.getRealm("test-realm");
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(realmResource, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRealmThrowsException() {
|
||||
when(keycloak.realm("bad-realm")).thenThrow(new RuntimeException("Connection failed"));
|
||||
|
||||
assertThrows(RuntimeException.class, () -> client.getRealm("bad-realm"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetUsers() {
|
||||
when(keycloak.realm("test-realm")).thenReturn(realmResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
|
||||
UsersResource result = client.getUsers("test-realm");
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(usersResource, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRoles() {
|
||||
when(keycloak.realm("test-realm")).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
|
||||
RolesResource result = client.getRoles("test-realm");
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(rolesResource, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsConnected_true() {
|
||||
when(keycloak.tokenManager()).thenReturn(tokenManager);
|
||||
when(tokenManager.getAccessTokenString()).thenReturn("fake-token");
|
||||
|
||||
assertTrue(client.isConnected());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsConnected_false_exception() {
|
||||
when(keycloak.tokenManager()).thenThrow(new RuntimeException("Connection refused"));
|
||||
|
||||
assertFalse(client.isConnected());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRealmExists_true() {
|
||||
when(keycloak.realm("test-realm")).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.list()).thenReturn(java.util.Collections.emptyList());
|
||||
|
||||
assertTrue(client.realmExists("test-realm"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRealmExists_notFound() {
|
||||
when(keycloak.realm("missing-realm")).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.list()).thenThrow(new NotFoundException("Realm not found"));
|
||||
|
||||
assertFalse(client.realmExists("missing-realm"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRealmExists_otherException() {
|
||||
when(keycloak.realm("problem-realm")).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.list()).thenThrow(new RuntimeException("Some other error"));
|
||||
|
||||
assertTrue(client.realmExists("problem-realm"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testClose() {
|
||||
assertDoesNotThrow(() -> client.close());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testReconnect() {
|
||||
assertDoesNotThrow(() -> client.reconnect());
|
||||
}
|
||||
}
|
||||
package dev.lions.user.manager.client;
|
||||
|
||||
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.ServerInfoResource;
|
||||
import org.keycloak.admin.client.resource.UsersResource;
|
||||
import org.keycloak.admin.client.token.TokenManager;
|
||||
import org.keycloak.representations.info.ServerInfoRepresentation;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import jakarta.ws.rs.NotFoundException;
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class KeycloakAdminClientImplTest {
|
||||
|
||||
@InjectMocks
|
||||
KeycloakAdminClientImpl client;
|
||||
|
||||
@Mock
|
||||
Keycloak keycloak;
|
||||
|
||||
@Mock
|
||||
RealmResource realmResource;
|
||||
|
||||
@Mock
|
||||
UsersResource usersResource;
|
||||
|
||||
@Mock
|
||||
RolesResource rolesResource;
|
||||
|
||||
@Mock
|
||||
ServerInfoResource serverInfoResource;
|
||||
|
||||
@Mock
|
||||
TokenManager tokenManager;
|
||||
|
||||
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();
|
||||
assertNotNull(result);
|
||||
assertEquals(keycloak, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRealm() {
|
||||
when(keycloak.realm("test-realm")).thenReturn(realmResource);
|
||||
|
||||
RealmResource result = client.getRealm("test-realm");
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(realmResource, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRealmThrowsException() {
|
||||
when(keycloak.realm("bad-realm")).thenThrow(new RuntimeException("Connection failed"));
|
||||
|
||||
assertThrows(RuntimeException.class, () -> client.getRealm("bad-realm"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetUsers() {
|
||||
when(keycloak.realm("test-realm")).thenReturn(realmResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
|
||||
UsersResource result = client.getUsers("test-realm");
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(usersResource, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRoles() {
|
||||
when(keycloak.realm("test-realm")).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
|
||||
RolesResource result = client.getRoles("test-realm");
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(rolesResource, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsConnected_true() {
|
||||
when(keycloak.tokenManager()).thenReturn(tokenManager);
|
||||
when(tokenManager.getAccessTokenString()).thenReturn("fake-token");
|
||||
|
||||
assertTrue(client.isConnected());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsConnected_false_exception() {
|
||||
when(keycloak.tokenManager()).thenThrow(new RuntimeException("Connection refused"));
|
||||
|
||||
assertFalse(client.isConnected());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRealmExists_true() {
|
||||
when(keycloak.realm("test-realm")).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.list()).thenReturn(java.util.Collections.emptyList());
|
||||
|
||||
assertTrue(client.realmExists("test-realm"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRealmExists_notFound() {
|
||||
when(keycloak.realm("missing-realm")).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.list()).thenThrow(new NotFoundException("Realm not found"));
|
||||
|
||||
assertFalse(client.realmExists("missing-realm"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRealmExists_otherException() {
|
||||
when(keycloak.realm("problem-realm")).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.list()).thenThrow(new RuntimeException("Some other error"));
|
||||
|
||||
assertTrue(client.realmExists("problem-realm"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testClose() {
|
||||
assertDoesNotThrow(() -> client.close());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testReconnect() {
|
||||
assertDoesNotThrow(() -> client.reconnect());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,422 +1,422 @@
|
||||
package dev.lions.user.manager.config;
|
||||
|
||||
import io.quarkus.runtime.StartupEvent;
|
||||
import jakarta.ws.rs.NotFoundException;
|
||||
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.KeycloakBuilder;
|
||||
import org.keycloak.admin.client.resource.*;
|
||||
import org.keycloak.representations.idm.*;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.net.URI;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* Tests complets pour KeycloakTestUserConfig pour atteindre 100% de couverture
|
||||
* Teste toutes les méthodes privées via la méthode publique onStart
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class KeycloakTestUserConfigCompleteTest {
|
||||
|
||||
private KeycloakTestUserConfig config;
|
||||
private Keycloak adminClient;
|
||||
private RealmsResource realmsResource;
|
||||
private RealmResource realmResource;
|
||||
private RolesResource rolesResource;
|
||||
private RoleResource roleResource;
|
||||
private UsersResource usersResource;
|
||||
private UserResource userResource;
|
||||
private ClientsResource clientsResource;
|
||||
private ClientResource clientResource;
|
||||
private ClientScopesResource clientScopesResource;
|
||||
private ClientScopeResource clientScopeResource;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
config = new KeycloakTestUserConfig();
|
||||
|
||||
// Injecter les valeurs via reflection
|
||||
setField("profile", "dev");
|
||||
setField("keycloakServerUrl", "http://localhost:8080");
|
||||
setField("adminRealm", "master");
|
||||
setField("adminUsername", "admin");
|
||||
setField("adminPassword", "admin");
|
||||
setField("authorizedRealms", "lions-user-manager");
|
||||
|
||||
// Mocks pour Keycloak
|
||||
adminClient = mock(Keycloak.class);
|
||||
realmsResource = mock(RealmsResource.class);
|
||||
realmResource = mock(RealmResource.class);
|
||||
rolesResource = mock(RolesResource.class);
|
||||
roleResource = mock(RoleResource.class);
|
||||
usersResource = mock(UsersResource.class);
|
||||
userResource = mock(UserResource.class);
|
||||
clientsResource = mock(ClientsResource.class);
|
||||
clientResource = mock(ClientResource.class);
|
||||
clientScopesResource = mock(ClientScopesResource.class);
|
||||
clientScopeResource = mock(ClientScopeResource.class);
|
||||
}
|
||||
|
||||
private void setField(String fieldName, Object value) throws Exception {
|
||||
java.lang.reflect.Field field = KeycloakTestUserConfig.class.getDeclaredField(fieldName);
|
||||
field.setAccessible(true);
|
||||
field.set(config, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testOnStart_DevMode() {
|
||||
// Le code est désactivé, donc onStart devrait juste logger et retourner
|
||||
StartupEvent event = mock(StartupEvent.class);
|
||||
|
||||
// Ne devrait pas lancer d'exception
|
||||
assertDoesNotThrow(() -> config.onStart(event));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testEnsureRealmExists_RealmExists() throws Exception {
|
||||
when(adminClient.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.realm("lions-user-manager")).thenReturn(realmResource);
|
||||
when(realmResource.toRepresentation()).thenReturn(new RealmRepresentation());
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("ensureRealmExists", Keycloak.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
assertDoesNotThrow(() -> method.invoke(config, adminClient));
|
||||
verify(realmResource).toRepresentation();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testEnsureRealmExists_RealmNotFound() throws Exception {
|
||||
when(adminClient.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.realm("lions-user-manager")).thenReturn(realmResource);
|
||||
when(realmResource.toRepresentation()).thenThrow(new NotFoundException());
|
||||
doNothing().when(realmsResource).create(any(RealmRepresentation.class));
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("ensureRealmExists", Keycloak.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
assertDoesNotThrow(() -> method.invoke(config, adminClient));
|
||||
verify(realmResource).toRepresentation();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testEnsureRolesExist_AllRolesExist() throws Exception {
|
||||
when(adminClient.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.realm("lions-user-manager")).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.get(anyString())).thenReturn(roleResource);
|
||||
when(roleResource.toRepresentation()).thenReturn(new RoleRepresentation());
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("ensureRolesExist", Keycloak.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
assertDoesNotThrow(() -> method.invoke(config, adminClient));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testEnsureRolesExist_RoleNotFound() throws Exception {
|
||||
when(adminClient.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.realm("lions-user-manager")).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.get(anyString())).thenReturn(roleResource);
|
||||
when(roleResource.toRepresentation())
|
||||
.thenThrow(new NotFoundException())
|
||||
.thenReturn(new RoleRepresentation());
|
||||
doNothing().when(rolesResource).create(any(RoleRepresentation.class));
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("ensureRolesExist", Keycloak.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
assertDoesNotThrow(() -> method.invoke(config, adminClient));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testEnsureTestUserExists_UserExists() throws Exception {
|
||||
when(adminClient.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.realm("lions-user-manager")).thenReturn(realmResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
|
||||
UserRepresentation existingUser = new UserRepresentation();
|
||||
existingUser.setId("user-id-123");
|
||||
when(usersResource.search("test-user", true)).thenReturn(List.of(existingUser));
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("ensureTestUserExists", Keycloak.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
String userId = (String) method.invoke(config, adminClient);
|
||||
assertEquals("user-id-123", userId);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testEnsureTestUserExists_UserNotFound() throws Exception {
|
||||
when(adminClient.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.realm("lions-user-manager")).thenReturn(realmResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
when(usersResource.search("test-user", true)).thenReturn(Collections.emptyList());
|
||||
|
||||
Response response = mock(Response.class);
|
||||
when(response.getStatusInfo()).thenReturn(Response.Status.CREATED);
|
||||
when(response.getLocation()).thenReturn(URI.create("http://localhost/users/user-id-123"));
|
||||
when(usersResource.create(any(UserRepresentation.class))).thenReturn(response);
|
||||
when(usersResource.get("user-id-123")).thenReturn(userResource);
|
||||
|
||||
CredentialRepresentation credential = new CredentialRepresentation();
|
||||
doNothing().when(userResource).resetPassword(any(CredentialRepresentation.class));
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("ensureTestUserExists", Keycloak.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
String userId = (String) method.invoke(config, adminClient);
|
||||
assertEquals("user-id-123", userId);
|
||||
verify(usersResource).create(any(UserRepresentation.class));
|
||||
verify(userResource).resetPassword(any(CredentialRepresentation.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAssignRolesToUser() throws Exception {
|
||||
when(adminClient.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.realm("lions-user-manager")).thenReturn(realmResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.get(anyString())).thenReturn(roleResource);
|
||||
|
||||
RoleRepresentation role = new RoleRepresentation();
|
||||
role.setName("admin");
|
||||
when(roleResource.toRepresentation()).thenReturn(role);
|
||||
|
||||
when(usersResource.get("user-id")).thenReturn(userResource);
|
||||
RoleMappingResource roleMappingResource = mock(RoleMappingResource.class);
|
||||
RoleScopeResource roleScopeResource = mock(RoleScopeResource.class);
|
||||
when(userResource.roles()).thenReturn(roleMappingResource);
|
||||
when(roleMappingResource.realmLevel()).thenReturn(roleScopeResource);
|
||||
doNothing().when(roleScopeResource).add(anyList());
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("assignRolesToUser", Keycloak.class, String.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
assertDoesNotThrow(() -> method.invoke(config, adminClient, "user-id"));
|
||||
verify(roleScopeResource).add(anyList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testEnsureClientAndMapper_ClientExists() throws Exception {
|
||||
when(adminClient.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.realm("lions-user-manager")).thenReturn(realmResource);
|
||||
when(realmResource.clients()).thenReturn(clientsResource);
|
||||
|
||||
ClientRepresentation existingClient = new ClientRepresentation();
|
||||
existingClient.setId("client-id-123");
|
||||
when(clientsResource.findByClientId("lions-user-manager-client")).thenReturn(List.of(existingClient));
|
||||
|
||||
when(realmResource.clientScopes()).thenReturn(clientScopesResource);
|
||||
ClientScopeRepresentation rolesScope = new ClientScopeRepresentation();
|
||||
rolesScope.setId("scope-id");
|
||||
rolesScope.setName("roles");
|
||||
when(clientScopesResource.findAll()).thenReturn(List.of(rolesScope));
|
||||
|
||||
when(clientsResource.get("client-id-123")).thenReturn(clientResource);
|
||||
when(clientResource.getDefaultClientScopes()).thenReturn(List.of(rolesScope));
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("ensureClientAndMapper", Keycloak.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
assertDoesNotThrow(() -> method.invoke(config, adminClient));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testEnsureClientAndMapper_ClientNotFound() throws Exception {
|
||||
when(adminClient.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.realm("lions-user-manager")).thenReturn(realmResource);
|
||||
when(realmResource.clients()).thenReturn(clientsResource);
|
||||
when(clientsResource.findByClientId("lions-user-manager-client")).thenReturn(Collections.emptyList());
|
||||
|
||||
Response response = mock(Response.class);
|
||||
when(response.getStatusInfo()).thenReturn(Response.Status.CREATED);
|
||||
when(response.getLocation()).thenReturn(URI.create("http://localhost/clients/client-id-123"));
|
||||
when(clientsResource.create(any(ClientRepresentation.class))).thenReturn(response);
|
||||
|
||||
when(realmResource.clientScopes()).thenReturn(clientScopesResource);
|
||||
ClientScopeRepresentation rolesScope = new ClientScopeRepresentation();
|
||||
rolesScope.setId("scope-id");
|
||||
rolesScope.setName("roles");
|
||||
when(clientScopesResource.findAll()).thenReturn(List.of(rolesScope));
|
||||
|
||||
when(clientsResource.get("client-id-123")).thenReturn(clientResource);
|
||||
when(clientResource.getDefaultClientScopes()).thenReturn(List.of(rolesScope));
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("ensureClientAndMapper", Keycloak.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
assertDoesNotThrow(() -> method.invoke(config, adminClient));
|
||||
verify(clientsResource).create(any(ClientRepresentation.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testEnsureClientAndMapper_ClientNotFound_NoRolesScope() throws Exception {
|
||||
when(adminClient.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.realm("lions-user-manager")).thenReturn(realmResource);
|
||||
when(realmResource.clients()).thenReturn(clientsResource);
|
||||
when(clientsResource.findByClientId("lions-user-manager-client")).thenReturn(Collections.emptyList());
|
||||
|
||||
Response response = mock(Response.class);
|
||||
when(response.getStatusInfo()).thenReturn(Response.Status.CREATED);
|
||||
when(response.getLocation()).thenReturn(URI.create("http://localhost/clients/client-id-123"));
|
||||
when(clientsResource.create(any(ClientRepresentation.class))).thenReturn(response);
|
||||
|
||||
when(realmResource.clientScopes()).thenReturn(clientScopesResource);
|
||||
when(clientScopesResource.findAll()).thenReturn(Collections.emptyList());
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("ensureClientAndMapper", Keycloak.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
assertDoesNotThrow(() -> method.invoke(config, adminClient));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testEnsureClientAndMapper_ClientNotFound_RolesScopeAlreadyPresent() throws Exception {
|
||||
when(adminClient.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.realm("lions-user-manager")).thenReturn(realmResource);
|
||||
when(realmResource.clients()).thenReturn(clientsResource);
|
||||
when(clientsResource.findByClientId("lions-user-manager-client")).thenReturn(Collections.emptyList());
|
||||
|
||||
Response response = mock(Response.class);
|
||||
when(response.getStatusInfo()).thenReturn(Response.Status.CREATED);
|
||||
when(response.getLocation()).thenReturn(URI.create("http://localhost/clients/client-id-123"));
|
||||
when(clientsResource.create(any(ClientRepresentation.class))).thenReturn(response);
|
||||
|
||||
when(realmResource.clientScopes()).thenReturn(clientScopesResource);
|
||||
ClientScopeRepresentation rolesScope = new ClientScopeRepresentation();
|
||||
rolesScope.setId("scope-id");
|
||||
rolesScope.setName("roles");
|
||||
when(clientScopesResource.findAll()).thenReturn(List.of(rolesScope));
|
||||
|
||||
when(clientsResource.get("client-id-123")).thenReturn(clientResource);
|
||||
// Simuler que le scope "roles" est déjà présent
|
||||
when(clientResource.getDefaultClientScopes()).thenReturn(List.of(rolesScope));
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("ensureClientAndMapper", Keycloak.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
assertDoesNotThrow(() -> method.invoke(config, adminClient));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testEnsureClientAndMapper_Exception() throws Exception {
|
||||
when(adminClient.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.realm("lions-user-manager")).thenReturn(realmResource);
|
||||
when(realmResource.clients()).thenReturn(clientsResource);
|
||||
when(clientsResource.findByClientId("lions-user-manager-client")).thenThrow(new RuntimeException("Connection error"));
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("ensureClientAndMapper", Keycloak.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
assertDoesNotThrow(() -> method.invoke(config, adminClient));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetCreatedId_Success() throws Exception {
|
||||
Response response = mock(Response.class);
|
||||
when(response.getStatusInfo()).thenReturn(Response.Status.CREATED);
|
||||
when(response.getLocation()).thenReturn(URI.create("http://localhost/users/user-id-123"));
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("getCreatedId", Response.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
String id = (String) method.invoke(config, response);
|
||||
assertEquals("user-id-123", id);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetCreatedId_Error() throws Exception {
|
||||
Response response = mock(Response.class);
|
||||
// Utiliser Response.Status.BAD_REQUEST directement
|
||||
when(response.getStatusInfo()).thenReturn(Response.Status.BAD_REQUEST);
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("getCreatedId", Response.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
Exception exception = assertThrows(Exception.class, () -> method.invoke(config, response));
|
||||
assertTrue(exception.getCause() instanceof RuntimeException);
|
||||
assertTrue(exception.getCause().getMessage().contains("Erreur lors de la création"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Couvre L250-252 : le scope "roles" n'est pas encore dans les scopes du client,
|
||||
* donc addDefaultClientScope est appelé.
|
||||
*/
|
||||
@Test
|
||||
void testEnsureClientAndMapper_ClientExists_RolesScopeNotYetPresent() throws Exception {
|
||||
when(adminClient.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.realm("lions-user-manager")).thenReturn(realmResource);
|
||||
when(realmResource.clients()).thenReturn(clientsResource);
|
||||
|
||||
ClientRepresentation existingClient = new ClientRepresentation();
|
||||
existingClient.setId("client-id-456");
|
||||
when(clientsResource.findByClientId("lions-user-manager-client")).thenReturn(List.of(existingClient));
|
||||
|
||||
// Le scope "roles" existe dans le realm
|
||||
when(realmResource.clientScopes()).thenReturn(clientScopesResource);
|
||||
ClientScopeRepresentation rolesScope = new ClientScopeRepresentation();
|
||||
rolesScope.setId("scope-roles-id");
|
||||
rolesScope.setName("roles");
|
||||
when(clientScopesResource.findAll()).thenReturn(List.of(rolesScope));
|
||||
|
||||
// Mais il N'EST PAS encore dans les scopes par défaut du client (liste vide)
|
||||
when(clientsResource.get("client-id-456")).thenReturn(clientResource);
|
||||
when(clientResource.getDefaultClientScopes()).thenReturn(Collections.emptyList());
|
||||
doNothing().when(clientResource).addDefaultClientScope(anyString());
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("ensureClientAndMapper", Keycloak.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
assertDoesNotThrow(() -> method.invoke(config, adminClient));
|
||||
// Vérifie que addDefaultClientScope a été appelé avec l'ID du scope
|
||||
verify(clientResource).addDefaultClientScope("scope-roles-id");
|
||||
}
|
||||
|
||||
/**
|
||||
* Couvre L259-260 : addDefaultClientScope lève une exception → catch warn.
|
||||
*/
|
||||
@Test
|
||||
void testEnsureClientAndMapper_ClientExists_AddScopeThrowsException() throws Exception {
|
||||
when(adminClient.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.realm("lions-user-manager")).thenReturn(realmResource);
|
||||
when(realmResource.clients()).thenReturn(clientsResource);
|
||||
|
||||
ClientRepresentation existingClient = new ClientRepresentation();
|
||||
existingClient.setId("client-id-789");
|
||||
when(clientsResource.findByClientId("lions-user-manager-client")).thenReturn(List.of(existingClient));
|
||||
|
||||
when(realmResource.clientScopes()).thenReturn(clientScopesResource);
|
||||
ClientScopeRepresentation rolesScope = new ClientScopeRepresentation();
|
||||
rolesScope.setId("scope-roles-id-2");
|
||||
rolesScope.setName("roles");
|
||||
when(clientScopesResource.findAll()).thenReturn(List.of(rolesScope));
|
||||
|
||||
// Scope pas encore présent
|
||||
when(clientsResource.get("client-id-789")).thenReturn(clientResource);
|
||||
when(clientResource.getDefaultClientScopes()).thenReturn(Collections.emptyList());
|
||||
// addDefaultClientScope lève une exception → couvre le catch L259-260
|
||||
doThrow(new RuntimeException("Forbidden")).when(clientResource).addDefaultClientScope(anyString());
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("ensureClientAndMapper", Keycloak.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
// La méthode ne doit pas propager l'exception (catch + warn)
|
||||
assertDoesNotThrow(() -> method.invoke(config, adminClient));
|
||||
}
|
||||
}
|
||||
|
||||
package dev.lions.user.manager.config;
|
||||
|
||||
import io.quarkus.runtime.StartupEvent;
|
||||
import jakarta.ws.rs.NotFoundException;
|
||||
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.KeycloakBuilder;
|
||||
import org.keycloak.admin.client.resource.*;
|
||||
import org.keycloak.representations.idm.*;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.net.URI;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* Tests complets pour KeycloakTestUserConfig pour atteindre 100% de couverture
|
||||
* Teste toutes les méthodes privées via la méthode publique onStart
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class KeycloakTestUserConfigCompleteTest {
|
||||
|
||||
private KeycloakTestUserConfig config;
|
||||
private Keycloak adminClient;
|
||||
private RealmsResource realmsResource;
|
||||
private RealmResource realmResource;
|
||||
private RolesResource rolesResource;
|
||||
private RoleResource roleResource;
|
||||
private UsersResource usersResource;
|
||||
private UserResource userResource;
|
||||
private ClientsResource clientsResource;
|
||||
private ClientResource clientResource;
|
||||
private ClientScopesResource clientScopesResource;
|
||||
private ClientScopeResource clientScopeResource;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
config = new KeycloakTestUserConfig();
|
||||
|
||||
// Injecter les valeurs via reflection
|
||||
setField("profile", "dev");
|
||||
setField("keycloakServerUrl", "http://localhost:8080");
|
||||
setField("adminRealm", "master");
|
||||
setField("adminUsername", "admin");
|
||||
setField("adminPassword", "admin");
|
||||
setField("authorizedRealms", "lions-user-manager");
|
||||
|
||||
// Mocks pour Keycloak
|
||||
adminClient = mock(Keycloak.class);
|
||||
realmsResource = mock(RealmsResource.class);
|
||||
realmResource = mock(RealmResource.class);
|
||||
rolesResource = mock(RolesResource.class);
|
||||
roleResource = mock(RoleResource.class);
|
||||
usersResource = mock(UsersResource.class);
|
||||
userResource = mock(UserResource.class);
|
||||
clientsResource = mock(ClientsResource.class);
|
||||
clientResource = mock(ClientResource.class);
|
||||
clientScopesResource = mock(ClientScopesResource.class);
|
||||
clientScopeResource = mock(ClientScopeResource.class);
|
||||
}
|
||||
|
||||
private void setField(String fieldName, Object value) throws Exception {
|
||||
java.lang.reflect.Field field = KeycloakTestUserConfig.class.getDeclaredField(fieldName);
|
||||
field.setAccessible(true);
|
||||
field.set(config, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testOnStart_DevMode() {
|
||||
// Le code est désactivé, donc onStart devrait juste logger et retourner
|
||||
StartupEvent event = mock(StartupEvent.class);
|
||||
|
||||
// Ne devrait pas lancer d'exception
|
||||
assertDoesNotThrow(() -> config.onStart(event));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testEnsureRealmExists_RealmExists() throws Exception {
|
||||
when(adminClient.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.realm("lions-user-manager")).thenReturn(realmResource);
|
||||
when(realmResource.toRepresentation()).thenReturn(new RealmRepresentation());
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("ensureRealmExists", Keycloak.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
assertDoesNotThrow(() -> method.invoke(config, adminClient));
|
||||
verify(realmResource).toRepresentation();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testEnsureRealmExists_RealmNotFound() throws Exception {
|
||||
when(adminClient.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.realm("lions-user-manager")).thenReturn(realmResource);
|
||||
when(realmResource.toRepresentation()).thenThrow(new NotFoundException());
|
||||
doNothing().when(realmsResource).create(any(RealmRepresentation.class));
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("ensureRealmExists", Keycloak.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
assertDoesNotThrow(() -> method.invoke(config, adminClient));
|
||||
verify(realmResource).toRepresentation();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testEnsureRolesExist_AllRolesExist() throws Exception {
|
||||
when(adminClient.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.realm("lions-user-manager")).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.get(anyString())).thenReturn(roleResource);
|
||||
when(roleResource.toRepresentation()).thenReturn(new RoleRepresentation());
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("ensureRolesExist", Keycloak.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
assertDoesNotThrow(() -> method.invoke(config, adminClient));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testEnsureRolesExist_RoleNotFound() throws Exception {
|
||||
when(adminClient.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.realm("lions-user-manager")).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.get(anyString())).thenReturn(roleResource);
|
||||
when(roleResource.toRepresentation())
|
||||
.thenThrow(new NotFoundException())
|
||||
.thenReturn(new RoleRepresentation());
|
||||
doNothing().when(rolesResource).create(any(RoleRepresentation.class));
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("ensureRolesExist", Keycloak.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
assertDoesNotThrow(() -> method.invoke(config, adminClient));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testEnsureTestUserExists_UserExists() throws Exception {
|
||||
when(adminClient.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.realm("lions-user-manager")).thenReturn(realmResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
|
||||
UserRepresentation existingUser = new UserRepresentation();
|
||||
existingUser.setId("user-id-123");
|
||||
when(usersResource.search("test-user", true)).thenReturn(List.of(existingUser));
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("ensureTestUserExists", Keycloak.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
String userId = (String) method.invoke(config, adminClient);
|
||||
assertEquals("user-id-123", userId);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testEnsureTestUserExists_UserNotFound() throws Exception {
|
||||
when(adminClient.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.realm("lions-user-manager")).thenReturn(realmResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
when(usersResource.search("test-user", true)).thenReturn(Collections.emptyList());
|
||||
|
||||
Response response = mock(Response.class);
|
||||
when(response.getStatusInfo()).thenReturn(Response.Status.CREATED);
|
||||
when(response.getLocation()).thenReturn(URI.create("http://localhost/users/user-id-123"));
|
||||
when(usersResource.create(any(UserRepresentation.class))).thenReturn(response);
|
||||
when(usersResource.get("user-id-123")).thenReturn(userResource);
|
||||
|
||||
CredentialRepresentation credential = new CredentialRepresentation();
|
||||
doNothing().when(userResource).resetPassword(any(CredentialRepresentation.class));
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("ensureTestUserExists", Keycloak.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
String userId = (String) method.invoke(config, adminClient);
|
||||
assertEquals("user-id-123", userId);
|
||||
verify(usersResource).create(any(UserRepresentation.class));
|
||||
verify(userResource).resetPassword(any(CredentialRepresentation.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAssignRolesToUser() throws Exception {
|
||||
when(adminClient.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.realm("lions-user-manager")).thenReturn(realmResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.get(anyString())).thenReturn(roleResource);
|
||||
|
||||
RoleRepresentation role = new RoleRepresentation();
|
||||
role.setName("admin");
|
||||
when(roleResource.toRepresentation()).thenReturn(role);
|
||||
|
||||
when(usersResource.get("user-id")).thenReturn(userResource);
|
||||
RoleMappingResource roleMappingResource = mock(RoleMappingResource.class);
|
||||
RoleScopeResource roleScopeResource = mock(RoleScopeResource.class);
|
||||
when(userResource.roles()).thenReturn(roleMappingResource);
|
||||
when(roleMappingResource.realmLevel()).thenReturn(roleScopeResource);
|
||||
doNothing().when(roleScopeResource).add(anyList());
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("assignRolesToUser", Keycloak.class, String.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
assertDoesNotThrow(() -> method.invoke(config, adminClient, "user-id"));
|
||||
verify(roleScopeResource).add(anyList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testEnsureClientAndMapper_ClientExists() throws Exception {
|
||||
when(adminClient.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.realm("lions-user-manager")).thenReturn(realmResource);
|
||||
when(realmResource.clients()).thenReturn(clientsResource);
|
||||
|
||||
ClientRepresentation existingClient = new ClientRepresentation();
|
||||
existingClient.setId("client-id-123");
|
||||
when(clientsResource.findByClientId("lions-user-manager-client")).thenReturn(List.of(existingClient));
|
||||
|
||||
when(realmResource.clientScopes()).thenReturn(clientScopesResource);
|
||||
ClientScopeRepresentation rolesScope = new ClientScopeRepresentation();
|
||||
rolesScope.setId("scope-id");
|
||||
rolesScope.setName("roles");
|
||||
when(clientScopesResource.findAll()).thenReturn(List.of(rolesScope));
|
||||
|
||||
when(clientsResource.get("client-id-123")).thenReturn(clientResource);
|
||||
when(clientResource.getDefaultClientScopes()).thenReturn(List.of(rolesScope));
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("ensureClientAndMapper", Keycloak.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
assertDoesNotThrow(() -> method.invoke(config, adminClient));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testEnsureClientAndMapper_ClientNotFound() throws Exception {
|
||||
when(adminClient.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.realm("lions-user-manager")).thenReturn(realmResource);
|
||||
when(realmResource.clients()).thenReturn(clientsResource);
|
||||
when(clientsResource.findByClientId("lions-user-manager-client")).thenReturn(Collections.emptyList());
|
||||
|
||||
Response response = mock(Response.class);
|
||||
when(response.getStatusInfo()).thenReturn(Response.Status.CREATED);
|
||||
when(response.getLocation()).thenReturn(URI.create("http://localhost/clients/client-id-123"));
|
||||
when(clientsResource.create(any(ClientRepresentation.class))).thenReturn(response);
|
||||
|
||||
when(realmResource.clientScopes()).thenReturn(clientScopesResource);
|
||||
ClientScopeRepresentation rolesScope = new ClientScopeRepresentation();
|
||||
rolesScope.setId("scope-id");
|
||||
rolesScope.setName("roles");
|
||||
when(clientScopesResource.findAll()).thenReturn(List.of(rolesScope));
|
||||
|
||||
when(clientsResource.get("client-id-123")).thenReturn(clientResource);
|
||||
when(clientResource.getDefaultClientScopes()).thenReturn(List.of(rolesScope));
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("ensureClientAndMapper", Keycloak.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
assertDoesNotThrow(() -> method.invoke(config, adminClient));
|
||||
verify(clientsResource).create(any(ClientRepresentation.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testEnsureClientAndMapper_ClientNotFound_NoRolesScope() throws Exception {
|
||||
when(adminClient.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.realm("lions-user-manager")).thenReturn(realmResource);
|
||||
when(realmResource.clients()).thenReturn(clientsResource);
|
||||
when(clientsResource.findByClientId("lions-user-manager-client")).thenReturn(Collections.emptyList());
|
||||
|
||||
Response response = mock(Response.class);
|
||||
when(response.getStatusInfo()).thenReturn(Response.Status.CREATED);
|
||||
when(response.getLocation()).thenReturn(URI.create("http://localhost/clients/client-id-123"));
|
||||
when(clientsResource.create(any(ClientRepresentation.class))).thenReturn(response);
|
||||
|
||||
when(realmResource.clientScopes()).thenReturn(clientScopesResource);
|
||||
when(clientScopesResource.findAll()).thenReturn(Collections.emptyList());
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("ensureClientAndMapper", Keycloak.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
assertDoesNotThrow(() -> method.invoke(config, adminClient));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testEnsureClientAndMapper_ClientNotFound_RolesScopeAlreadyPresent() throws Exception {
|
||||
when(adminClient.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.realm("lions-user-manager")).thenReturn(realmResource);
|
||||
when(realmResource.clients()).thenReturn(clientsResource);
|
||||
when(clientsResource.findByClientId("lions-user-manager-client")).thenReturn(Collections.emptyList());
|
||||
|
||||
Response response = mock(Response.class);
|
||||
when(response.getStatusInfo()).thenReturn(Response.Status.CREATED);
|
||||
when(response.getLocation()).thenReturn(URI.create("http://localhost/clients/client-id-123"));
|
||||
when(clientsResource.create(any(ClientRepresentation.class))).thenReturn(response);
|
||||
|
||||
when(realmResource.clientScopes()).thenReturn(clientScopesResource);
|
||||
ClientScopeRepresentation rolesScope = new ClientScopeRepresentation();
|
||||
rolesScope.setId("scope-id");
|
||||
rolesScope.setName("roles");
|
||||
when(clientScopesResource.findAll()).thenReturn(List.of(rolesScope));
|
||||
|
||||
when(clientsResource.get("client-id-123")).thenReturn(clientResource);
|
||||
// Simuler que le scope "roles" est déjà présent
|
||||
when(clientResource.getDefaultClientScopes()).thenReturn(List.of(rolesScope));
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("ensureClientAndMapper", Keycloak.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
assertDoesNotThrow(() -> method.invoke(config, adminClient));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testEnsureClientAndMapper_Exception() throws Exception {
|
||||
when(adminClient.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.realm("lions-user-manager")).thenReturn(realmResource);
|
||||
when(realmResource.clients()).thenReturn(clientsResource);
|
||||
when(clientsResource.findByClientId("lions-user-manager-client")).thenThrow(new RuntimeException("Connection error"));
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("ensureClientAndMapper", Keycloak.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
assertDoesNotThrow(() -> method.invoke(config, adminClient));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetCreatedId_Success() throws Exception {
|
||||
Response response = mock(Response.class);
|
||||
when(response.getStatusInfo()).thenReturn(Response.Status.CREATED);
|
||||
when(response.getLocation()).thenReturn(URI.create("http://localhost/users/user-id-123"));
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("getCreatedId", Response.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
String id = (String) method.invoke(config, response);
|
||||
assertEquals("user-id-123", id);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetCreatedId_Error() throws Exception {
|
||||
Response response = mock(Response.class);
|
||||
// Utiliser Response.Status.BAD_REQUEST directement
|
||||
when(response.getStatusInfo()).thenReturn(Response.Status.BAD_REQUEST);
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("getCreatedId", Response.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
Exception exception = assertThrows(Exception.class, () -> method.invoke(config, response));
|
||||
assertTrue(exception.getCause() instanceof RuntimeException);
|
||||
assertTrue(exception.getCause().getMessage().contains("Erreur lors de la création"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Couvre L250-252 : le scope "roles" n'est pas encore dans les scopes du client,
|
||||
* donc addDefaultClientScope est appelé.
|
||||
*/
|
||||
@Test
|
||||
void testEnsureClientAndMapper_ClientExists_RolesScopeNotYetPresent() throws Exception {
|
||||
when(adminClient.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.realm("lions-user-manager")).thenReturn(realmResource);
|
||||
when(realmResource.clients()).thenReturn(clientsResource);
|
||||
|
||||
ClientRepresentation existingClient = new ClientRepresentation();
|
||||
existingClient.setId("client-id-456");
|
||||
when(clientsResource.findByClientId("lions-user-manager-client")).thenReturn(List.of(existingClient));
|
||||
|
||||
// Le scope "roles" existe dans le realm
|
||||
when(realmResource.clientScopes()).thenReturn(clientScopesResource);
|
||||
ClientScopeRepresentation rolesScope = new ClientScopeRepresentation();
|
||||
rolesScope.setId("scope-roles-id");
|
||||
rolesScope.setName("roles");
|
||||
when(clientScopesResource.findAll()).thenReturn(List.of(rolesScope));
|
||||
|
||||
// Mais il N'EST PAS encore dans les scopes par défaut du client (liste vide)
|
||||
when(clientsResource.get("client-id-456")).thenReturn(clientResource);
|
||||
when(clientResource.getDefaultClientScopes()).thenReturn(Collections.emptyList());
|
||||
doNothing().when(clientResource).addDefaultClientScope(anyString());
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("ensureClientAndMapper", Keycloak.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
assertDoesNotThrow(() -> method.invoke(config, adminClient));
|
||||
// Vérifie que addDefaultClientScope a été appelé avec l'ID du scope
|
||||
verify(clientResource).addDefaultClientScope("scope-roles-id");
|
||||
}
|
||||
|
||||
/**
|
||||
* Couvre L259-260 : addDefaultClientScope lève une exception → catch warn.
|
||||
*/
|
||||
@Test
|
||||
void testEnsureClientAndMapper_ClientExists_AddScopeThrowsException() throws Exception {
|
||||
when(adminClient.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.realm("lions-user-manager")).thenReturn(realmResource);
|
||||
when(realmResource.clients()).thenReturn(clientsResource);
|
||||
|
||||
ClientRepresentation existingClient = new ClientRepresentation();
|
||||
existingClient.setId("client-id-789");
|
||||
when(clientsResource.findByClientId("lions-user-manager-client")).thenReturn(List.of(existingClient));
|
||||
|
||||
when(realmResource.clientScopes()).thenReturn(clientScopesResource);
|
||||
ClientScopeRepresentation rolesScope = new ClientScopeRepresentation();
|
||||
rolesScope.setId("scope-roles-id-2");
|
||||
rolesScope.setName("roles");
|
||||
when(clientScopesResource.findAll()).thenReturn(List.of(rolesScope));
|
||||
|
||||
// Scope pas encore présent
|
||||
when(clientsResource.get("client-id-789")).thenReturn(clientResource);
|
||||
when(clientResource.getDefaultClientScopes()).thenReturn(Collections.emptyList());
|
||||
// addDefaultClientScope lève une exception → couvre le catch L259-260
|
||||
doThrow(new RuntimeException("Forbidden")).when(clientResource).addDefaultClientScope(anyString());
|
||||
|
||||
Method method = KeycloakTestUserConfig.class.getDeclaredMethod("ensureClientAndMapper", Keycloak.class);
|
||||
method.setAccessible(true);
|
||||
|
||||
// La méthode ne doit pas propager l'exception (catch + warn)
|
||||
assertDoesNotThrow(() -> method.invoke(config, adminClient));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,65 +1,65 @@
|
||||
package dev.lions.user.manager.config;
|
||||
|
||||
import io.quarkus.runtime.StartupEvent;
|
||||
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.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Tests unitaires pour KeycloakTestUserConfig
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class KeycloakTestUserConfigTest {
|
||||
|
||||
@InjectMocks
|
||||
private KeycloakTestUserConfig config;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
// Injecter les propriétés via reflection
|
||||
setField("profile", "dev");
|
||||
setField("keycloakServerUrl", "http://localhost:8180");
|
||||
setField("adminRealm", "master");
|
||||
setField("adminUsername", "admin");
|
||||
setField("adminPassword", "admin");
|
||||
setField("authorizedRealms", "lions-user-manager");
|
||||
}
|
||||
|
||||
private void setField(String fieldName, Object value) throws Exception {
|
||||
Field field = KeycloakTestUserConfig.class.getDeclaredField(fieldName);
|
||||
field.setAccessible(true);
|
||||
field.set(config, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testOnStart_DevMode() {
|
||||
// La méthode onStart est désactivée, elle devrait juste logger et retourner
|
||||
assertDoesNotThrow(() -> {
|
||||
config.onStart(new StartupEvent());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testOnStart_ProdMode() throws Exception {
|
||||
setField("profile", "prod");
|
||||
|
||||
// En prod, la méthode devrait retourner immédiatement
|
||||
assertDoesNotThrow(() -> {
|
||||
config.onStart(new StartupEvent());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testConstants() {
|
||||
// Vérifier que les constantes sont définies
|
||||
assertNotNull(KeycloakTestUserConfig.class);
|
||||
// Les constantes sont privées, on ne peut pas les tester directement
|
||||
// mais on peut vérifier que la classe se charge correctement
|
||||
}
|
||||
}
|
||||
package dev.lions.user.manager.config;
|
||||
|
||||
import io.quarkus.runtime.StartupEvent;
|
||||
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.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Tests unitaires pour KeycloakTestUserConfig
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class KeycloakTestUserConfigTest {
|
||||
|
||||
@InjectMocks
|
||||
private KeycloakTestUserConfig config;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
// Injecter les propriétés via reflection
|
||||
setField("profile", "dev");
|
||||
setField("keycloakServerUrl", "http://localhost:8180");
|
||||
setField("adminRealm", "master");
|
||||
setField("adminUsername", "admin");
|
||||
setField("adminPassword", "admin");
|
||||
setField("authorizedRealms", "lions-user-manager");
|
||||
}
|
||||
|
||||
private void setField(String fieldName, Object value) throws Exception {
|
||||
Field field = KeycloakTestUserConfig.class.getDeclaredField(fieldName);
|
||||
field.setAccessible(true);
|
||||
field.set(config, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testOnStart_DevMode() {
|
||||
// La méthode onStart est désactivée, elle devrait juste logger et retourner
|
||||
assertDoesNotThrow(() -> {
|
||||
config.onStart(new StartupEvent());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testOnStart_ProdMode() throws Exception {
|
||||
setField("profile", "prod");
|
||||
|
||||
// En prod, la méthode devrait retourner immédiatement
|
||||
assertDoesNotThrow(() -> {
|
||||
config.onStart(new StartupEvent());
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testConstants() {
|
||||
// Vérifier que les constantes sont définies
|
||||
assertNotNull(KeycloakTestUserConfig.class);
|
||||
// Les constantes sont privées, on ne peut pas les tester directement
|
||||
// mais on peut vérifier que la classe se charge correctement
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,91 +1,91 @@
|
||||
package dev.lions.user.manager.mapper;
|
||||
|
||||
import dev.lions.user.manager.dto.role.RoleDTO;
|
||||
import dev.lions.user.manager.enums.role.TypeRole;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.keycloak.representations.idm.RoleRepresentation;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Tests supplémentaires pour RoleMapper pour améliorer la couverture
|
||||
*/
|
||||
class RoleMapperAdditionalTest {
|
||||
|
||||
@Test
|
||||
void testToDTO_WithAllFields() {
|
||||
RoleRepresentation roleRep = new RoleRepresentation();
|
||||
roleRep.setId("role-123");
|
||||
roleRep.setName("admin");
|
||||
roleRep.setDescription("Administrator role");
|
||||
roleRep.setComposite(false);
|
||||
|
||||
RoleDTO dto = RoleMapper.toDTO(roleRep, "test-realm", TypeRole.REALM_ROLE);
|
||||
|
||||
assertNotNull(dto);
|
||||
assertEquals("role-123", dto.getId());
|
||||
assertEquals("admin", dto.getName());
|
||||
assertEquals("Administrator role", dto.getDescription());
|
||||
assertEquals(TypeRole.REALM_ROLE, dto.getTypeRole());
|
||||
assertFalse(dto.getComposite());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testToDTO_WithNullFields() {
|
||||
RoleRepresentation roleRep = new RoleRepresentation();
|
||||
roleRep.setId("role-123");
|
||||
roleRep.setName("user");
|
||||
|
||||
RoleDTO dto = RoleMapper.toDTO(roleRep, "test-realm", TypeRole.REALM_ROLE);
|
||||
|
||||
assertNotNull(dto);
|
||||
assertEquals("role-123", dto.getId());
|
||||
assertEquals("user", dto.getName());
|
||||
assertNull(dto.getDescription());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testToDTOList_Empty() {
|
||||
List<RoleDTO> dtos = RoleMapper.toDTOList(Collections.emptyList(), "test-realm", TypeRole.REALM_ROLE);
|
||||
|
||||
assertNotNull(dtos);
|
||||
assertTrue(dtos.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testToDTOList_WithRoles() {
|
||||
RoleRepresentation role1 = new RoleRepresentation();
|
||||
role1.setId("role-1");
|
||||
role1.setName("admin");
|
||||
RoleRepresentation role2 = new RoleRepresentation();
|
||||
role2.setId("role-2");
|
||||
role2.setName("user");
|
||||
|
||||
List<RoleDTO> dtos = RoleMapper.toDTOList(Arrays.asList(role1, role2), "test-realm", TypeRole.REALM_ROLE);
|
||||
|
||||
assertNotNull(dtos);
|
||||
assertEquals(2, dtos.size());
|
||||
assertEquals("admin", dtos.get(0).getName());
|
||||
assertEquals("user", dtos.get(1).getName());
|
||||
}
|
||||
|
||||
// La méthode toKeycloak() n'existe pas dans RoleMapper
|
||||
// Ces tests sont supprimés car la méthode n'est pas disponible
|
||||
|
||||
/**
|
||||
* Couvre RoleMapper.java L13 : le constructeur par défaut implicite de la classe utilitaire.
|
||||
* JaCoCo (counter=LINE) marque la déclaration de classe comme non couverte si aucune instance
|
||||
* n'est jamais créée.
|
||||
*/
|
||||
@Test
|
||||
void testRoleMapperInstantiation() {
|
||||
// Instantie la classe pour couvrir le constructeur par défaut (L13)
|
||||
RoleMapper mapper = new RoleMapper();
|
||||
assertNotNull(mapper);
|
||||
}
|
||||
}
|
||||
|
||||
package dev.lions.user.manager.mapper;
|
||||
|
||||
import dev.lions.user.manager.dto.role.RoleDTO;
|
||||
import dev.lions.user.manager.enums.role.TypeRole;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.keycloak.representations.idm.RoleRepresentation;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* Tests supplémentaires pour RoleMapper pour améliorer la couverture
|
||||
*/
|
||||
class RoleMapperAdditionalTest {
|
||||
|
||||
@Test
|
||||
void testToDTO_WithAllFields() {
|
||||
RoleRepresentation roleRep = new RoleRepresentation();
|
||||
roleRep.setId("role-123");
|
||||
roleRep.setName("admin");
|
||||
roleRep.setDescription("Administrator role");
|
||||
roleRep.setComposite(false);
|
||||
|
||||
RoleDTO dto = RoleMapper.toDTO(roleRep, "test-realm", TypeRole.REALM_ROLE);
|
||||
|
||||
assertNotNull(dto);
|
||||
assertEquals("role-123", dto.getId());
|
||||
assertEquals("admin", dto.getName());
|
||||
assertEquals("Administrator role", dto.getDescription());
|
||||
assertEquals(TypeRole.REALM_ROLE, dto.getTypeRole());
|
||||
assertFalse(dto.getComposite());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testToDTO_WithNullFields() {
|
||||
RoleRepresentation roleRep = new RoleRepresentation();
|
||||
roleRep.setId("role-123");
|
||||
roleRep.setName("user");
|
||||
|
||||
RoleDTO dto = RoleMapper.toDTO(roleRep, "test-realm", TypeRole.REALM_ROLE);
|
||||
|
||||
assertNotNull(dto);
|
||||
assertEquals("role-123", dto.getId());
|
||||
assertEquals("user", dto.getName());
|
||||
assertNull(dto.getDescription());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testToDTOList_Empty() {
|
||||
List<RoleDTO> dtos = RoleMapper.toDTOList(Collections.emptyList(), "test-realm", TypeRole.REALM_ROLE);
|
||||
|
||||
assertNotNull(dtos);
|
||||
assertTrue(dtos.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testToDTOList_WithRoles() {
|
||||
RoleRepresentation role1 = new RoleRepresentation();
|
||||
role1.setId("role-1");
|
||||
role1.setName("admin");
|
||||
RoleRepresentation role2 = new RoleRepresentation();
|
||||
role2.setId("role-2");
|
||||
role2.setName("user");
|
||||
|
||||
List<RoleDTO> dtos = RoleMapper.toDTOList(Arrays.asList(role1, role2), "test-realm", TypeRole.REALM_ROLE);
|
||||
|
||||
assertNotNull(dtos);
|
||||
assertEquals(2, dtos.size());
|
||||
assertEquals("admin", dtos.get(0).getName());
|
||||
assertEquals("user", dtos.get(1).getName());
|
||||
}
|
||||
|
||||
// La méthode toKeycloak() n'existe pas dans RoleMapper
|
||||
// Ces tests sont supprimés car la méthode n'est pas disponible
|
||||
|
||||
/**
|
||||
* Couvre RoleMapper.java L13 : le constructeur par défaut implicite de la classe utilitaire.
|
||||
* JaCoCo (counter=LINE) marque la déclaration de classe comme non couverte si aucune instance
|
||||
* n'est jamais créée.
|
||||
*/
|
||||
@Test
|
||||
void testRoleMapperInstantiation() {
|
||||
// Instantie la classe pour couvrir le constructeur par défaut (L13)
|
||||
RoleMapper mapper = new RoleMapper();
|
||||
assertNotNull(mapper);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,91 +1,91 @@
|
||||
package dev.lions.user.manager.mapper;
|
||||
|
||||
import dev.lions.user.manager.dto.role.RoleDTO;
|
||||
import dev.lions.user.manager.enums.role.TypeRole;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.keycloak.representations.idm.RoleRepresentation;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class RoleMapperTest {
|
||||
|
||||
@Test
|
||||
void testToDTO() {
|
||||
RoleRepresentation rep = new RoleRepresentation();
|
||||
rep.setId("1");
|
||||
rep.setName("role");
|
||||
rep.setDescription("desc");
|
||||
rep.setComposite(true);
|
||||
|
||||
RoleDTO dto = RoleMapper.toDTO(rep, "realm", TypeRole.REALM_ROLE);
|
||||
|
||||
assertNotNull(dto);
|
||||
assertEquals("1", dto.getId());
|
||||
assertEquals("role", dto.getName());
|
||||
assertEquals("desc", dto.getDescription());
|
||||
assertEquals(TypeRole.REALM_ROLE, dto.getTypeRole());
|
||||
assertEquals("realm", dto.getRealmName());
|
||||
assertTrue(dto.getComposite());
|
||||
|
||||
assertNull(RoleMapper.toDTO(null, "realm", TypeRole.REALM_ROLE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testToRepresentation() {
|
||||
RoleDTO dto = RoleDTO.builder()
|
||||
.id("1")
|
||||
.name("role")
|
||||
.description("desc")
|
||||
.composite(true)
|
||||
.compositeRoles(Collections.singletonList("subrole"))
|
||||
.typeRole(TypeRole.CLIENT_ROLE) // Should setClientRole(true)
|
||||
.build();
|
||||
|
||||
RoleRepresentation rep = RoleMapper.toRepresentation(dto);
|
||||
|
||||
assertNotNull(rep);
|
||||
assertEquals("1", rep.getId());
|
||||
assertEquals("role", rep.getName());
|
||||
assertEquals("desc", rep.getDescription());
|
||||
assertTrue(rep.isComposite());
|
||||
assertTrue(rep.getClientRole());
|
||||
|
||||
assertNull(RoleMapper.toRepresentation(null));
|
||||
}
|
||||
|
||||
// New test case to cover full branch logic
|
||||
@Test
|
||||
void testToRepresentationRealmRole() {
|
||||
RoleDTO dto = RoleDTO.builder()
|
||||
.typeRole(TypeRole.REALM_ROLE)
|
||||
.build();
|
||||
RoleRepresentation rep = RoleMapper.toRepresentation(dto);
|
||||
assertFalse(rep.getClientRole());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testToDTOList() {
|
||||
RoleRepresentation rep = new RoleRepresentation();
|
||||
rep.setName("role");
|
||||
List<RoleRepresentation> reps = Collections.singletonList(rep);
|
||||
|
||||
List<RoleDTO> dtos = RoleMapper.toDTOList(reps, "realm", TypeRole.REALM_ROLE);
|
||||
assertEquals(1, dtos.size());
|
||||
assertEquals("role", dtos.get(0).getName());
|
||||
|
||||
assertTrue(RoleMapper.toDTOList(null, "realm", TypeRole.REALM_ROLE).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testToRepresentationList() {
|
||||
RoleDTO dto = RoleDTO.builder().name("role").typeRole(TypeRole.REALM_ROLE).build();
|
||||
List<RoleDTO> dtos = Collections.singletonList(dto);
|
||||
|
||||
List<RoleRepresentation> reps = RoleMapper.toRepresentationList(dtos);
|
||||
assertEquals(1, reps.size());
|
||||
assertEquals("role", reps.get(0).getName());
|
||||
|
||||
assertTrue(RoleMapper.toRepresentationList(null).isEmpty());
|
||||
}
|
||||
}
|
||||
package dev.lions.user.manager.mapper;
|
||||
|
||||
import dev.lions.user.manager.dto.role.RoleDTO;
|
||||
import dev.lions.user.manager.enums.role.TypeRole;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.keycloak.representations.idm.RoleRepresentation;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class RoleMapperTest {
|
||||
|
||||
@Test
|
||||
void testToDTO() {
|
||||
RoleRepresentation rep = new RoleRepresentation();
|
||||
rep.setId("1");
|
||||
rep.setName("role");
|
||||
rep.setDescription("desc");
|
||||
rep.setComposite(true);
|
||||
|
||||
RoleDTO dto = RoleMapper.toDTO(rep, "realm", TypeRole.REALM_ROLE);
|
||||
|
||||
assertNotNull(dto);
|
||||
assertEquals("1", dto.getId());
|
||||
assertEquals("role", dto.getName());
|
||||
assertEquals("desc", dto.getDescription());
|
||||
assertEquals(TypeRole.REALM_ROLE, dto.getTypeRole());
|
||||
assertEquals("realm", dto.getRealmName());
|
||||
assertTrue(dto.getComposite());
|
||||
|
||||
assertNull(RoleMapper.toDTO(null, "realm", TypeRole.REALM_ROLE));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testToRepresentation() {
|
||||
RoleDTO dto = RoleDTO.builder()
|
||||
.id("1")
|
||||
.name("role")
|
||||
.description("desc")
|
||||
.composite(true)
|
||||
.compositeRoles(Collections.singletonList("subrole"))
|
||||
.typeRole(TypeRole.CLIENT_ROLE) // Should setClientRole(true)
|
||||
.build();
|
||||
|
||||
RoleRepresentation rep = RoleMapper.toRepresentation(dto);
|
||||
|
||||
assertNotNull(rep);
|
||||
assertEquals("1", rep.getId());
|
||||
assertEquals("role", rep.getName());
|
||||
assertEquals("desc", rep.getDescription());
|
||||
assertTrue(rep.isComposite());
|
||||
assertTrue(rep.getClientRole());
|
||||
|
||||
assertNull(RoleMapper.toRepresentation(null));
|
||||
}
|
||||
|
||||
// New test case to cover full branch logic
|
||||
@Test
|
||||
void testToRepresentationRealmRole() {
|
||||
RoleDTO dto = RoleDTO.builder()
|
||||
.typeRole(TypeRole.REALM_ROLE)
|
||||
.build();
|
||||
RoleRepresentation rep = RoleMapper.toRepresentation(dto);
|
||||
assertFalse(rep.getClientRole());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testToDTOList() {
|
||||
RoleRepresentation rep = new RoleRepresentation();
|
||||
rep.setName("role");
|
||||
List<RoleRepresentation> reps = Collections.singletonList(rep);
|
||||
|
||||
List<RoleDTO> dtos = RoleMapper.toDTOList(reps, "realm", TypeRole.REALM_ROLE);
|
||||
assertEquals(1, dtos.size());
|
||||
assertEquals("role", dtos.get(0).getName());
|
||||
|
||||
assertTrue(RoleMapper.toDTOList(null, "realm", TypeRole.REALM_ROLE).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testToRepresentationList() {
|
||||
RoleDTO dto = RoleDTO.builder().name("role").typeRole(TypeRole.REALM_ROLE).build();
|
||||
List<RoleDTO> dtos = Collections.singletonList(dto);
|
||||
|
||||
List<RoleRepresentation> reps = RoleMapper.toRepresentationList(dtos);
|
||||
assertEquals(1, reps.size());
|
||||
assertEquals("role", reps.get(0).getName());
|
||||
|
||||
assertTrue(RoleMapper.toRepresentationList(null).isEmpty());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,150 +1,150 @@
|
||||
package dev.lions.user.manager.mapper;
|
||||
|
||||
import dev.lions.user.manager.dto.user.UserDTO;
|
||||
import dev.lions.user.manager.enums.user.StatutUser;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.keycloak.representations.idm.UserRepresentation;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class UserMapperTest {
|
||||
|
||||
@Test
|
||||
void testToDTO() {
|
||||
UserRepresentation rep = new UserRepresentation();
|
||||
rep.setId("1");
|
||||
rep.setUsername("jdoe");
|
||||
rep.setEmail("jdoe@example.com");
|
||||
rep.setEmailVerified(true);
|
||||
rep.setFirstName("John");
|
||||
rep.setLastName("Doe");
|
||||
rep.setEnabled(true);
|
||||
rep.setCreatedTimestamp(System.currentTimeMillis());
|
||||
|
||||
Map<String, List<String>> attrs = Map.of(
|
||||
"phone_number", List.of("123"),
|
||||
"organization", List.of("Lions"),
|
||||
"department", List.of("IT"),
|
||||
"job_title", List.of("Dev"),
|
||||
"country", List.of("CI"),
|
||||
"city", List.of("Abidjan"),
|
||||
"locale", List.of("fr"),
|
||||
"timezone", List.of("UTC"));
|
||||
rep.setAttributes(attrs);
|
||||
|
||||
UserDTO dto = UserMapper.toDTO(rep, "realm");
|
||||
|
||||
assertNotNull(dto);
|
||||
assertEquals("1", dto.getId());
|
||||
assertEquals("jdoe", dto.getUsername());
|
||||
assertEquals("jdoe@example.com", dto.getEmail());
|
||||
assertTrue(dto.getEmailVerified());
|
||||
assertEquals("John", dto.getPrenom());
|
||||
assertEquals("Doe", dto.getNom());
|
||||
assertEquals(StatutUser.ACTIF, dto.getStatut());
|
||||
assertEquals("realm", dto.getRealmName());
|
||||
assertEquals("123", dto.getTelephone());
|
||||
assertEquals("Lions", dto.getOrganisation());
|
||||
assertEquals("IT", dto.getDepartement());
|
||||
assertEquals("Dev", dto.getFonction());
|
||||
assertEquals("CI", dto.getPays());
|
||||
assertEquals("Abidjan", dto.getVille());
|
||||
assertEquals("fr", dto.getLangue());
|
||||
assertEquals("UTC", dto.getTimezone());
|
||||
assertNotNull(dto.getDateCreation());
|
||||
|
||||
assertNull(UserMapper.toDTO(null, "realm"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testToDTOWithNullAttributes() {
|
||||
UserRepresentation rep = new UserRepresentation();
|
||||
rep.setId("1");
|
||||
rep.setEnabled(true);
|
||||
UserDTO dto = UserMapper.toDTO(rep, "realm");
|
||||
assertNotNull(dto);
|
||||
assertNull(dto.getTelephone()); // Attribute missing
|
||||
}
|
||||
|
||||
@Test
|
||||
void testToDTOWithEmptyAttributes() {
|
||||
UserRepresentation rep = new UserRepresentation();
|
||||
rep.setEnabled(true);
|
||||
rep.setAttributes(Collections.emptyMap());
|
||||
UserDTO dto = UserMapper.toDTO(rep, "realm");
|
||||
assertNotNull(dto);
|
||||
assertNull(dto.getTelephone());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testToRepresentation() {
|
||||
UserDTO dto = UserDTO.builder()
|
||||
.id("1")
|
||||
.username("jdoe")
|
||||
.email("jdoe@example.com")
|
||||
.emailVerified(true)
|
||||
.prenom("John")
|
||||
.nom("Doe")
|
||||
.enabled(true)
|
||||
.telephone("123")
|
||||
.organisation("Lions")
|
||||
.departement("IT")
|
||||
.fonction("Dev")
|
||||
.pays("CI")
|
||||
.ville("Abidjan")
|
||||
.langue("fr")
|
||||
.timezone("UTC")
|
||||
.requiredActions(Collections.singletonList("UPDATE_PASSWORD"))
|
||||
.attributes(Map.of("custom", List.of("value")))
|
||||
.build();
|
||||
|
||||
UserRepresentation rep = UserMapper.toRepresentation(dto);
|
||||
|
||||
assertNotNull(rep);
|
||||
assertEquals("1", rep.getId());
|
||||
assertEquals("jdoe", rep.getUsername());
|
||||
assertEquals("jdoe@example.com", rep.getEmail());
|
||||
assertTrue(rep.isEmailVerified());
|
||||
assertEquals("John", rep.getFirstName());
|
||||
assertEquals("Doe", rep.getLastName());
|
||||
assertTrue(rep.isEnabled());
|
||||
|
||||
assertNotNull(rep.getAttributes());
|
||||
assertEquals(List.of("123"), rep.getAttributes().get("phone_number"));
|
||||
assertEquals(List.of("Lions"), rep.getAttributes().get("organization"));
|
||||
assertEquals(List.of("value"), rep.getAttributes().get("custom"));
|
||||
|
||||
assertNotNull(rep.getRequiredActions());
|
||||
assertTrue(rep.getRequiredActions().contains("UPDATE_PASSWORD"));
|
||||
|
||||
assertNull(UserMapper.toRepresentation(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testToRepresentationValuesNull() {
|
||||
UserDTO dto = UserDTO.builder().username("jdoe").enabled(null).build();
|
||||
UserRepresentation rep = UserMapper.toRepresentation(dto);
|
||||
assertTrue(rep.isEnabled()); // Defaults to true in mapper
|
||||
}
|
||||
|
||||
@Test
|
||||
void testToDTOList() {
|
||||
UserRepresentation rep = new UserRepresentation();
|
||||
rep.setEnabled(true);
|
||||
List<UserRepresentation> reps = Collections.singletonList(rep);
|
||||
List<UserDTO> dtos = UserMapper.toDTOList(reps, "realm");
|
||||
assertEquals(1, dtos.size());
|
||||
|
||||
assertTrue(UserMapper.toDTOList(null, "realm").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPrivateConstructor() throws Exception {
|
||||
java.lang.reflect.Constructor<UserMapper> constructor = UserMapper.class.getDeclaredConstructor();
|
||||
assertTrue(java.lang.reflect.Modifier.isPrivate(constructor.getModifiers()));
|
||||
constructor.setAccessible(true);
|
||||
assertNotNull(constructor.newInstance());
|
||||
}
|
||||
}
|
||||
package dev.lions.user.manager.mapper;
|
||||
|
||||
import dev.lions.user.manager.dto.user.UserDTO;
|
||||
import dev.lions.user.manager.enums.user.StatutUser;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.keycloak.representations.idm.UserRepresentation;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class UserMapperTest {
|
||||
|
||||
@Test
|
||||
void testToDTO() {
|
||||
UserRepresentation rep = new UserRepresentation();
|
||||
rep.setId("1");
|
||||
rep.setUsername("jdoe");
|
||||
rep.setEmail("jdoe@example.com");
|
||||
rep.setEmailVerified(true);
|
||||
rep.setFirstName("John");
|
||||
rep.setLastName("Doe");
|
||||
rep.setEnabled(true);
|
||||
rep.setCreatedTimestamp(System.currentTimeMillis());
|
||||
|
||||
Map<String, List<String>> attrs = Map.of(
|
||||
"phone_number", List.of("123"),
|
||||
"organization", List.of("Lions"),
|
||||
"department", List.of("IT"),
|
||||
"job_title", List.of("Dev"),
|
||||
"country", List.of("CI"),
|
||||
"city", List.of("Abidjan"),
|
||||
"locale", List.of("fr"),
|
||||
"timezone", List.of("UTC"));
|
||||
rep.setAttributes(attrs);
|
||||
|
||||
UserDTO dto = UserMapper.toDTO(rep, "realm");
|
||||
|
||||
assertNotNull(dto);
|
||||
assertEquals("1", dto.getId());
|
||||
assertEquals("jdoe", dto.getUsername());
|
||||
assertEquals("jdoe@example.com", dto.getEmail());
|
||||
assertTrue(dto.getEmailVerified());
|
||||
assertEquals("John", dto.getPrenom());
|
||||
assertEquals("Doe", dto.getNom());
|
||||
assertEquals(StatutUser.ACTIF, dto.getStatut());
|
||||
assertEquals("realm", dto.getRealmName());
|
||||
assertEquals("123", dto.getTelephone());
|
||||
assertEquals("Lions", dto.getOrganisation());
|
||||
assertEquals("IT", dto.getDepartement());
|
||||
assertEquals("Dev", dto.getFonction());
|
||||
assertEquals("CI", dto.getPays());
|
||||
assertEquals("Abidjan", dto.getVille());
|
||||
assertEquals("fr", dto.getLangue());
|
||||
assertEquals("UTC", dto.getTimezone());
|
||||
assertNotNull(dto.getDateCreation());
|
||||
|
||||
assertNull(UserMapper.toDTO(null, "realm"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testToDTOWithNullAttributes() {
|
||||
UserRepresentation rep = new UserRepresentation();
|
||||
rep.setId("1");
|
||||
rep.setEnabled(true);
|
||||
UserDTO dto = UserMapper.toDTO(rep, "realm");
|
||||
assertNotNull(dto);
|
||||
assertNull(dto.getTelephone()); // Attribute missing
|
||||
}
|
||||
|
||||
@Test
|
||||
void testToDTOWithEmptyAttributes() {
|
||||
UserRepresentation rep = new UserRepresentation();
|
||||
rep.setEnabled(true);
|
||||
rep.setAttributes(Collections.emptyMap());
|
||||
UserDTO dto = UserMapper.toDTO(rep, "realm");
|
||||
assertNotNull(dto);
|
||||
assertNull(dto.getTelephone());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testToRepresentation() {
|
||||
UserDTO dto = UserDTO.builder()
|
||||
.id("1")
|
||||
.username("jdoe")
|
||||
.email("jdoe@example.com")
|
||||
.emailVerified(true)
|
||||
.prenom("John")
|
||||
.nom("Doe")
|
||||
.enabled(true)
|
||||
.telephone("123")
|
||||
.organisation("Lions")
|
||||
.departement("IT")
|
||||
.fonction("Dev")
|
||||
.pays("CI")
|
||||
.ville("Abidjan")
|
||||
.langue("fr")
|
||||
.timezone("UTC")
|
||||
.requiredActions(Collections.singletonList("UPDATE_PASSWORD"))
|
||||
.attributes(Map.of("custom", List.of("value")))
|
||||
.build();
|
||||
|
||||
UserRepresentation rep = UserMapper.toRepresentation(dto);
|
||||
|
||||
assertNotNull(rep);
|
||||
assertEquals("1", rep.getId());
|
||||
assertEquals("jdoe", rep.getUsername());
|
||||
assertEquals("jdoe@example.com", rep.getEmail());
|
||||
assertTrue(rep.isEmailVerified());
|
||||
assertEquals("John", rep.getFirstName());
|
||||
assertEquals("Doe", rep.getLastName());
|
||||
assertTrue(rep.isEnabled());
|
||||
|
||||
assertNotNull(rep.getAttributes());
|
||||
assertEquals(List.of("123"), rep.getAttributes().get("phone_number"));
|
||||
assertEquals(List.of("Lions"), rep.getAttributes().get("organization"));
|
||||
assertEquals(List.of("value"), rep.getAttributes().get("custom"));
|
||||
|
||||
assertNotNull(rep.getRequiredActions());
|
||||
assertTrue(rep.getRequiredActions().contains("UPDATE_PASSWORD"));
|
||||
|
||||
assertNull(UserMapper.toRepresentation(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testToRepresentationValuesNull() {
|
||||
UserDTO dto = UserDTO.builder().username("jdoe").enabled(null).build();
|
||||
UserRepresentation rep = UserMapper.toRepresentation(dto);
|
||||
assertTrue(rep.isEnabled()); // Defaults to true in mapper
|
||||
}
|
||||
|
||||
@Test
|
||||
void testToDTOList() {
|
||||
UserRepresentation rep = new UserRepresentation();
|
||||
rep.setEnabled(true);
|
||||
List<UserRepresentation> reps = Collections.singletonList(rep);
|
||||
List<UserDTO> dtos = UserMapper.toDTOList(reps, "realm");
|
||||
assertEquals(1, dtos.size());
|
||||
|
||||
assertTrue(UserMapper.toDTOList(null, "realm").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPrivateConstructor() throws Exception {
|
||||
java.lang.reflect.Constructor<UserMapper> constructor = UserMapper.class.getDeclaredConstructor();
|
||||
assertTrue(java.lang.reflect.Modifier.isPrivate(constructor.getModifiers()));
|
||||
constructor.setAccessible(true);
|
||||
assertNotNull(constructor.newInstance());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,233 +1,233 @@
|
||||
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;
|
||||
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.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AuditResourceTest {
|
||||
|
||||
@Mock
|
||||
AuditService auditService;
|
||||
|
||||
@InjectMocks
|
||||
AuditResource auditResource;
|
||||
|
||||
@org.junit.jupiter.api.BeforeEach
|
||||
void setUp() {
|
||||
auditResource.defaultRealm = "master";
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSearchLogs() {
|
||||
List<AuditLogDTO> logs = Collections.singletonList(
|
||||
AuditLogDTO.builder().acteurUsername("admin").typeAction(TypeActionAudit.USER_CREATE).build());
|
||||
when(auditService.findByActeur(eq("admin"), any(), any(), eq(0), eq(50))).thenReturn(logs);
|
||||
|
||||
List<AuditLogDTO> result = auditResource.searchLogs("admin", null, null, null, null, null, 0, 50);
|
||||
|
||||
assertEquals(logs, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetLogsByActor() {
|
||||
List<AuditLogDTO> logs = Collections.singletonList(
|
||||
AuditLogDTO.builder().acteurUsername("admin").build());
|
||||
when(auditService.findByActeur(eq("admin"), isNull(), isNull(), eq(0), eq(100))).thenReturn(logs);
|
||||
|
||||
List<AuditLogDTO> result = auditResource.getLogsByActor("admin", 100);
|
||||
|
||||
assertEquals(logs, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetLogsByResource() {
|
||||
List<AuditLogDTO> logs = Collections.emptyList();
|
||||
when(auditService.findByRessource(eq("USER"), eq("1"), any(), any(), eq(0), eq(100)))
|
||||
.thenReturn(logs);
|
||||
|
||||
List<AuditLogDTO> result = auditResource.getLogsByResource("USER", "1", 100);
|
||||
|
||||
assertEquals(logs, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetLogsByAction() {
|
||||
List<AuditLogDTO> logs = Collections.emptyList();
|
||||
when(auditService.findByTypeAction(eq(TypeActionAudit.USER_CREATE), eq("master"), any(), any(), eq(0), eq(100)))
|
||||
.thenReturn(logs);
|
||||
|
||||
List<AuditLogDTO> result = auditResource.getLogsByAction(TypeActionAudit.USER_CREATE, null, null, 100);
|
||||
|
||||
assertEquals(logs, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetActionStatistics() {
|
||||
Map<TypeActionAudit, Long> stats = Map.of(TypeActionAudit.USER_CREATE, 10L);
|
||||
when(auditService.countByActionType(eq("master"), any(), any())).thenReturn(stats);
|
||||
|
||||
Map<TypeActionAudit, Long> result = auditResource.getActionStatistics(null, null);
|
||||
|
||||
assertEquals(stats, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetUserActivityStatistics() {
|
||||
Map<String, Long> stats = Map.of("admin", 100L);
|
||||
when(auditService.countByActeur(eq("master"), any(), any())).thenReturn(stats);
|
||||
|
||||
Map<String, Long> result = auditResource.getUserActivityStatistics(null, null);
|
||||
|
||||
assertEquals(stats, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetFailureCount() {
|
||||
Map<String, Long> successVsFailure = Map.of("failure", 5L, "success", 100L);
|
||||
when(auditService.countSuccessVsFailure(eq("master"), any(), any())).thenReturn(successVsFailure);
|
||||
|
||||
CountDTO result = auditResource.getFailureCount(null, null);
|
||||
|
||||
assertEquals(5L, result.getCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetSuccessCount() {
|
||||
Map<String, Long> successVsFailure = Map.of("failure", 5L, "success", 100L);
|
||||
when(auditService.countSuccessVsFailure(eq("master"), any(), any())).thenReturn(successVsFailure);
|
||||
|
||||
CountDTO result = auditResource.getSuccessCount(null, null);
|
||||
|
||||
assertEquals(100L, result.getCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExportLogsToCSV() {
|
||||
when(auditService.exportToCSV(eq("master"), any(), any())).thenReturn("csv,data");
|
||||
|
||||
Response response = auditResource.exportLogsToCSV(null, null);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals("csv,data", response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPurgeOldLogs() {
|
||||
when(auditService.purgeOldLogs(any())).thenReturn(0L);
|
||||
|
||||
auditResource.purgeOldLogs(90);
|
||||
|
||||
verify(auditService).purgeOldLogs(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSearchLogs_NullActeur_UsesRealm() {
|
||||
List<AuditLogDTO> logs = Collections.singletonList(
|
||||
AuditLogDTO.builder().acteurUsername("admin").typeAction(TypeActionAudit.USER_CREATE).build());
|
||||
when(auditService.findByRealm(eq("master"), any(), any(), eq(0), eq(50))).thenReturn(logs);
|
||||
|
||||
List<AuditLogDTO> result = auditResource.searchLogs(null, null, null, null, null, null, 0, 50);
|
||||
|
||||
assertEquals(logs, result);
|
||||
verify(auditService).findByRealm(eq("master"), any(), any(), eq(0), eq(50));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSearchLogs_BlankActeur_UsesRealm() {
|
||||
List<AuditLogDTO> logs = Collections.emptyList();
|
||||
when(auditService.findByRealm(eq("master"), any(), any(), eq(0), eq(20))).thenReturn(logs);
|
||||
|
||||
List<AuditLogDTO> result = auditResource.searchLogs(" ", null, null, null, null, null, 0, 20);
|
||||
|
||||
assertEquals(logs, result);
|
||||
verify(auditService).findByRealm(eq("master"), any(), any(), eq(0), eq(20));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSearchLogs_WithPostFilter_TypeAction() {
|
||||
AuditLogDTO matchLog = AuditLogDTO.builder()
|
||||
.acteurUsername("admin")
|
||||
.typeAction(TypeActionAudit.USER_CREATE)
|
||||
.build();
|
||||
AuditLogDTO otherLog = AuditLogDTO.builder()
|
||||
.acteurUsername("admin")
|
||||
.typeAction(TypeActionAudit.USER_DELETE)
|
||||
.build();
|
||||
when(auditService.findByActeur(eq("admin"), any(), any(), eq(0), eq(50)))
|
||||
.thenReturn(List.of(matchLog, otherLog));
|
||||
|
||||
List<AuditLogDTO> result = auditResource.searchLogs("admin", null, null,
|
||||
TypeActionAudit.USER_CREATE, null, null, 0, 50);
|
||||
|
||||
assertEquals(1, result.size());
|
||||
assertEquals(TypeActionAudit.USER_CREATE, result.get(0).getTypeAction());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSearchLogs_WithPostFilter_RessourceType() {
|
||||
AuditLogDTO matchLog = AuditLogDTO.builder()
|
||||
.acteurUsername("admin")
|
||||
.typeAction(TypeActionAudit.USER_CREATE)
|
||||
.ressourceType("USER")
|
||||
.build();
|
||||
AuditLogDTO otherLog = AuditLogDTO.builder()
|
||||
.acteurUsername("admin")
|
||||
.typeAction(TypeActionAudit.USER_CREATE)
|
||||
.ressourceType("ROLE")
|
||||
.build();
|
||||
when(auditService.findByActeur(eq("admin"), any(), any(), eq(0), eq(50)))
|
||||
.thenReturn(List.of(matchLog, otherLog));
|
||||
|
||||
List<AuditLogDTO> result = auditResource.searchLogs("admin", null, null,
|
||||
null, "USER", null, 0, 50);
|
||||
|
||||
assertEquals(1, result.size());
|
||||
assertEquals("USER", result.get(0).getRessourceType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSearchLogs_WithPostFilter_Succes() {
|
||||
AuditLogDTO successLog = AuditLogDTO.builder()
|
||||
.acteurUsername("admin")
|
||||
.typeAction(TypeActionAudit.USER_CREATE)
|
||||
.success(true)
|
||||
.build();
|
||||
AuditLogDTO failLog = AuditLogDTO.builder()
|
||||
.acteurUsername("admin")
|
||||
.typeAction(TypeActionAudit.USER_CREATE)
|
||||
.success(false)
|
||||
.build();
|
||||
when(auditService.findByActeur(eq("admin"), any(), any(), eq(0), eq(50)))
|
||||
.thenReturn(List.of(successLog, failLog));
|
||||
|
||||
List<AuditLogDTO> result = auditResource.searchLogs("admin", null, null,
|
||||
null, null, Boolean.TRUE, 0, 50);
|
||||
|
||||
assertEquals(1, result.size());
|
||||
assertTrue(result.get(0).isSuccessful());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExportLogsToCSV_Exception() {
|
||||
when(auditService.exportToCSV(eq("master"), any(), any()))
|
||||
.thenThrow(new RuntimeException("Export failed"));
|
||||
|
||||
assertThrows(RuntimeException.class, () -> auditResource.exportLogsToCSV(null, null));
|
||||
}
|
||||
}
|
||||
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;
|
||||
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.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AuditResourceTest {
|
||||
|
||||
@Mock
|
||||
AuditService auditService;
|
||||
|
||||
@InjectMocks
|
||||
AuditResource auditResource;
|
||||
|
||||
@org.junit.jupiter.api.BeforeEach
|
||||
void setUp() {
|
||||
auditResource.defaultRealm = "master";
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSearchLogs() {
|
||||
List<AuditLogDTO> logs = Collections.singletonList(
|
||||
AuditLogDTO.builder().acteurUsername("admin").typeAction(TypeActionAudit.USER_CREATE).build());
|
||||
when(auditService.findByActeur(eq("admin"), any(), any(), eq(0), eq(50))).thenReturn(logs);
|
||||
|
||||
List<AuditLogDTO> result = auditResource.searchLogs("admin", null, null, null, null, null, 0, 50);
|
||||
|
||||
assertEquals(logs, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetLogsByActor() {
|
||||
List<AuditLogDTO> logs = Collections.singletonList(
|
||||
AuditLogDTO.builder().acteurUsername("admin").build());
|
||||
when(auditService.findByActeur(eq("admin"), isNull(), isNull(), eq(0), eq(100))).thenReturn(logs);
|
||||
|
||||
List<AuditLogDTO> result = auditResource.getLogsByActor("admin", 100);
|
||||
|
||||
assertEquals(logs, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetLogsByResource() {
|
||||
List<AuditLogDTO> logs = Collections.emptyList();
|
||||
when(auditService.findByRessource(eq("USER"), eq("1"), any(), any(), eq(0), eq(100)))
|
||||
.thenReturn(logs);
|
||||
|
||||
List<AuditLogDTO> result = auditResource.getLogsByResource("USER", "1", 100);
|
||||
|
||||
assertEquals(logs, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetLogsByAction() {
|
||||
List<AuditLogDTO> logs = Collections.emptyList();
|
||||
when(auditService.findByTypeAction(eq(TypeActionAudit.USER_CREATE), eq("master"), any(), any(), eq(0), eq(100)))
|
||||
.thenReturn(logs);
|
||||
|
||||
List<AuditLogDTO> result = auditResource.getLogsByAction(TypeActionAudit.USER_CREATE, null, null, 100);
|
||||
|
||||
assertEquals(logs, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetActionStatistics() {
|
||||
Map<TypeActionAudit, Long> stats = Map.of(TypeActionAudit.USER_CREATE, 10L);
|
||||
when(auditService.countByActionType(eq("master"), any(), any())).thenReturn(stats);
|
||||
|
||||
Map<TypeActionAudit, Long> result = auditResource.getActionStatistics(null, null);
|
||||
|
||||
assertEquals(stats, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetUserActivityStatistics() {
|
||||
Map<String, Long> stats = Map.of("admin", 100L);
|
||||
when(auditService.countByActeur(eq("master"), any(), any())).thenReturn(stats);
|
||||
|
||||
Map<String, Long> result = auditResource.getUserActivityStatistics(null, null);
|
||||
|
||||
assertEquals(stats, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetFailureCount() {
|
||||
Map<String, Long> successVsFailure = Map.of("failure", 5L, "success", 100L);
|
||||
when(auditService.countSuccessVsFailure(eq("master"), any(), any())).thenReturn(successVsFailure);
|
||||
|
||||
CountDTO result = auditResource.getFailureCount(null, null);
|
||||
|
||||
assertEquals(5L, result.getCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetSuccessCount() {
|
||||
Map<String, Long> successVsFailure = Map.of("failure", 5L, "success", 100L);
|
||||
when(auditService.countSuccessVsFailure(eq("master"), any(), any())).thenReturn(successVsFailure);
|
||||
|
||||
CountDTO result = auditResource.getSuccessCount(null, null);
|
||||
|
||||
assertEquals(100L, result.getCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExportLogsToCSV() {
|
||||
when(auditService.exportToCSV(eq("master"), any(), any())).thenReturn("csv,data");
|
||||
|
||||
Response response = auditResource.exportLogsToCSV(null, null);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals("csv,data", response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPurgeOldLogs() {
|
||||
when(auditService.purgeOldLogs(any())).thenReturn(0L);
|
||||
|
||||
auditResource.purgeOldLogs(90);
|
||||
|
||||
verify(auditService).purgeOldLogs(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSearchLogs_NullActeur_UsesRealm() {
|
||||
List<AuditLogDTO> logs = Collections.singletonList(
|
||||
AuditLogDTO.builder().acteurUsername("admin").typeAction(TypeActionAudit.USER_CREATE).build());
|
||||
when(auditService.findByRealm(eq("master"), any(), any(), eq(0), eq(50))).thenReturn(logs);
|
||||
|
||||
List<AuditLogDTO> result = auditResource.searchLogs(null, null, null, null, null, null, 0, 50);
|
||||
|
||||
assertEquals(logs, result);
|
||||
verify(auditService).findByRealm(eq("master"), any(), any(), eq(0), eq(50));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSearchLogs_BlankActeur_UsesRealm() {
|
||||
List<AuditLogDTO> logs = Collections.emptyList();
|
||||
when(auditService.findByRealm(eq("master"), any(), any(), eq(0), eq(20))).thenReturn(logs);
|
||||
|
||||
List<AuditLogDTO> result = auditResource.searchLogs(" ", null, null, null, null, null, 0, 20);
|
||||
|
||||
assertEquals(logs, result);
|
||||
verify(auditService).findByRealm(eq("master"), any(), any(), eq(0), eq(20));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSearchLogs_WithPostFilter_TypeAction() {
|
||||
AuditLogDTO matchLog = AuditLogDTO.builder()
|
||||
.acteurUsername("admin")
|
||||
.typeAction(TypeActionAudit.USER_CREATE)
|
||||
.build();
|
||||
AuditLogDTO otherLog = AuditLogDTO.builder()
|
||||
.acteurUsername("admin")
|
||||
.typeAction(TypeActionAudit.USER_DELETE)
|
||||
.build();
|
||||
when(auditService.findByActeur(eq("admin"), any(), any(), eq(0), eq(50)))
|
||||
.thenReturn(List.of(matchLog, otherLog));
|
||||
|
||||
List<AuditLogDTO> result = auditResource.searchLogs("admin", null, null,
|
||||
TypeActionAudit.USER_CREATE, null, null, 0, 50);
|
||||
|
||||
assertEquals(1, result.size());
|
||||
assertEquals(TypeActionAudit.USER_CREATE, result.get(0).getTypeAction());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSearchLogs_WithPostFilter_RessourceType() {
|
||||
AuditLogDTO matchLog = AuditLogDTO.builder()
|
||||
.acteurUsername("admin")
|
||||
.typeAction(TypeActionAudit.USER_CREATE)
|
||||
.ressourceType("USER")
|
||||
.build();
|
||||
AuditLogDTO otherLog = AuditLogDTO.builder()
|
||||
.acteurUsername("admin")
|
||||
.typeAction(TypeActionAudit.USER_CREATE)
|
||||
.ressourceType("ROLE")
|
||||
.build();
|
||||
when(auditService.findByActeur(eq("admin"), any(), any(), eq(0), eq(50)))
|
||||
.thenReturn(List.of(matchLog, otherLog));
|
||||
|
||||
List<AuditLogDTO> result = auditResource.searchLogs("admin", null, null,
|
||||
null, "USER", null, 0, 50);
|
||||
|
||||
assertEquals(1, result.size());
|
||||
assertEquals("USER", result.get(0).getRessourceType());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSearchLogs_WithPostFilter_Succes() {
|
||||
AuditLogDTO successLog = AuditLogDTO.builder()
|
||||
.acteurUsername("admin")
|
||||
.typeAction(TypeActionAudit.USER_CREATE)
|
||||
.success(true)
|
||||
.build();
|
||||
AuditLogDTO failLog = AuditLogDTO.builder()
|
||||
.acteurUsername("admin")
|
||||
.typeAction(TypeActionAudit.USER_CREATE)
|
||||
.success(false)
|
||||
.build();
|
||||
when(auditService.findByActeur(eq("admin"), any(), any(), eq(0), eq(50)))
|
||||
.thenReturn(List.of(successLog, failLog));
|
||||
|
||||
List<AuditLogDTO> result = auditResource.searchLogs("admin", null, null,
|
||||
null, null, Boolean.TRUE, 0, 50);
|
||||
|
||||
assertEquals(1, result.size());
|
||||
assertTrue(result.get(0).isSuccessful());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExportLogsToCSV_Exception() {
|
||||
when(auditService.exportToCSV(eq("master"), any(), any()))
|
||||
.thenThrow(new RuntimeException("Export failed"));
|
||||
|
||||
assertThrows(RuntimeException.class, () -> auditResource.exportLogsToCSV(null, null));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,99 +1,99 @@
|
||||
package dev.lions.user.manager.resource;
|
||||
|
||||
import dev.lions.user.manager.client.KeycloakAdminClient;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.keycloak.admin.client.Keycloak;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class HealthResourceEndpointTest {
|
||||
|
||||
@Mock
|
||||
KeycloakAdminClient keycloakAdminClient;
|
||||
|
||||
@Mock
|
||||
Keycloak keycloak;
|
||||
|
||||
@InjectMocks
|
||||
HealthResourceEndpoint healthResourceEndpoint;
|
||||
|
||||
@Test
|
||||
void testGetKeycloakHealthConnected() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloak);
|
||||
|
||||
Map<String, Object> result = healthResourceEndpoint.getKeycloakHealth();
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals("UP", result.get("status"));
|
||||
assertEquals(true, result.get("connected"));
|
||||
assertNotNull(result.get("timestamp"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetKeycloakHealthDisconnected() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(null);
|
||||
|
||||
Map<String, Object> result = healthResourceEndpoint.getKeycloakHealth();
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals("DOWN", result.get("status"));
|
||||
assertEquals(false, result.get("connected"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetKeycloakHealthError() {
|
||||
when(keycloakAdminClient.getInstance()).thenThrow(new RuntimeException("Connection error"));
|
||||
|
||||
Map<String, Object> result = healthResourceEndpoint.getKeycloakHealth();
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals("ERROR", result.get("status"));
|
||||
assertEquals(false, result.get("connected"));
|
||||
assertEquals("Connection error", result.get("error"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetServiceStatusConnected() {
|
||||
when(keycloakAdminClient.isConnected()).thenReturn(true);
|
||||
|
||||
Map<String, Object> result = healthResourceEndpoint.getServiceStatus();
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals("lions-user-manager-server", result.get("service"));
|
||||
assertEquals("1.0.0", result.get("version"));
|
||||
assertEquals("UP", result.get("status"));
|
||||
assertEquals("CONNECTED", result.get("keycloak"));
|
||||
assertNotNull(result.get("timestamp"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetServiceStatusDisconnected() {
|
||||
when(keycloakAdminClient.isConnected()).thenReturn(false);
|
||||
|
||||
Map<String, Object> result = healthResourceEndpoint.getServiceStatus();
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals("UP", result.get("status"));
|
||||
assertEquals("DISCONNECTED", result.get("keycloak"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetServiceStatusKeycloakError() {
|
||||
when(keycloakAdminClient.isConnected()).thenThrow(new RuntimeException("Error"));
|
||||
|
||||
Map<String, Object> result = healthResourceEndpoint.getServiceStatus();
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals("UP", result.get("status"));
|
||||
assertEquals("ERROR", result.get("keycloak"));
|
||||
assertEquals("Error", result.get("keycloakError"));
|
||||
}
|
||||
}
|
||||
package dev.lions.user.manager.resource;
|
||||
|
||||
import dev.lions.user.manager.client.KeycloakAdminClient;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.keycloak.admin.client.Keycloak;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class HealthResourceEndpointTest {
|
||||
|
||||
@Mock
|
||||
KeycloakAdminClient keycloakAdminClient;
|
||||
|
||||
@Mock
|
||||
Keycloak keycloak;
|
||||
|
||||
@InjectMocks
|
||||
HealthResourceEndpoint healthResourceEndpoint;
|
||||
|
||||
@Test
|
||||
void testGetKeycloakHealthConnected() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloak);
|
||||
|
||||
Map<String, Object> result = healthResourceEndpoint.getKeycloakHealth();
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals("UP", result.get("status"));
|
||||
assertEquals(true, result.get("connected"));
|
||||
assertNotNull(result.get("timestamp"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetKeycloakHealthDisconnected() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(null);
|
||||
|
||||
Map<String, Object> result = healthResourceEndpoint.getKeycloakHealth();
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals("DOWN", result.get("status"));
|
||||
assertEquals(false, result.get("connected"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetKeycloakHealthError() {
|
||||
when(keycloakAdminClient.getInstance()).thenThrow(new RuntimeException("Connection error"));
|
||||
|
||||
Map<String, Object> result = healthResourceEndpoint.getKeycloakHealth();
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals("ERROR", result.get("status"));
|
||||
assertEquals(false, result.get("connected"));
|
||||
assertEquals("Connection error", result.get("error"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetServiceStatusConnected() {
|
||||
when(keycloakAdminClient.isConnected()).thenReturn(true);
|
||||
|
||||
Map<String, Object> result = healthResourceEndpoint.getServiceStatus();
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals("lions-user-manager-server", result.get("service"));
|
||||
assertEquals("1.0.0", result.get("version"));
|
||||
assertEquals("UP", result.get("status"));
|
||||
assertEquals("CONNECTED", result.get("keycloak"));
|
||||
assertNotNull(result.get("timestamp"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetServiceStatusDisconnected() {
|
||||
when(keycloakAdminClient.isConnected()).thenReturn(false);
|
||||
|
||||
Map<String, Object> result = healthResourceEndpoint.getServiceStatus();
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals("UP", result.get("status"));
|
||||
assertEquals("DISCONNECTED", result.get("keycloak"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetServiceStatusKeycloakError() {
|
||||
when(keycloakAdminClient.isConnected()).thenThrow(new RuntimeException("Error"));
|
||||
|
||||
Map<String, Object> result = healthResourceEndpoint.getServiceStatus();
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals("UP", result.get("status"));
|
||||
assertEquals("ERROR", result.get("keycloak"));
|
||||
assertEquals("Error", result.get("keycloakError"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,222 +1,222 @@
|
||||
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;
|
||||
import jakarta.ws.rs.core.SecurityContext;
|
||||
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 java.security.Principal;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* Tests unitaires pour RealmAssignmentResource
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class RealmAssignmentResourceTest {
|
||||
|
||||
@Mock
|
||||
private RealmAuthorizationService realmAuthorizationService;
|
||||
|
||||
@Mock
|
||||
private SecurityContext securityContext;
|
||||
|
||||
@Mock
|
||||
private Principal principal;
|
||||
|
||||
@InjectMocks
|
||||
private RealmAssignmentResource realmAssignmentResource;
|
||||
|
||||
private RealmAssignmentDTO assignment;
|
||||
|
||||
@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();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllAssignments_Success() {
|
||||
List<RealmAssignmentDTO> assignments = Arrays.asList(assignment);
|
||||
when(realmAuthorizationService.getAllAssignments()).thenReturn(assignments);
|
||||
|
||||
List<RealmAssignmentDTO> result = realmAssignmentResource.getAllAssignments();
|
||||
|
||||
assertEquals(1, result.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAssignmentsByUser_Success() {
|
||||
List<RealmAssignmentDTO> assignments = Arrays.asList(assignment);
|
||||
when(realmAuthorizationService.getAssignmentsByUser("user-1")).thenReturn(assignments);
|
||||
|
||||
List<RealmAssignmentDTO> result = realmAssignmentResource.getAssignmentsByUser("user-1");
|
||||
|
||||
assertEquals(1, result.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAssignmentsByRealm_Success() {
|
||||
List<RealmAssignmentDTO> assignments = Arrays.asList(assignment);
|
||||
when(realmAuthorizationService.getAssignmentsByRealm("realm1")).thenReturn(assignments);
|
||||
|
||||
List<RealmAssignmentDTO> result = realmAssignmentResource.getAssignmentsByRealm("realm1");
|
||||
|
||||
assertEquals(1, result.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAssignmentById_Success() {
|
||||
when(realmAuthorizationService.getAssignmentById("assignment-1")).thenReturn(Optional.of(assignment));
|
||||
|
||||
RealmAssignmentDTO result = realmAssignmentResource.getAssignmentById("assignment-1");
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals("assignment-1", result.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAssignmentById_NotFound() {
|
||||
when(realmAuthorizationService.getAssignmentById("non-existent")).thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(RuntimeException.class, () -> realmAssignmentResource.getAssignmentById("non-existent"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCanManageRealm_Success() {
|
||||
when(realmAuthorizationService.canManageRealm("user-1", "realm1")).thenReturn(true);
|
||||
|
||||
RealmAccessCheckDTO result = realmAssignmentResource.canManageRealm("user-1", "realm1");
|
||||
|
||||
assertTrue(result.isCanManage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAuthorizedRealms_Success() {
|
||||
List<String> realms = Arrays.asList("realm1", "realm2");
|
||||
when(realmAuthorizationService.getAuthorizedRealms("user-1")).thenReturn(realms);
|
||||
when(realmAuthorizationService.isSuperAdmin("user-1")).thenReturn(false);
|
||||
|
||||
AuthorizedRealmsDTO result = realmAssignmentResource.getAuthorizedRealms("user-1");
|
||||
|
||||
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(201, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRevokeRealmFromUser_Success() {
|
||||
doNothing().when(realmAuthorizationService).revokeRealmFromUser("user-1", "realm1");
|
||||
|
||||
realmAssignmentResource.revokeRealmFromUser("user-1", "realm1");
|
||||
|
||||
verify(realmAuthorizationService).revokeRealmFromUser("user-1", "realm1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRevokeAllRealmsFromUser_Success() {
|
||||
doNothing().when(realmAuthorizationService).revokeAllRealmsFromUser("user-1");
|
||||
|
||||
realmAssignmentResource.revokeAllRealmsFromUser("user-1");
|
||||
|
||||
verify(realmAuthorizationService).revokeAllRealmsFromUser("user-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeactivateAssignment_Success() {
|
||||
doNothing().when(realmAuthorizationService).deactivateAssignment("assignment-1");
|
||||
|
||||
realmAssignmentResource.deactivateAssignment("assignment-1");
|
||||
|
||||
verify(realmAuthorizationService).deactivateAssignment("assignment-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testActivateAssignment_Success() {
|
||||
doNothing().when(realmAuthorizationService).activateAssignment("assignment-1");
|
||||
|
||||
realmAssignmentResource.activateAssignment("assignment-1");
|
||||
|
||||
verify(realmAuthorizationService).activateAssignment("assignment-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSetSuperAdmin_Success() {
|
||||
doNothing().when(realmAuthorizationService).setSuperAdmin("user-1", true);
|
||||
|
||||
realmAssignmentResource.setSuperAdmin("user-1", true);
|
||||
|
||||
verify(realmAuthorizationService).setSuperAdmin("user-1", true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAssignRealmToUser_NullPrincipal() {
|
||||
when(securityContext.getUserPrincipal()).thenReturn(null);
|
||||
when(realmAuthorizationService.assignRealmToUser(any(RealmAssignmentDTO.class))).thenReturn(assignment);
|
||||
|
||||
Response response = realmAssignmentResource.assignRealmToUser(assignment);
|
||||
|
||||
assertEquals(201, response.getStatus());
|
||||
// assignedBy n'est pas modifié car le principal est null
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAssignRealmToUser_IllegalArgumentException() {
|
||||
when(securityContext.getUserPrincipal()).thenReturn(principal);
|
||||
when(principal.getName()).thenReturn("admin");
|
||||
when(realmAuthorizationService.assignRealmToUser(any(RealmAssignmentDTO.class)))
|
||||
.thenThrow(new IllegalArgumentException("Affectation déjà existante"));
|
||||
|
||||
Response response = realmAssignmentResource.assignRealmToUser(assignment);
|
||||
|
||||
assertEquals(409, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAssignRealmToUser_GenericException() {
|
||||
when(securityContext.getUserPrincipal()).thenReturn(principal);
|
||||
when(principal.getName()).thenReturn("admin");
|
||||
when(realmAuthorizationService.assignRealmToUser(any(RealmAssignmentDTO.class)))
|
||||
.thenThrow(new RuntimeException("Erreur inattendue"));
|
||||
|
||||
assertThrows(RuntimeException.class, () -> realmAssignmentResource.assignRealmToUser(assignment));
|
||||
}
|
||||
}
|
||||
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;
|
||||
import jakarta.ws.rs.core.SecurityContext;
|
||||
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 java.security.Principal;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* Tests unitaires pour RealmAssignmentResource
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class RealmAssignmentResourceTest {
|
||||
|
||||
@Mock
|
||||
private RealmAuthorizationService realmAuthorizationService;
|
||||
|
||||
@Mock
|
||||
private SecurityContext securityContext;
|
||||
|
||||
@Mock
|
||||
private Principal principal;
|
||||
|
||||
@InjectMocks
|
||||
private RealmAssignmentResource realmAssignmentResource;
|
||||
|
||||
private RealmAssignmentDTO assignment;
|
||||
|
||||
@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();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllAssignments_Success() {
|
||||
List<RealmAssignmentDTO> assignments = Arrays.asList(assignment);
|
||||
when(realmAuthorizationService.getAllAssignments()).thenReturn(assignments);
|
||||
|
||||
List<RealmAssignmentDTO> result = realmAssignmentResource.getAllAssignments();
|
||||
|
||||
assertEquals(1, result.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAssignmentsByUser_Success() {
|
||||
List<RealmAssignmentDTO> assignments = Arrays.asList(assignment);
|
||||
when(realmAuthorizationService.getAssignmentsByUser("user-1")).thenReturn(assignments);
|
||||
|
||||
List<RealmAssignmentDTO> result = realmAssignmentResource.getAssignmentsByUser("user-1");
|
||||
|
||||
assertEquals(1, result.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAssignmentsByRealm_Success() {
|
||||
List<RealmAssignmentDTO> assignments = Arrays.asList(assignment);
|
||||
when(realmAuthorizationService.getAssignmentsByRealm("realm1")).thenReturn(assignments);
|
||||
|
||||
List<RealmAssignmentDTO> result = realmAssignmentResource.getAssignmentsByRealm("realm1");
|
||||
|
||||
assertEquals(1, result.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAssignmentById_Success() {
|
||||
when(realmAuthorizationService.getAssignmentById("assignment-1")).thenReturn(Optional.of(assignment));
|
||||
|
||||
RealmAssignmentDTO result = realmAssignmentResource.getAssignmentById("assignment-1");
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals("assignment-1", result.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAssignmentById_NotFound() {
|
||||
when(realmAuthorizationService.getAssignmentById("non-existent")).thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(RuntimeException.class, () -> realmAssignmentResource.getAssignmentById("non-existent"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCanManageRealm_Success() {
|
||||
when(realmAuthorizationService.canManageRealm("user-1", "realm1")).thenReturn(true);
|
||||
|
||||
RealmAccessCheckDTO result = realmAssignmentResource.canManageRealm("user-1", "realm1");
|
||||
|
||||
assertTrue(result.isCanManage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAuthorizedRealms_Success() {
|
||||
List<String> realms = Arrays.asList("realm1", "realm2");
|
||||
when(realmAuthorizationService.getAuthorizedRealms("user-1")).thenReturn(realms);
|
||||
when(realmAuthorizationService.isSuperAdmin("user-1")).thenReturn(false);
|
||||
|
||||
AuthorizedRealmsDTO result = realmAssignmentResource.getAuthorizedRealms("user-1");
|
||||
|
||||
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(201, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRevokeRealmFromUser_Success() {
|
||||
doNothing().when(realmAuthorizationService).revokeRealmFromUser("user-1", "realm1");
|
||||
|
||||
realmAssignmentResource.revokeRealmFromUser("user-1", "realm1");
|
||||
|
||||
verify(realmAuthorizationService).revokeRealmFromUser("user-1", "realm1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRevokeAllRealmsFromUser_Success() {
|
||||
doNothing().when(realmAuthorizationService).revokeAllRealmsFromUser("user-1");
|
||||
|
||||
realmAssignmentResource.revokeAllRealmsFromUser("user-1");
|
||||
|
||||
verify(realmAuthorizationService).revokeAllRealmsFromUser("user-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeactivateAssignment_Success() {
|
||||
doNothing().when(realmAuthorizationService).deactivateAssignment("assignment-1");
|
||||
|
||||
realmAssignmentResource.deactivateAssignment("assignment-1");
|
||||
|
||||
verify(realmAuthorizationService).deactivateAssignment("assignment-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testActivateAssignment_Success() {
|
||||
doNothing().when(realmAuthorizationService).activateAssignment("assignment-1");
|
||||
|
||||
realmAssignmentResource.activateAssignment("assignment-1");
|
||||
|
||||
verify(realmAuthorizationService).activateAssignment("assignment-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSetSuperAdmin_Success() {
|
||||
doNothing().when(realmAuthorizationService).setSuperAdmin("user-1", true);
|
||||
|
||||
realmAssignmentResource.setSuperAdmin("user-1", true);
|
||||
|
||||
verify(realmAuthorizationService).setSuperAdmin("user-1", true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAssignRealmToUser_NullPrincipal() {
|
||||
when(securityContext.getUserPrincipal()).thenReturn(null);
|
||||
when(realmAuthorizationService.assignRealmToUser(any(RealmAssignmentDTO.class))).thenReturn(assignment);
|
||||
|
||||
Response response = realmAssignmentResource.assignRealmToUser(assignment);
|
||||
|
||||
assertEquals(201, response.getStatus());
|
||||
// assignedBy n'est pas modifié car le principal est null
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAssignRealmToUser_IllegalArgumentException() {
|
||||
when(securityContext.getUserPrincipal()).thenReturn(principal);
|
||||
when(principal.getName()).thenReturn("admin");
|
||||
when(realmAuthorizationService.assignRealmToUser(any(RealmAssignmentDTO.class)))
|
||||
.thenThrow(new IllegalArgumentException("Affectation déjà existante"));
|
||||
|
||||
Response response = realmAssignmentResource.assignRealmToUser(assignment);
|
||||
|
||||
assertEquals(409, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAssignRealmToUser_GenericException() {
|
||||
when(securityContext.getUserPrincipal()).thenReturn(principal);
|
||||
when(principal.getName()).thenReturn("admin");
|
||||
when(realmAuthorizationService.assignRealmToUser(any(RealmAssignmentDTO.class)))
|
||||
.thenThrow(new RuntimeException("Erreur inattendue"));
|
||||
|
||||
assertThrows(RuntimeException.class, () -> realmAssignmentResource.assignRealmToUser(assignment));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,88 +1,88 @@
|
||||
package dev.lions.user.manager.resource;
|
||||
|
||||
import dev.lions.user.manager.client.KeycloakAdminClient;
|
||||
import io.quarkus.security.identity.SecurityIdentity;
|
||||
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.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* Tests supplémentaires pour RealmResource pour améliorer la couverture
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class RealmResourceAdditionalTest {
|
||||
|
||||
@Mock
|
||||
private KeycloakAdminClient keycloakAdminClient;
|
||||
|
||||
@Mock
|
||||
private SecurityIdentity securityIdentity;
|
||||
|
||||
@InjectMocks
|
||||
private RealmResource realmResource;
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_Success() {
|
||||
List<String> realms = Arrays.asList("master", "lions-user-manager", "test-realm");
|
||||
when(keycloakAdminClient.getAllRealms()).thenReturn(realms);
|
||||
|
||||
List<String> result = realmResource.getAllRealms();
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(3, result.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_Empty() {
|
||||
when(keycloakAdminClient.getAllRealms()).thenReturn(List.of());
|
||||
|
||||
List<String> result = realmResource.getAllRealms();
|
||||
|
||||
assertNotNull(result);
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_Exception() {
|
||||
when(keycloakAdminClient.getAllRealms()).thenThrow(new RuntimeException("Connection error"));
|
||||
|
||||
assertThrows(RuntimeException.class, () -> realmResource.getAllRealms());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRealmClients_Success() {
|
||||
List<String> clients = Arrays.asList("admin-cli", "account", "lions-app");
|
||||
when(keycloakAdminClient.getRealmClients("test-realm")).thenReturn(clients);
|
||||
|
||||
List<String> result = realmResource.getRealmClients("test-realm");
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(3, result.size());
|
||||
assertTrue(result.contains("admin-cli"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRealmClients_Empty() {
|
||||
when(keycloakAdminClient.getRealmClients("test-realm")).thenReturn(List.of());
|
||||
|
||||
List<String> result = realmResource.getRealmClients("test-realm");
|
||||
|
||||
assertNotNull(result);
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRealmClients_Exception() {
|
||||
when(keycloakAdminClient.getRealmClients("bad-realm")).thenThrow(new RuntimeException("Not found"));
|
||||
|
||||
assertThrows(RuntimeException.class, () -> realmResource.getRealmClients("bad-realm"));
|
||||
}
|
||||
}
|
||||
package dev.lions.user.manager.resource;
|
||||
|
||||
import dev.lions.user.manager.client.KeycloakAdminClient;
|
||||
import io.quarkus.security.identity.SecurityIdentity;
|
||||
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.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* Tests supplémentaires pour RealmResource pour améliorer la couverture
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class RealmResourceAdditionalTest {
|
||||
|
||||
@Mock
|
||||
private KeycloakAdminClient keycloakAdminClient;
|
||||
|
||||
@Mock
|
||||
private SecurityIdentity securityIdentity;
|
||||
|
||||
@InjectMocks
|
||||
private RealmResource realmResource;
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_Success() {
|
||||
List<String> realms = Arrays.asList("master", "lions-user-manager", "test-realm");
|
||||
when(keycloakAdminClient.getAllRealms()).thenReturn(realms);
|
||||
|
||||
List<String> result = realmResource.getAllRealms();
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(3, result.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_Empty() {
|
||||
when(keycloakAdminClient.getAllRealms()).thenReturn(List.of());
|
||||
|
||||
List<String> result = realmResource.getAllRealms();
|
||||
|
||||
assertNotNull(result);
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_Exception() {
|
||||
when(keycloakAdminClient.getAllRealms()).thenThrow(new RuntimeException("Connection error"));
|
||||
|
||||
assertThrows(RuntimeException.class, () -> realmResource.getAllRealms());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRealmClients_Success() {
|
||||
List<String> clients = Arrays.asList("admin-cli", "account", "lions-app");
|
||||
when(keycloakAdminClient.getRealmClients("test-realm")).thenReturn(clients);
|
||||
|
||||
List<String> result = realmResource.getRealmClients("test-realm");
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(3, result.size());
|
||||
assertTrue(result.contains("admin-cli"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRealmClients_Empty() {
|
||||
when(keycloakAdminClient.getRealmClients("test-realm")).thenReturn(List.of());
|
||||
|
||||
List<String> result = realmResource.getRealmClients("test-realm");
|
||||
|
||||
assertNotNull(result);
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRealmClients_Exception() {
|
||||
when(keycloakAdminClient.getRealmClients("bad-realm")).thenThrow(new RuntimeException("Not found"));
|
||||
|
||||
assertThrows(RuntimeException.class, () -> realmResource.getRealmClients("bad-realm"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,62 +1,62 @@
|
||||
package dev.lions.user.manager.resource;
|
||||
|
||||
import dev.lions.user.manager.client.KeycloakAdminClient;
|
||||
import io.quarkus.security.identity.SecurityIdentity;
|
||||
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.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* Tests unitaires pour RealmResource
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class RealmResourceTest {
|
||||
|
||||
@Mock
|
||||
private KeycloakAdminClient keycloakAdminClient;
|
||||
|
||||
@Mock
|
||||
private SecurityIdentity securityIdentity;
|
||||
|
||||
@InjectMocks
|
||||
private RealmResource realmResource;
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_Success() {
|
||||
List<String> realms = Arrays.asList("master", "lions-user-manager", "btpxpress");
|
||||
when(keycloakAdminClient.getAllRealms()).thenReturn(realms);
|
||||
|
||||
List<String> result = realmResource.getAllRealms();
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(3, result.size());
|
||||
assertEquals("master", result.get(0));
|
||||
verify(keycloakAdminClient).getAllRealms();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_EmptyList() {
|
||||
when(keycloakAdminClient.getAllRealms()).thenReturn(Collections.emptyList());
|
||||
|
||||
List<String> result = realmResource.getAllRealms();
|
||||
|
||||
assertNotNull(result);
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_Exception() {
|
||||
when(keycloakAdminClient.getAllRealms()).thenThrow(new RuntimeException("Keycloak connection error"));
|
||||
|
||||
assertThrows(RuntimeException.class, () -> realmResource.getAllRealms());
|
||||
}
|
||||
}
|
||||
package dev.lions.user.manager.resource;
|
||||
|
||||
import dev.lions.user.manager.client.KeycloakAdminClient;
|
||||
import io.quarkus.security.identity.SecurityIdentity;
|
||||
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.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* Tests unitaires pour RealmResource
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class RealmResourceTest {
|
||||
|
||||
@Mock
|
||||
private KeycloakAdminClient keycloakAdminClient;
|
||||
|
||||
@Mock
|
||||
private SecurityIdentity securityIdentity;
|
||||
|
||||
@InjectMocks
|
||||
private RealmResource realmResource;
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_Success() {
|
||||
List<String> realms = Arrays.asList("master", "lions-user-manager", "btpxpress");
|
||||
when(keycloakAdminClient.getAllRealms()).thenReturn(realms);
|
||||
|
||||
List<String> result = realmResource.getAllRealms();
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(3, result.size());
|
||||
assertEquals("master", result.get(0));
|
||||
verify(keycloakAdminClient).getAllRealms();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_EmptyList() {
|
||||
when(keycloakAdminClient.getAllRealms()).thenReturn(Collections.emptyList());
|
||||
|
||||
List<String> result = realmResource.getAllRealms();
|
||||
|
||||
assertNotNull(result);
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealms_Exception() {
|
||||
when(keycloakAdminClient.getAllRealms()).thenThrow(new RuntimeException("Keycloak connection error"));
|
||||
|
||||
assertThrows(RuntimeException.class, () -> realmResource.getAllRealms());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,370 +1,370 @@
|
||||
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;
|
||||
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.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class RoleResourceTest {
|
||||
|
||||
@Mock
|
||||
RoleService roleService;
|
||||
|
||||
@InjectMocks
|
||||
RoleResource roleResource;
|
||||
|
||||
private static final String REALM = "test-realm";
|
||||
private static final String CLIENT_ID = "test-client";
|
||||
|
||||
// ============== Realm Role Tests ==============
|
||||
|
||||
@Test
|
||||
void testCreateRealmRole() {
|
||||
RoleDTO input = RoleDTO.builder().name("role").description("desc").build();
|
||||
RoleDTO created = RoleDTO.builder().id("1").name("role").description("desc").build();
|
||||
|
||||
when(roleService.createRealmRole(any(), eq(REALM))).thenReturn(created);
|
||||
|
||||
Response response = roleResource.createRealmRole(input, REALM);
|
||||
|
||||
assertEquals(201, response.getStatus());
|
||||
assertEquals(created, response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateRealmRoleConflict() {
|
||||
RoleDTO input = RoleDTO.builder().name("role").build();
|
||||
|
||||
when(roleService.createRealmRole(any(), eq(REALM)))
|
||||
.thenThrow(new IllegalArgumentException("Role already exists"));
|
||||
|
||||
Response response = roleResource.createRealmRole(input, REALM);
|
||||
|
||||
assertEquals(409, 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));
|
||||
|
||||
RoleDTO result = roleResource.getRealmRole("role", REALM);
|
||||
|
||||
assertEquals(role, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRealmRoleNotFound() {
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(RuntimeException.class, () -> roleResource.getRealmRole("role", REALM));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealmRoles() {
|
||||
List<RoleDTO> roles = Collections.singletonList(RoleDTO.builder().name("role").build());
|
||||
when(roleService.getAllRealmRoles(REALM)).thenReturn(roles);
|
||||
|
||||
List<RoleDTO> result = roleResource.getAllRealmRoles(REALM);
|
||||
|
||||
assertEquals(roles, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateRealmRole() {
|
||||
RoleDTO existingRole = RoleDTO.builder().id("1").name("role").build();
|
||||
RoleDTO input = RoleDTO.builder().description("updated").build();
|
||||
RoleDTO updated = RoleDTO.builder().id("1").name("role").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()))
|
||||
.thenReturn(updated);
|
||||
|
||||
RoleDTO result = roleResource.updateRealmRole("role", input, REALM);
|
||||
|
||||
assertEquals(updated, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteRealmRole() {
|
||||
RoleDTO existingRole = RoleDTO.builder().id("1").name("role").build();
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(Optional.of(existingRole));
|
||||
doNothing().when(roleService).deleteRole(eq("1"), eq(REALM), eq(TypeRole.REALM_ROLE), isNull());
|
||||
|
||||
roleResource.deleteRealmRole("role", REALM);
|
||||
|
||||
verify(roleService).deleteRole(eq("1"), eq(REALM), eq(TypeRole.REALM_ROLE), isNull());
|
||||
}
|
||||
|
||||
// ============== Client Role Tests ==============
|
||||
|
||||
@Test
|
||||
void testCreateClientRole() {
|
||||
RoleDTO input = RoleDTO.builder().name("role").build();
|
||||
RoleDTO created = RoleDTO.builder().id("1").name("role").build();
|
||||
|
||||
when(roleService.createClientRole(any(RoleDTO.class), eq(CLIENT_ID), eq(REALM))).thenReturn(created);
|
||||
|
||||
Response response = roleResource.createClientRole(CLIENT_ID, input, REALM);
|
||||
|
||||
assertEquals(201, response.getStatus());
|
||||
assertEquals(created, response.getEntity());
|
||||
}
|
||||
|
||||
@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));
|
||||
|
||||
RoleDTO result = roleResource.getClientRole(CLIENT_ID, "role", REALM);
|
||||
|
||||
assertEquals(role, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllClientRoles() {
|
||||
List<RoleDTO> roles = Collections.singletonList(RoleDTO.builder().name("role").build());
|
||||
when(roleService.getAllClientRoles(REALM, CLIENT_ID)).thenReturn(roles);
|
||||
|
||||
List<RoleDTO> result = roleResource.getAllClientRoles(CLIENT_ID, REALM);
|
||||
|
||||
assertEquals(roles, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteClientRole() {
|
||||
RoleDTO existingRole = RoleDTO.builder().id("1").name("role").build();
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.CLIENT_ROLE, CLIENT_ID))
|
||||
.thenReturn(Optional.of(existingRole));
|
||||
doNothing().when(roleService).deleteRole(eq("1"), eq(REALM), eq(TypeRole.CLIENT_ROLE), eq(CLIENT_ID));
|
||||
|
||||
roleResource.deleteClientRole(CLIENT_ID, "role", REALM);
|
||||
|
||||
verify(roleService).deleteRole(eq("1"), eq(REALM), eq(TypeRole.CLIENT_ROLE), eq(CLIENT_ID));
|
||||
}
|
||||
|
||||
// ============== Role Assignment Tests ==============
|
||||
|
||||
@Test
|
||||
void testAssignRealmRoles() {
|
||||
doNothing().when(roleService).assignRolesToUser(any(RoleAssignmentDTO.class));
|
||||
|
||||
RoleAssignmentRequestDTO request = RoleAssignmentRequestDTO.builder()
|
||||
.roleNames(Collections.singletonList("role"))
|
||||
.build();
|
||||
|
||||
roleResource.assignRealmRoles("user1", REALM, request);
|
||||
|
||||
verify(roleService).assignRolesToUser(any(RoleAssignmentDTO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRevokeRealmRoles() {
|
||||
doNothing().when(roleService).revokeRolesFromUser(any(RoleAssignmentDTO.class));
|
||||
|
||||
RoleAssignmentRequestDTO request = RoleAssignmentRequestDTO.builder()
|
||||
.roleNames(Collections.singletonList("role"))
|
||||
.build();
|
||||
|
||||
roleResource.revokeRealmRoles("user1", REALM, request);
|
||||
|
||||
verify(roleService).revokeRolesFromUser(any(RoleAssignmentDTO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAssignClientRoles() {
|
||||
doNothing().when(roleService).assignRolesToUser(any(RoleAssignmentDTO.class));
|
||||
|
||||
RoleAssignmentRequestDTO request = RoleAssignmentRequestDTO.builder()
|
||||
.roleNames(Collections.singletonList("role"))
|
||||
.build();
|
||||
|
||||
roleResource.assignClientRoles(CLIENT_ID, "user1", REALM, request);
|
||||
|
||||
verify(roleService).assignRolesToUser(any(RoleAssignmentDTO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetUserRealmRoles() {
|
||||
List<RoleDTO> roles = Collections.singletonList(RoleDTO.builder().name("role").build());
|
||||
when(roleService.getUserRealmRoles("user1", REALM)).thenReturn(roles);
|
||||
|
||||
List<RoleDTO> result = roleResource.getUserRealmRoles("user1", REALM);
|
||||
|
||||
assertEquals(roles, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetUserClientRoles() {
|
||||
List<RoleDTO> roles = Collections.singletonList(RoleDTO.builder().name("role").build());
|
||||
when(roleService.getUserClientRoles("user1", CLIENT_ID, REALM)).thenReturn(roles);
|
||||
|
||||
List<RoleDTO> result = roleResource.getUserClientRoles(CLIENT_ID, "user1", REALM);
|
||||
|
||||
assertEquals(roles, result);
|
||||
}
|
||||
|
||||
// ============== Composite Role Tests ==============
|
||||
|
||||
@Test
|
||||
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),
|
||||
eq(TypeRole.REALM_ROLE), isNull());
|
||||
|
||||
RoleAssignmentRequestDTO request = RoleAssignmentRequestDTO.builder()
|
||||
.roleNames(Collections.singletonList("composite"))
|
||||
.build();
|
||||
|
||||
roleResource.addComposites("role", REALM, request);
|
||||
|
||||
verify(roleService).addCompositeRoles(eq("parent-1"), anyList(), eq(REALM),
|
||||
eq(TypeRole.REALM_ROLE), isNull());
|
||||
}
|
||||
|
||||
@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);
|
||||
|
||||
List<RoleDTO> result = roleResource.getComposites("role", REALM);
|
||||
|
||||
assertEquals(composites, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateRealmRole_GenericException() {
|
||||
RoleDTO input = RoleDTO.builder().name("role").build();
|
||||
when(roleService.createRealmRole(any(), eq(REALM)))
|
||||
.thenThrow(new RuntimeException("Internal error"));
|
||||
|
||||
assertThrows(RuntimeException.class, () -> roleResource.createRealmRole(input, REALM));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateRealmRole_NotFound() {
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
RoleDTO input = RoleDTO.builder().description("updated").build();
|
||||
assertThrows(RuntimeException.class, () -> roleResource.updateRealmRole("role", input, REALM));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteRealmRole_NotFound() {
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(RuntimeException.class, () -> roleResource.deleteRealmRole("role", REALM));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateClientRole_IllegalArgumentException() {
|
||||
RoleDTO input = RoleDTO.builder().name("role").build();
|
||||
when(roleService.createClientRole(any(RoleDTO.class), eq(CLIENT_ID), eq(REALM)))
|
||||
.thenThrow(new IllegalArgumentException("Conflict"));
|
||||
|
||||
Response response = roleResource.createClientRole(CLIENT_ID, input, REALM);
|
||||
|
||||
assertEquals(409, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateClientRole_GenericException() {
|
||||
RoleDTO input = RoleDTO.builder().name("role").build();
|
||||
when(roleService.createClientRole(any(RoleDTO.class), eq(CLIENT_ID), eq(REALM)))
|
||||
.thenThrow(new RuntimeException("Internal error"));
|
||||
|
||||
assertThrows(RuntimeException.class, () -> roleResource.createClientRole(CLIENT_ID, input, REALM));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetClientRole_NotFound() {
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.CLIENT_ROLE, CLIENT_ID))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(RuntimeException.class, () -> roleResource.getClientRole(CLIENT_ID, "role", REALM));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteClientRole_NotFound() {
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.CLIENT_ROLE, CLIENT_ID))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(RuntimeException.class, () -> roleResource.deleteClientRole(CLIENT_ID, "role", REALM));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAddComposites_ParentNotFound() {
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
RoleAssignmentRequestDTO request = RoleAssignmentRequestDTO.builder()
|
||||
.roleNames(Collections.singletonList("composite"))
|
||||
.build();
|
||||
|
||||
assertThrows(RuntimeException.class, () -> roleResource.addComposites("role", REALM, request));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAddComposites_ChildNotFound_FilteredOut() {
|
||||
RoleDTO parentRole = RoleDTO.builder().id("parent-1").name("role").build();
|
||||
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(Optional.of(parentRole));
|
||||
when(roleService.getRoleByName("nonexistent", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(Optional.empty()); // will be filtered out (null id)
|
||||
doNothing().when(roleService).addCompositeRoles(eq("parent-1"), anyList(), eq(REALM),
|
||||
eq(TypeRole.REALM_ROLE), isNull());
|
||||
|
||||
RoleAssignmentRequestDTO request = RoleAssignmentRequestDTO.builder()
|
||||
.roleNames(Collections.singletonList("nonexistent"))
|
||||
.build();
|
||||
|
||||
roleResource.addComposites("role", REALM, request);
|
||||
|
||||
// addCompositeRoles called with empty list (filtered out)
|
||||
verify(roleService).addCompositeRoles(eq("parent-1"), eq(Collections.emptyList()), eq(REALM),
|
||||
eq(TypeRole.REALM_ROLE), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetComposites_RoleNotFound() {
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(RuntimeException.class, () -> roleResource.getComposites("role", REALM));
|
||||
}
|
||||
}
|
||||
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;
|
||||
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.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class RoleResourceTest {
|
||||
|
||||
@Mock
|
||||
RoleService roleService;
|
||||
|
||||
@InjectMocks
|
||||
RoleResource roleResource;
|
||||
|
||||
private static final String REALM = "test-realm";
|
||||
private static final String CLIENT_ID = "test-client";
|
||||
|
||||
// ============== Realm Role Tests ==============
|
||||
|
||||
@Test
|
||||
void testCreateRealmRole() {
|
||||
RoleDTO input = RoleDTO.builder().name("role").description("desc").build();
|
||||
RoleDTO created = RoleDTO.builder().id("1").name("role").description("desc").build();
|
||||
|
||||
when(roleService.createRealmRole(any(), eq(REALM))).thenReturn(created);
|
||||
|
||||
Response response = roleResource.createRealmRole(input, REALM);
|
||||
|
||||
assertEquals(201, response.getStatus());
|
||||
assertEquals(created, response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateRealmRoleConflict() {
|
||||
RoleDTO input = RoleDTO.builder().name("role").build();
|
||||
|
||||
when(roleService.createRealmRole(any(), eq(REALM)))
|
||||
.thenThrow(new IllegalArgumentException("Role already exists"));
|
||||
|
||||
Response response = roleResource.createRealmRole(input, REALM);
|
||||
|
||||
assertEquals(409, 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));
|
||||
|
||||
RoleDTO result = roleResource.getRealmRole("role", REALM);
|
||||
|
||||
assertEquals(role, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetRealmRoleNotFound() {
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(RuntimeException.class, () -> roleResource.getRealmRole("role", REALM));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealmRoles() {
|
||||
List<RoleDTO> roles = Collections.singletonList(RoleDTO.builder().name("role").build());
|
||||
when(roleService.getAllRealmRoles(REALM)).thenReturn(roles);
|
||||
|
||||
List<RoleDTO> result = roleResource.getAllRealmRoles(REALM);
|
||||
|
||||
assertEquals(roles, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateRealmRole() {
|
||||
RoleDTO existingRole = RoleDTO.builder().id("1").name("role").build();
|
||||
RoleDTO input = RoleDTO.builder().description("updated").build();
|
||||
RoleDTO updated = RoleDTO.builder().id("1").name("role").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()))
|
||||
.thenReturn(updated);
|
||||
|
||||
RoleDTO result = roleResource.updateRealmRole("role", input, REALM);
|
||||
|
||||
assertEquals(updated, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteRealmRole() {
|
||||
RoleDTO existingRole = RoleDTO.builder().id("1").name("role").build();
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(Optional.of(existingRole));
|
||||
doNothing().when(roleService).deleteRole(eq("1"), eq(REALM), eq(TypeRole.REALM_ROLE), isNull());
|
||||
|
||||
roleResource.deleteRealmRole("role", REALM);
|
||||
|
||||
verify(roleService).deleteRole(eq("1"), eq(REALM), eq(TypeRole.REALM_ROLE), isNull());
|
||||
}
|
||||
|
||||
// ============== Client Role Tests ==============
|
||||
|
||||
@Test
|
||||
void testCreateClientRole() {
|
||||
RoleDTO input = RoleDTO.builder().name("role").build();
|
||||
RoleDTO created = RoleDTO.builder().id("1").name("role").build();
|
||||
|
||||
when(roleService.createClientRole(any(RoleDTO.class), eq(CLIENT_ID), eq(REALM))).thenReturn(created);
|
||||
|
||||
Response response = roleResource.createClientRole(CLIENT_ID, input, REALM);
|
||||
|
||||
assertEquals(201, response.getStatus());
|
||||
assertEquals(created, response.getEntity());
|
||||
}
|
||||
|
||||
@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));
|
||||
|
||||
RoleDTO result = roleResource.getClientRole(CLIENT_ID, "role", REALM);
|
||||
|
||||
assertEquals(role, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllClientRoles() {
|
||||
List<RoleDTO> roles = Collections.singletonList(RoleDTO.builder().name("role").build());
|
||||
when(roleService.getAllClientRoles(REALM, CLIENT_ID)).thenReturn(roles);
|
||||
|
||||
List<RoleDTO> result = roleResource.getAllClientRoles(CLIENT_ID, REALM);
|
||||
|
||||
assertEquals(roles, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteClientRole() {
|
||||
RoleDTO existingRole = RoleDTO.builder().id("1").name("role").build();
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.CLIENT_ROLE, CLIENT_ID))
|
||||
.thenReturn(Optional.of(existingRole));
|
||||
doNothing().when(roleService).deleteRole(eq("1"), eq(REALM), eq(TypeRole.CLIENT_ROLE), eq(CLIENT_ID));
|
||||
|
||||
roleResource.deleteClientRole(CLIENT_ID, "role", REALM);
|
||||
|
||||
verify(roleService).deleteRole(eq("1"), eq(REALM), eq(TypeRole.CLIENT_ROLE), eq(CLIENT_ID));
|
||||
}
|
||||
|
||||
// ============== Role Assignment Tests ==============
|
||||
|
||||
@Test
|
||||
void testAssignRealmRoles() {
|
||||
doNothing().when(roleService).assignRolesToUser(any(RoleAssignmentDTO.class));
|
||||
|
||||
RoleAssignmentRequestDTO request = RoleAssignmentRequestDTO.builder()
|
||||
.roleNames(Collections.singletonList("role"))
|
||||
.build();
|
||||
|
||||
roleResource.assignRealmRoles("user1", REALM, request);
|
||||
|
||||
verify(roleService).assignRolesToUser(any(RoleAssignmentDTO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRevokeRealmRoles() {
|
||||
doNothing().when(roleService).revokeRolesFromUser(any(RoleAssignmentDTO.class));
|
||||
|
||||
RoleAssignmentRequestDTO request = RoleAssignmentRequestDTO.builder()
|
||||
.roleNames(Collections.singletonList("role"))
|
||||
.build();
|
||||
|
||||
roleResource.revokeRealmRoles("user1", REALM, request);
|
||||
|
||||
verify(roleService).revokeRolesFromUser(any(RoleAssignmentDTO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAssignClientRoles() {
|
||||
doNothing().when(roleService).assignRolesToUser(any(RoleAssignmentDTO.class));
|
||||
|
||||
RoleAssignmentRequestDTO request = RoleAssignmentRequestDTO.builder()
|
||||
.roleNames(Collections.singletonList("role"))
|
||||
.build();
|
||||
|
||||
roleResource.assignClientRoles(CLIENT_ID, "user1", REALM, request);
|
||||
|
||||
verify(roleService).assignRolesToUser(any(RoleAssignmentDTO.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetUserRealmRoles() {
|
||||
List<RoleDTO> roles = Collections.singletonList(RoleDTO.builder().name("role").build());
|
||||
when(roleService.getUserRealmRoles("user1", REALM)).thenReturn(roles);
|
||||
|
||||
List<RoleDTO> result = roleResource.getUserRealmRoles("user1", REALM);
|
||||
|
||||
assertEquals(roles, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetUserClientRoles() {
|
||||
List<RoleDTO> roles = Collections.singletonList(RoleDTO.builder().name("role").build());
|
||||
when(roleService.getUserClientRoles("user1", CLIENT_ID, REALM)).thenReturn(roles);
|
||||
|
||||
List<RoleDTO> result = roleResource.getUserClientRoles(CLIENT_ID, "user1", REALM);
|
||||
|
||||
assertEquals(roles, result);
|
||||
}
|
||||
|
||||
// ============== Composite Role Tests ==============
|
||||
|
||||
@Test
|
||||
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),
|
||||
eq(TypeRole.REALM_ROLE), isNull());
|
||||
|
||||
RoleAssignmentRequestDTO request = RoleAssignmentRequestDTO.builder()
|
||||
.roleNames(Collections.singletonList("composite"))
|
||||
.build();
|
||||
|
||||
roleResource.addComposites("role", REALM, request);
|
||||
|
||||
verify(roleService).addCompositeRoles(eq("parent-1"), anyList(), eq(REALM),
|
||||
eq(TypeRole.REALM_ROLE), isNull());
|
||||
}
|
||||
|
||||
@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);
|
||||
|
||||
List<RoleDTO> result = roleResource.getComposites("role", REALM);
|
||||
|
||||
assertEquals(composites, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateRealmRole_GenericException() {
|
||||
RoleDTO input = RoleDTO.builder().name("role").build();
|
||||
when(roleService.createRealmRole(any(), eq(REALM)))
|
||||
.thenThrow(new RuntimeException("Internal error"));
|
||||
|
||||
assertThrows(RuntimeException.class, () -> roleResource.createRealmRole(input, REALM));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateRealmRole_NotFound() {
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
RoleDTO input = RoleDTO.builder().description("updated").build();
|
||||
assertThrows(RuntimeException.class, () -> roleResource.updateRealmRole("role", input, REALM));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteRealmRole_NotFound() {
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(RuntimeException.class, () -> roleResource.deleteRealmRole("role", REALM));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateClientRole_IllegalArgumentException() {
|
||||
RoleDTO input = RoleDTO.builder().name("role").build();
|
||||
when(roleService.createClientRole(any(RoleDTO.class), eq(CLIENT_ID), eq(REALM)))
|
||||
.thenThrow(new IllegalArgumentException("Conflict"));
|
||||
|
||||
Response response = roleResource.createClientRole(CLIENT_ID, input, REALM);
|
||||
|
||||
assertEquals(409, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateClientRole_GenericException() {
|
||||
RoleDTO input = RoleDTO.builder().name("role").build();
|
||||
when(roleService.createClientRole(any(RoleDTO.class), eq(CLIENT_ID), eq(REALM)))
|
||||
.thenThrow(new RuntimeException("Internal error"));
|
||||
|
||||
assertThrows(RuntimeException.class, () -> roleResource.createClientRole(CLIENT_ID, input, REALM));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetClientRole_NotFound() {
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.CLIENT_ROLE, CLIENT_ID))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(RuntimeException.class, () -> roleResource.getClientRole(CLIENT_ID, "role", REALM));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteClientRole_NotFound() {
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.CLIENT_ROLE, CLIENT_ID))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(RuntimeException.class, () -> roleResource.deleteClientRole(CLIENT_ID, "role", REALM));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAddComposites_ParentNotFound() {
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
RoleAssignmentRequestDTO request = RoleAssignmentRequestDTO.builder()
|
||||
.roleNames(Collections.singletonList("composite"))
|
||||
.build();
|
||||
|
||||
assertThrows(RuntimeException.class, () -> roleResource.addComposites("role", REALM, request));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAddComposites_ChildNotFound_FilteredOut() {
|
||||
RoleDTO parentRole = RoleDTO.builder().id("parent-1").name("role").build();
|
||||
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(Optional.of(parentRole));
|
||||
when(roleService.getRoleByName("nonexistent", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(Optional.empty()); // will be filtered out (null id)
|
||||
doNothing().when(roleService).addCompositeRoles(eq("parent-1"), anyList(), eq(REALM),
|
||||
eq(TypeRole.REALM_ROLE), isNull());
|
||||
|
||||
RoleAssignmentRequestDTO request = RoleAssignmentRequestDTO.builder()
|
||||
.roleNames(Collections.singletonList("nonexistent"))
|
||||
.build();
|
||||
|
||||
roleResource.addComposites("role", REALM, request);
|
||||
|
||||
// addCompositeRoles called with empty list (filtered out)
|
||||
verify(roleService).addCompositeRoles(eq("parent-1"), eq(Collections.emptyList()), eq(REALM),
|
||||
eq(TypeRole.REALM_ROLE), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetComposites_RoleNotFound() {
|
||||
when(roleService.getRoleByName("role", REALM, TypeRole.REALM_ROLE, null))
|
||||
.thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(RuntimeException.class, () -> roleResource.getComposites("role", REALM));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,163 +1,163 @@
|
||||
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.SyncConsistencyDTO;
|
||||
import dev.lions.user.manager.dto.sync.SyncHistoryDTO;
|
||||
import dev.lions.user.manager.dto.sync.SyncResultDTO;
|
||||
import dev.lions.user.manager.service.SyncService;
|
||||
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.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class SyncResourceTest {
|
||||
|
||||
@Mock
|
||||
SyncService syncService;
|
||||
|
||||
@InjectMocks
|
||||
SyncResource syncResource;
|
||||
|
||||
private static final String REALM = "test-realm";
|
||||
|
||||
@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);
|
||||
|
||||
SyncResultDTO result = syncResource.syncUsers(REALM);
|
||||
|
||||
assertTrue(result.isSuccess());
|
||||
assertEquals(10, result.getUsersCount());
|
||||
assertEquals(REALM, result.getRealmName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSyncUsersError() {
|
||||
when(syncService.syncUsersFromRealm(REALM)).thenThrow(new RuntimeException("Sync failed"));
|
||||
|
||||
SyncResultDTO result = syncResource.syncUsers(REALM);
|
||||
|
||||
assertFalse(result.isSuccess());
|
||||
assertEquals("Sync failed", result.getErrorMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSyncRoles() {
|
||||
when(syncService.syncRolesFromRealm(REALM)).thenReturn(5);
|
||||
|
||||
SyncResultDTO result = syncResource.syncRoles(REALM, null);
|
||||
|
||||
assertTrue(result.isSuccess());
|
||||
assertEquals(5, result.getRealmRolesCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSyncRolesError() {
|
||||
when(syncService.syncRolesFromRealm(REALM)).thenThrow(new RuntimeException("Roles sync failed"));
|
||||
|
||||
SyncResultDTO result = syncResource.syncRoles(REALM, null);
|
||||
|
||||
assertFalse(result.isSuccess());
|
||||
assertEquals("Roles sync failed", result.getErrorMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPing() {
|
||||
String response = syncResource.ping();
|
||||
|
||||
assertNotNull(response);
|
||||
assertTrue(response.contains("pong"));
|
||||
assertTrue(response.contains("SyncResource"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCheckDataConsistency_Success() {
|
||||
when(syncService.checkDataConsistency(REALM)).thenReturn(Map.of(
|
||||
"realmName", REALM,
|
||||
"status", "OK",
|
||||
"usersKeycloakCount", 10,
|
||||
"usersLocalCount", 10
|
||||
));
|
||||
|
||||
var result = syncResource.checkDataConsistency(REALM);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(REALM, result.getRealmName());
|
||||
assertEquals("OK", result.getStatus());
|
||||
assertEquals(10, result.getUsersKeycloakCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCheckDataConsistency_Exception() {
|
||||
when(syncService.checkDataConsistency(REALM)).thenThrow(new RuntimeException("DB error"));
|
||||
|
||||
var result = syncResource.checkDataConsistency(REALM);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals("ERROR", result.getStatus());
|
||||
assertEquals(REALM, result.getRealmName());
|
||||
assertEquals("DB error", result.getError());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetLastSyncStatus() {
|
||||
var result = syncResource.getLastSyncStatus(REALM);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(REALM, result.getRealmName());
|
||||
assertEquals("NEVER_SYNCED", result.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testForceSyncRealm_Success() {
|
||||
when(syncService.forceSyncRealm(REALM)).thenReturn(Map.of());
|
||||
|
||||
var result = syncResource.forceSyncRealm(REALM);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals("SUCCESS", result.getStatus());
|
||||
assertEquals(REALM, result.getRealmName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testForceSyncRealm_Exception() {
|
||||
doThrow(new RuntimeException("Force sync failed")).when(syncService).forceSyncRealm(REALM);
|
||||
|
||||
var result = syncResource.forceSyncRealm(REALM);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals("FAILED", result.getStatus());
|
||||
assertEquals(REALM, result.getRealmName());
|
||||
}
|
||||
}
|
||||
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.SyncConsistencyDTO;
|
||||
import dev.lions.user.manager.dto.sync.SyncHistoryDTO;
|
||||
import dev.lions.user.manager.dto.sync.SyncResultDTO;
|
||||
import dev.lions.user.manager.service.SyncService;
|
||||
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.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class SyncResourceTest {
|
||||
|
||||
@Mock
|
||||
SyncService syncService;
|
||||
|
||||
@InjectMocks
|
||||
SyncResource syncResource;
|
||||
|
||||
private static final String REALM = "test-realm";
|
||||
|
||||
@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);
|
||||
|
||||
SyncResultDTO result = syncResource.syncUsers(REALM);
|
||||
|
||||
assertTrue(result.isSuccess());
|
||||
assertEquals(10, result.getUsersCount());
|
||||
assertEquals(REALM, result.getRealmName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSyncUsersError() {
|
||||
when(syncService.syncUsersFromRealm(REALM)).thenThrow(new RuntimeException("Sync failed"));
|
||||
|
||||
SyncResultDTO result = syncResource.syncUsers(REALM);
|
||||
|
||||
assertFalse(result.isSuccess());
|
||||
assertEquals("Sync failed", result.getErrorMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSyncRoles() {
|
||||
when(syncService.syncRolesFromRealm(REALM)).thenReturn(5);
|
||||
|
||||
SyncResultDTO result = syncResource.syncRoles(REALM, null);
|
||||
|
||||
assertTrue(result.isSuccess());
|
||||
assertEquals(5, result.getRealmRolesCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSyncRolesError() {
|
||||
when(syncService.syncRolesFromRealm(REALM)).thenThrow(new RuntimeException("Roles sync failed"));
|
||||
|
||||
SyncResultDTO result = syncResource.syncRoles(REALM, null);
|
||||
|
||||
assertFalse(result.isSuccess());
|
||||
assertEquals("Roles sync failed", result.getErrorMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPing() {
|
||||
String response = syncResource.ping();
|
||||
|
||||
assertNotNull(response);
|
||||
assertTrue(response.contains("pong"));
|
||||
assertTrue(response.contains("SyncResource"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCheckDataConsistency_Success() {
|
||||
when(syncService.checkDataConsistency(REALM)).thenReturn(Map.of(
|
||||
"realmName", REALM,
|
||||
"status", "OK",
|
||||
"usersKeycloakCount", 10,
|
||||
"usersLocalCount", 10
|
||||
));
|
||||
|
||||
var result = syncResource.checkDataConsistency(REALM);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(REALM, result.getRealmName());
|
||||
assertEquals("OK", result.getStatus());
|
||||
assertEquals(10, result.getUsersKeycloakCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCheckDataConsistency_Exception() {
|
||||
when(syncService.checkDataConsistency(REALM)).thenThrow(new RuntimeException("DB error"));
|
||||
|
||||
var result = syncResource.checkDataConsistency(REALM);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals("ERROR", result.getStatus());
|
||||
assertEquals(REALM, result.getRealmName());
|
||||
assertEquals("DB error", result.getError());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetLastSyncStatus() {
|
||||
var result = syncResource.getLastSyncStatus(REALM);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(REALM, result.getRealmName());
|
||||
assertEquals("NEVER_SYNCED", result.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testForceSyncRealm_Success() {
|
||||
when(syncService.forceSyncRealm(REALM)).thenReturn(Map.of());
|
||||
|
||||
var result = syncResource.forceSyncRealm(REALM);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals("SUCCESS", result.getStatus());
|
||||
assertEquals(REALM, result.getRealmName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testForceSyncRealm_Exception() {
|
||||
doThrow(new RuntimeException("Force sync failed")).when(syncService).forceSyncRealm(REALM);
|
||||
|
||||
var result = syncResource.forceSyncRealm(REALM);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals("FAILED", result.getStatus());
|
||||
assertEquals(REALM, result.getRealmName());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,95 +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"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
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,243 +1,243 @@
|
||||
package dev.lions.user.manager.resource;
|
||||
|
||||
import dev.lions.user.manager.dto.importexport.ImportResultDTO;
|
||||
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;
|
||||
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.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class UserResourceTest {
|
||||
|
||||
@Mock
|
||||
UserService userService;
|
||||
|
||||
@InjectMocks
|
||||
UserResource userResource;
|
||||
|
||||
private static final String REALM = "test-realm";
|
||||
|
||||
@Test
|
||||
void testSearchUsers() {
|
||||
UserSearchCriteriaDTO criteria = UserSearchCriteriaDTO.builder()
|
||||
.realmName(REALM)
|
||||
.searchTerm("test")
|
||||
.page(0)
|
||||
.pageSize(20)
|
||||
.build();
|
||||
|
||||
UserSearchResultDTO mockResult = UserSearchResultDTO.builder()
|
||||
.users(Collections.singletonList(UserDTO.builder().username("test").build()))
|
||||
.totalCount(1L)
|
||||
.build();
|
||||
|
||||
when(userService.searchUsers(any())).thenReturn(mockResult);
|
||||
|
||||
UserSearchResultDTO result = userResource.searchUsers(criteria);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.getTotalCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetUserById() {
|
||||
UserDTO user = UserDTO.builder().id("1").username("testuser").build();
|
||||
when(userService.getUserById("1", REALM)).thenReturn(Optional.of(user));
|
||||
|
||||
UserDTO result = userResource.getUserById("1", REALM);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(user, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetUserByIdNotFound() {
|
||||
when(userService.getUserById("1", REALM)).thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(RuntimeException.class, () -> userResource.getUserById("1", REALM));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllUsers() {
|
||||
UserSearchResultDTO mockResult = UserSearchResultDTO.builder()
|
||||
.users(Collections.emptyList())
|
||||
.totalCount(0L)
|
||||
.build();
|
||||
when(userService.getAllUsers(REALM, 0, 20)).thenReturn(mockResult);
|
||||
|
||||
UserSearchResultDTO result = userResource.getAllUsers(REALM, 0, 20);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(0, result.getTotalCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateUser() {
|
||||
UserDTO newUser = UserDTO.builder().username("newuser").email("new@test.com").build();
|
||||
UserDTO createdUser = UserDTO.builder().id("123").username("newuser").email("new@test.com").build();
|
||||
|
||||
when(userService.createUser(any(), eq(REALM))).thenReturn(createdUser);
|
||||
|
||||
Response response = userResource.createUser(newUser, REALM);
|
||||
|
||||
assertEquals(201, response.getStatus());
|
||||
assertEquals(createdUser, response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateUser() {
|
||||
UserDTO updateUser = UserDTO.builder()
|
||||
.username("updated")
|
||||
.prenom("John")
|
||||
.nom("Doe")
|
||||
.email("john.doe@test.com")
|
||||
.build();
|
||||
UserDTO updatedUser = UserDTO.builder()
|
||||
.id("1")
|
||||
.username("updated")
|
||||
.prenom("John")
|
||||
.nom("Doe")
|
||||
.email("john.doe@test.com")
|
||||
.build();
|
||||
|
||||
when(userService.updateUser(eq("1"), any(), eq(REALM))).thenReturn(updatedUser);
|
||||
|
||||
UserDTO result = userResource.updateUser("1", updateUser, REALM);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(updatedUser, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteUser() {
|
||||
doNothing().when(userService).deleteUser("1", REALM, false);
|
||||
|
||||
userResource.deleteUser("1", REALM, false);
|
||||
|
||||
verify(userService).deleteUser("1", REALM, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testActivateUser() {
|
||||
doNothing().when(userService).activateUser("1", REALM);
|
||||
|
||||
userResource.activateUser("1", REALM);
|
||||
|
||||
verify(userService).activateUser("1", REALM);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeactivateUser() {
|
||||
doNothing().when(userService).deactivateUser("1", REALM, "reason");
|
||||
|
||||
userResource.deactivateUser("1", REALM, "reason");
|
||||
|
||||
verify(userService).deactivateUser("1", REALM, "reason");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testResetPassword() {
|
||||
doNothing().when(userService).resetPassword("1", REALM, "newpassword", true);
|
||||
|
||||
PasswordResetRequestDTO request = PasswordResetRequestDTO.builder()
|
||||
.password("newpassword")
|
||||
.temporary(true)
|
||||
.build();
|
||||
|
||||
userResource.resetPassword("1", REALM, request);
|
||||
|
||||
verify(userService).resetPassword("1", REALM, "newpassword", true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSendVerificationEmail() {
|
||||
doNothing().when(userService).sendVerificationEmail("1", REALM);
|
||||
|
||||
Response response = userResource.sendVerificationEmail("1", REALM);
|
||||
|
||||
verify(userService).sendVerificationEmail("1", REALM);
|
||||
assertNotNull(response);
|
||||
assertEquals(202, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testLogoutAllSessions() {
|
||||
when(userService.logoutAllSessions("1", REALM)).thenReturn(5);
|
||||
|
||||
SessionsRevokedDTO result = userResource.logoutAllSessions("1", REALM);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(5, result.getCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetActiveSessions() {
|
||||
when(userService.getActiveSessions("1", REALM)).thenReturn(Collections.singletonList("session-1"));
|
||||
|
||||
List<String> result = userResource.getActiveSessions("1", REALM);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.size());
|
||||
assertEquals("session-1", result.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateUser_IllegalArgumentException() {
|
||||
UserDTO newUser = UserDTO.builder().username("existinguser").email("existing@test.com").build();
|
||||
when(userService.createUser(any(), eq(REALM))).thenThrow(new IllegalArgumentException("Username exists"));
|
||||
|
||||
Response response = userResource.createUser(newUser, REALM);
|
||||
|
||||
assertEquals(409, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateUser_RuntimeException() {
|
||||
UserDTO newUser = UserDTO.builder().username("user").email("user@test.com").build();
|
||||
when(userService.createUser(any(), eq(REALM))).thenThrow(new RuntimeException("Connection error"));
|
||||
|
||||
assertThrows(RuntimeException.class, () -> userResource.createUser(newUser, REALM));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExportUsersToCSV() {
|
||||
String csvContent = "username,email,prenom,nom\ntest,test@test.com,Test,User";
|
||||
when(userService.exportUsersToCSV(any())).thenReturn(csvContent);
|
||||
|
||||
Response response = userResource.exportUsersToCSV(REALM);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals(csvContent, response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testImportUsersFromCSV() {
|
||||
String csvContent = "username,email,prenom,nom\ntest,test@test.com,Test,User";
|
||||
ImportResultDTO importResult = ImportResultDTO.builder()
|
||||
.successCount(1)
|
||||
.errorCount(0)
|
||||
.totalLines(2)
|
||||
.errors(Collections.emptyList())
|
||||
.build();
|
||||
when(userService.importUsersFromCSV(csvContent, REALM)).thenReturn(importResult);
|
||||
|
||||
ImportResultDTO result = userResource.importUsersFromCSV(REALM, csvContent);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.getSuccessCount());
|
||||
assertEquals(0, result.getErrorCount());
|
||||
}
|
||||
}
|
||||
package dev.lions.user.manager.resource;
|
||||
|
||||
import dev.lions.user.manager.dto.importexport.ImportResultDTO;
|
||||
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;
|
||||
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.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class UserResourceTest {
|
||||
|
||||
@Mock
|
||||
UserService userService;
|
||||
|
||||
@InjectMocks
|
||||
UserResource userResource;
|
||||
|
||||
private static final String REALM = "test-realm";
|
||||
|
||||
@Test
|
||||
void testSearchUsers() {
|
||||
UserSearchCriteriaDTO criteria = UserSearchCriteriaDTO.builder()
|
||||
.realmName(REALM)
|
||||
.searchTerm("test")
|
||||
.page(0)
|
||||
.pageSize(20)
|
||||
.build();
|
||||
|
||||
UserSearchResultDTO mockResult = UserSearchResultDTO.builder()
|
||||
.users(Collections.singletonList(UserDTO.builder().username("test").build()))
|
||||
.totalCount(1L)
|
||||
.build();
|
||||
|
||||
when(userService.searchUsers(any())).thenReturn(mockResult);
|
||||
|
||||
UserSearchResultDTO result = userResource.searchUsers(criteria);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.getTotalCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetUserById() {
|
||||
UserDTO user = UserDTO.builder().id("1").username("testuser").build();
|
||||
when(userService.getUserById("1", REALM)).thenReturn(Optional.of(user));
|
||||
|
||||
UserDTO result = userResource.getUserById("1", REALM);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(user, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetUserByIdNotFound() {
|
||||
when(userService.getUserById("1", REALM)).thenReturn(Optional.empty());
|
||||
|
||||
assertThrows(RuntimeException.class, () -> userResource.getUserById("1", REALM));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllUsers() {
|
||||
UserSearchResultDTO mockResult = UserSearchResultDTO.builder()
|
||||
.users(Collections.emptyList())
|
||||
.totalCount(0L)
|
||||
.build();
|
||||
when(userService.getAllUsers(REALM, 0, 20)).thenReturn(mockResult);
|
||||
|
||||
UserSearchResultDTO result = userResource.getAllUsers(REALM, 0, 20);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(0, result.getTotalCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateUser() {
|
||||
UserDTO newUser = UserDTO.builder().username("newuser").email("new@test.com").build();
|
||||
UserDTO createdUser = UserDTO.builder().id("123").username("newuser").email("new@test.com").build();
|
||||
|
||||
when(userService.createUser(any(), eq(REALM))).thenReturn(createdUser);
|
||||
|
||||
Response response = userResource.createUser(newUser, REALM);
|
||||
|
||||
assertEquals(201, response.getStatus());
|
||||
assertEquals(createdUser, response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateUser() {
|
||||
UserDTO updateUser = UserDTO.builder()
|
||||
.username("updated")
|
||||
.prenom("John")
|
||||
.nom("Doe")
|
||||
.email("john.doe@test.com")
|
||||
.build();
|
||||
UserDTO updatedUser = UserDTO.builder()
|
||||
.id("1")
|
||||
.username("updated")
|
||||
.prenom("John")
|
||||
.nom("Doe")
|
||||
.email("john.doe@test.com")
|
||||
.build();
|
||||
|
||||
when(userService.updateUser(eq("1"), any(), eq(REALM))).thenReturn(updatedUser);
|
||||
|
||||
UserDTO result = userResource.updateUser("1", updateUser, REALM);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(updatedUser, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteUser() {
|
||||
doNothing().when(userService).deleteUser("1", REALM, false);
|
||||
|
||||
userResource.deleteUser("1", REALM, false);
|
||||
|
||||
verify(userService).deleteUser("1", REALM, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testActivateUser() {
|
||||
doNothing().when(userService).activateUser("1", REALM);
|
||||
|
||||
userResource.activateUser("1", REALM);
|
||||
|
||||
verify(userService).activateUser("1", REALM);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeactivateUser() {
|
||||
doNothing().when(userService).deactivateUser("1", REALM, "reason");
|
||||
|
||||
userResource.deactivateUser("1", REALM, "reason");
|
||||
|
||||
verify(userService).deactivateUser("1", REALM, "reason");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testResetPassword() {
|
||||
doNothing().when(userService).resetPassword("1", REALM, "newpassword", true);
|
||||
|
||||
PasswordResetRequestDTO request = PasswordResetRequestDTO.builder()
|
||||
.password("newpassword")
|
||||
.temporary(true)
|
||||
.build();
|
||||
|
||||
userResource.resetPassword("1", REALM, request);
|
||||
|
||||
verify(userService).resetPassword("1", REALM, "newpassword", true);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSendVerificationEmail() {
|
||||
doNothing().when(userService).sendVerificationEmail("1", REALM);
|
||||
|
||||
Response response = userResource.sendVerificationEmail("1", REALM);
|
||||
|
||||
verify(userService).sendVerificationEmail("1", REALM);
|
||||
assertNotNull(response);
|
||||
assertEquals(202, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testLogoutAllSessions() {
|
||||
when(userService.logoutAllSessions("1", REALM)).thenReturn(5);
|
||||
|
||||
SessionsRevokedDTO result = userResource.logoutAllSessions("1", REALM);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(5, result.getCount());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetActiveSessions() {
|
||||
when(userService.getActiveSessions("1", REALM)).thenReturn(Collections.singletonList("session-1"));
|
||||
|
||||
List<String> result = userResource.getActiveSessions("1", REALM);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.size());
|
||||
assertEquals("session-1", result.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateUser_IllegalArgumentException() {
|
||||
UserDTO newUser = UserDTO.builder().username("existinguser").email("existing@test.com").build();
|
||||
when(userService.createUser(any(), eq(REALM))).thenThrow(new IllegalArgumentException("Username exists"));
|
||||
|
||||
Response response = userResource.createUser(newUser, REALM);
|
||||
|
||||
assertEquals(409, response.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateUser_RuntimeException() {
|
||||
UserDTO newUser = UserDTO.builder().username("user").email("user@test.com").build();
|
||||
when(userService.createUser(any(), eq(REALM))).thenThrow(new RuntimeException("Connection error"));
|
||||
|
||||
assertThrows(RuntimeException.class, () -> userResource.createUser(newUser, REALM));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testExportUsersToCSV() {
|
||||
String csvContent = "username,email,prenom,nom\ntest,test@test.com,Test,User";
|
||||
when(userService.exportUsersToCSV(any())).thenReturn(csvContent);
|
||||
|
||||
Response response = userResource.exportUsersToCSV(REALM);
|
||||
|
||||
assertEquals(200, response.getStatus());
|
||||
assertEquals(csvContent, response.getEntity());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testImportUsersFromCSV() {
|
||||
String csvContent = "username,email,prenom,nom\ntest,test@test.com,Test,User";
|
||||
ImportResultDTO importResult = ImportResultDTO.builder()
|
||||
.successCount(1)
|
||||
.errorCount(0)
|
||||
.totalLines(2)
|
||||
.errors(Collections.emptyList())
|
||||
.build();
|
||||
when(userService.importUsersFromCSV(csvContent, REALM)).thenReturn(importResult);
|
||||
|
||||
ImportResultDTO result = userResource.importUsersFromCSV(REALM, csvContent);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.getSuccessCount());
|
||||
assertEquals(0, result.getErrorCount());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,178 +1,178 @@
|
||||
package dev.lions.user.manager.security;
|
||||
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.SecurityContext;
|
||||
import jakarta.ws.rs.core.UriInfo;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* Tests unitaires pour DevSecurityContextProducer
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class DevSecurityContextProducerTest {
|
||||
|
||||
@Mock
|
||||
private ContainerRequestContext requestContext;
|
||||
|
||||
@Mock
|
||||
private UriInfo uriInfo;
|
||||
|
||||
@Mock
|
||||
private SecurityContext originalSecurityContext;
|
||||
|
||||
private DevSecurityContextProducer producer;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
producer = new DevSecurityContextProducer();
|
||||
|
||||
// Injecter les propriétés via reflection
|
||||
setField("profile", "dev");
|
||||
setField("oidcEnabled", false);
|
||||
}
|
||||
|
||||
private void setField(String fieldName, Object value) throws Exception {
|
||||
Field field = DevSecurityContextProducer.class.getDeclaredField(fieldName);
|
||||
field.setAccessible(true);
|
||||
field.set(producer, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFilter_DevMode() throws Exception {
|
||||
setField("profile", "dev");
|
||||
setField("oidcEnabled", true);
|
||||
|
||||
when(requestContext.getUriInfo()).thenReturn(uriInfo);
|
||||
when(uriInfo.getPath()).thenReturn("/api/users");
|
||||
when(requestContext.getSecurityContext()).thenReturn(originalSecurityContext);
|
||||
|
||||
producer.filter(requestContext);
|
||||
|
||||
verify(requestContext, times(1)).setSecurityContext(any(SecurityContext.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFilter_ProdMode() throws Exception {
|
||||
setField("profile", "prod");
|
||||
setField("oidcEnabled", true);
|
||||
|
||||
// En mode prod, on n'a pas besoin de mocker getUriInfo car le code ne l'utilise pas
|
||||
producer.filter(requestContext);
|
||||
|
||||
verify(requestContext, never()).setSecurityContext(any(SecurityContext.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFilter_OidcDisabled() throws Exception {
|
||||
setField("profile", "prod");
|
||||
setField("oidcEnabled", false);
|
||||
|
||||
when(requestContext.getUriInfo()).thenReturn(uriInfo);
|
||||
when(uriInfo.getPath()).thenReturn("/api/users");
|
||||
when(requestContext.getSecurityContext()).thenReturn(originalSecurityContext);
|
||||
|
||||
producer.filter(requestContext);
|
||||
|
||||
verify(requestContext, times(1)).setSecurityContext(any(SecurityContext.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDevSecurityContext_GetUserPrincipal() throws Exception {
|
||||
setField("profile", "dev");
|
||||
setField("oidcEnabled", false);
|
||||
|
||||
when(requestContext.getUriInfo()).thenReturn(uriInfo);
|
||||
when(uriInfo.getPath()).thenReturn("/api/test");
|
||||
when(requestContext.getSecurityContext()).thenReturn(originalSecurityContext);
|
||||
|
||||
ArgumentCaptor<SecurityContext> captor = ArgumentCaptor.forClass(SecurityContext.class);
|
||||
producer.filter(requestContext);
|
||||
verify(requestContext).setSecurityContext(captor.capture());
|
||||
|
||||
SecurityContext devCtx = captor.getValue();
|
||||
assertNotNull(devCtx.getUserPrincipal());
|
||||
assertEquals("dev-user", devCtx.getUserPrincipal().getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDevSecurityContext_IsUserInRole() throws Exception {
|
||||
setField("profile", "dev");
|
||||
setField("oidcEnabled", false);
|
||||
|
||||
when(requestContext.getUriInfo()).thenReturn(uriInfo);
|
||||
when(uriInfo.getPath()).thenReturn("/api/test");
|
||||
when(requestContext.getSecurityContext()).thenReturn(originalSecurityContext);
|
||||
|
||||
ArgumentCaptor<SecurityContext> captor = ArgumentCaptor.forClass(SecurityContext.class);
|
||||
producer.filter(requestContext);
|
||||
verify(requestContext).setSecurityContext(captor.capture());
|
||||
|
||||
SecurityContext devCtx = captor.getValue();
|
||||
assertTrue(devCtx.isUserInRole("admin"));
|
||||
assertTrue(devCtx.isUserInRole("user_manager"));
|
||||
assertTrue(devCtx.isUserInRole("any_role"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDevSecurityContext_IsSecure_WithOriginal() throws Exception {
|
||||
setField("profile", "dev");
|
||||
setField("oidcEnabled", false);
|
||||
|
||||
when(requestContext.getUriInfo()).thenReturn(uriInfo);
|
||||
when(uriInfo.getPath()).thenReturn("/api/test");
|
||||
when(requestContext.getSecurityContext()).thenReturn(originalSecurityContext);
|
||||
when(originalSecurityContext.isSecure()).thenReturn(true);
|
||||
|
||||
ArgumentCaptor<SecurityContext> captor = ArgumentCaptor.forClass(SecurityContext.class);
|
||||
producer.filter(requestContext);
|
||||
verify(requestContext).setSecurityContext(captor.capture());
|
||||
|
||||
SecurityContext devCtx = captor.getValue();
|
||||
assertTrue(devCtx.isSecure()); // delegates to original which returns true
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDevSecurityContext_IsSecure_WithNullOriginal() throws Exception {
|
||||
setField("profile", "dev");
|
||||
setField("oidcEnabled", false);
|
||||
|
||||
when(requestContext.getUriInfo()).thenReturn(uriInfo);
|
||||
when(uriInfo.getPath()).thenReturn("/api/test");
|
||||
when(requestContext.getSecurityContext()).thenReturn(null); // null original
|
||||
|
||||
ArgumentCaptor<SecurityContext> captor = ArgumentCaptor.forClass(SecurityContext.class);
|
||||
producer.filter(requestContext);
|
||||
verify(requestContext).setSecurityContext(captor.capture());
|
||||
|
||||
SecurityContext devCtx = captor.getValue();
|
||||
assertFalse(devCtx.isSecure()); // original is null → returns false
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDevSecurityContext_GetAuthenticationScheme() throws Exception {
|
||||
setField("profile", "dev");
|
||||
setField("oidcEnabled", false);
|
||||
|
||||
when(requestContext.getUriInfo()).thenReturn(uriInfo);
|
||||
when(uriInfo.getPath()).thenReturn("/api/test");
|
||||
when(requestContext.getSecurityContext()).thenReturn(originalSecurityContext);
|
||||
|
||||
ArgumentCaptor<SecurityContext> captor = ArgumentCaptor.forClass(SecurityContext.class);
|
||||
producer.filter(requestContext);
|
||||
verify(requestContext).setSecurityContext(captor.capture());
|
||||
|
||||
SecurityContext devCtx = captor.getValue();
|
||||
assertEquals("DEV", devCtx.getAuthenticationScheme());
|
||||
}
|
||||
}
|
||||
|
||||
package dev.lions.user.manager.security;
|
||||
|
||||
import jakarta.ws.rs.container.ContainerRequestContext;
|
||||
import jakarta.ws.rs.core.SecurityContext;
|
||||
import jakarta.ws.rs.core.UriInfo;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* Tests unitaires pour DevSecurityContextProducer
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class DevSecurityContextProducerTest {
|
||||
|
||||
@Mock
|
||||
private ContainerRequestContext requestContext;
|
||||
|
||||
@Mock
|
||||
private UriInfo uriInfo;
|
||||
|
||||
@Mock
|
||||
private SecurityContext originalSecurityContext;
|
||||
|
||||
private DevSecurityContextProducer producer;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
producer = new DevSecurityContextProducer();
|
||||
|
||||
// Injecter les propriétés via reflection
|
||||
setField("profile", "dev");
|
||||
setField("oidcEnabled", false);
|
||||
}
|
||||
|
||||
private void setField(String fieldName, Object value) throws Exception {
|
||||
Field field = DevSecurityContextProducer.class.getDeclaredField(fieldName);
|
||||
field.setAccessible(true);
|
||||
field.set(producer, value);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFilter_DevMode() throws Exception {
|
||||
setField("profile", "dev");
|
||||
setField("oidcEnabled", true);
|
||||
|
||||
when(requestContext.getUriInfo()).thenReturn(uriInfo);
|
||||
when(uriInfo.getPath()).thenReturn("/api/users");
|
||||
when(requestContext.getSecurityContext()).thenReturn(originalSecurityContext);
|
||||
|
||||
producer.filter(requestContext);
|
||||
|
||||
verify(requestContext, times(1)).setSecurityContext(any(SecurityContext.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFilter_ProdMode() throws Exception {
|
||||
setField("profile", "prod");
|
||||
setField("oidcEnabled", true);
|
||||
|
||||
// En mode prod, on n'a pas besoin de mocker getUriInfo car le code ne l'utilise pas
|
||||
producer.filter(requestContext);
|
||||
|
||||
verify(requestContext, never()).setSecurityContext(any(SecurityContext.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFilter_OidcDisabled() throws Exception {
|
||||
setField("profile", "prod");
|
||||
setField("oidcEnabled", false);
|
||||
|
||||
when(requestContext.getUriInfo()).thenReturn(uriInfo);
|
||||
when(uriInfo.getPath()).thenReturn("/api/users");
|
||||
when(requestContext.getSecurityContext()).thenReturn(originalSecurityContext);
|
||||
|
||||
producer.filter(requestContext);
|
||||
|
||||
verify(requestContext, times(1)).setSecurityContext(any(SecurityContext.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDevSecurityContext_GetUserPrincipal() throws Exception {
|
||||
setField("profile", "dev");
|
||||
setField("oidcEnabled", false);
|
||||
|
||||
when(requestContext.getUriInfo()).thenReturn(uriInfo);
|
||||
when(uriInfo.getPath()).thenReturn("/api/test");
|
||||
when(requestContext.getSecurityContext()).thenReturn(originalSecurityContext);
|
||||
|
||||
ArgumentCaptor<SecurityContext> captor = ArgumentCaptor.forClass(SecurityContext.class);
|
||||
producer.filter(requestContext);
|
||||
verify(requestContext).setSecurityContext(captor.capture());
|
||||
|
||||
SecurityContext devCtx = captor.getValue();
|
||||
assertNotNull(devCtx.getUserPrincipal());
|
||||
assertEquals("dev-user", devCtx.getUserPrincipal().getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDevSecurityContext_IsUserInRole() throws Exception {
|
||||
setField("profile", "dev");
|
||||
setField("oidcEnabled", false);
|
||||
|
||||
when(requestContext.getUriInfo()).thenReturn(uriInfo);
|
||||
when(uriInfo.getPath()).thenReturn("/api/test");
|
||||
when(requestContext.getSecurityContext()).thenReturn(originalSecurityContext);
|
||||
|
||||
ArgumentCaptor<SecurityContext> captor = ArgumentCaptor.forClass(SecurityContext.class);
|
||||
producer.filter(requestContext);
|
||||
verify(requestContext).setSecurityContext(captor.capture());
|
||||
|
||||
SecurityContext devCtx = captor.getValue();
|
||||
assertTrue(devCtx.isUserInRole("admin"));
|
||||
assertTrue(devCtx.isUserInRole("user_manager"));
|
||||
assertTrue(devCtx.isUserInRole("any_role"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDevSecurityContext_IsSecure_WithOriginal() throws Exception {
|
||||
setField("profile", "dev");
|
||||
setField("oidcEnabled", false);
|
||||
|
||||
when(requestContext.getUriInfo()).thenReturn(uriInfo);
|
||||
when(uriInfo.getPath()).thenReturn("/api/test");
|
||||
when(requestContext.getSecurityContext()).thenReturn(originalSecurityContext);
|
||||
when(originalSecurityContext.isSecure()).thenReturn(true);
|
||||
|
||||
ArgumentCaptor<SecurityContext> captor = ArgumentCaptor.forClass(SecurityContext.class);
|
||||
producer.filter(requestContext);
|
||||
verify(requestContext).setSecurityContext(captor.capture());
|
||||
|
||||
SecurityContext devCtx = captor.getValue();
|
||||
assertTrue(devCtx.isSecure()); // delegates to original which returns true
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDevSecurityContext_IsSecure_WithNullOriginal() throws Exception {
|
||||
setField("profile", "dev");
|
||||
setField("oidcEnabled", false);
|
||||
|
||||
when(requestContext.getUriInfo()).thenReturn(uriInfo);
|
||||
when(uriInfo.getPath()).thenReturn("/api/test");
|
||||
when(requestContext.getSecurityContext()).thenReturn(null); // null original
|
||||
|
||||
ArgumentCaptor<SecurityContext> captor = ArgumentCaptor.forClass(SecurityContext.class);
|
||||
producer.filter(requestContext);
|
||||
verify(requestContext).setSecurityContext(captor.capture());
|
||||
|
||||
SecurityContext devCtx = captor.getValue();
|
||||
assertFalse(devCtx.isSecure()); // original is null → returns false
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDevSecurityContext_GetAuthenticationScheme() throws Exception {
|
||||
setField("profile", "dev");
|
||||
setField("oidcEnabled", false);
|
||||
|
||||
when(requestContext.getUriInfo()).thenReturn(uriInfo);
|
||||
when(uriInfo.getPath()).thenReturn("/api/test");
|
||||
when(requestContext.getSecurityContext()).thenReturn(originalSecurityContext);
|
||||
|
||||
ArgumentCaptor<SecurityContext> captor = ArgumentCaptor.forClass(SecurityContext.class);
|
||||
producer.filter(requestContext);
|
||||
verify(requestContext).setSecurityContext(captor.capture());
|
||||
|
||||
SecurityContext devCtx = captor.getValue();
|
||||
assertEquals("DEV", devCtx.getAuthenticationScheme());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,118 +1,118 @@
|
||||
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 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.auditEnabled = true;
|
||||
auditService.logToDatabase = true;
|
||||
}
|
||||
|
||||
@Test
|
||||
void testLogAction() {
|
||||
AuditLogDTO log = new AuditLogDTO();
|
||||
log.setTypeAction(TypeActionAudit.USER_CREATE);
|
||||
log.setActeurUsername("admin");
|
||||
|
||||
when(auditLogMapper.toEntity(any(AuditLogDTO.class))).thenReturn(new AuditLogEntity());
|
||||
|
||||
auditService.logAction(log);
|
||||
|
||||
verify(auditLogRepository).persist(any(AuditLogEntity.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testLogDisabled() {
|
||||
auditService.auditEnabled = false;
|
||||
AuditLogDTO log = new AuditLogDTO();
|
||||
|
||||
auditService.logAction(log);
|
||||
|
||||
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");
|
||||
|
||||
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");
|
||||
|
||||
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() {
|
||||
// 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);
|
||||
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);
|
||||
assertNotNull(byType);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testClearAll() {
|
||||
auditService.clearAll();
|
||||
verify(auditLogRepository).deleteAll();
|
||||
}
|
||||
}
|
||||
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 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.auditEnabled = true;
|
||||
auditService.logToDatabase = true;
|
||||
}
|
||||
|
||||
@Test
|
||||
void testLogAction() {
|
||||
AuditLogDTO log = new AuditLogDTO();
|
||||
log.setTypeAction(TypeActionAudit.USER_CREATE);
|
||||
log.setActeurUsername("admin");
|
||||
|
||||
when(auditLogMapper.toEntity(any(AuditLogDTO.class))).thenReturn(new AuditLogEntity());
|
||||
|
||||
auditService.logAction(log);
|
||||
|
||||
verify(auditLogRepository).persist(any(AuditLogEntity.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testLogDisabled() {
|
||||
auditService.auditEnabled = false;
|
||||
AuditLogDTO log = new AuditLogDTO();
|
||||
|
||||
auditService.logAction(log);
|
||||
|
||||
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");
|
||||
|
||||
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");
|
||||
|
||||
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() {
|
||||
// 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);
|
||||
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);
|
||||
assertNotNull(byType);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testClearAll() {
|
||||
auditService.clearAll();
|
||||
verify(auditLogRepository).deleteAll();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,280 +1,280 @@
|
||||
package dev.lions.user.manager.service.impl;
|
||||
|
||||
import dev.lions.user.manager.dto.realm.RealmAssignmentDTO;
|
||||
import dev.lions.user.manager.enums.audit.TypeActionAudit;
|
||||
import dev.lions.user.manager.service.AuditService;
|
||||
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 java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* Tests unitaires pour RealmAuthorizationServiceImpl
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class RealmAuthorizationServiceImplTest {
|
||||
|
||||
@Mock
|
||||
private AuditService auditService;
|
||||
|
||||
@InjectMocks
|
||||
private RealmAuthorizationServiceImpl realmAuthorizationService;
|
||||
|
||||
private RealmAssignmentDTO assignment;
|
||||
|
||||
@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();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllAssignments_Empty() {
|
||||
List<RealmAssignmentDTO> assignments = realmAuthorizationService.getAllAssignments();
|
||||
assertTrue(assignments.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllAssignments_WithAssignments() {
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
List<RealmAssignmentDTO> assignments = realmAuthorizationService.getAllAssignments();
|
||||
assertEquals(1, assignments.size());
|
||||
assertEquals("assignment-1", assignments.get(0).getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAssignmentsByUser_Success() {
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
List<RealmAssignmentDTO> assignments = realmAuthorizationService.getAssignmentsByUser("user-1");
|
||||
assertEquals(1, assignments.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAssignmentsByUser_Empty() {
|
||||
List<RealmAssignmentDTO> assignments = realmAuthorizationService.getAssignmentsByUser("user-1");
|
||||
assertTrue(assignments.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAssignmentsByRealm_Success() {
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
List<RealmAssignmentDTO> assignments = realmAuthorizationService.getAssignmentsByRealm("realm1");
|
||||
assertEquals(1, assignments.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAssignmentById_Success() {
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
Optional<RealmAssignmentDTO> found = realmAuthorizationService.getAssignmentById("assignment-1");
|
||||
assertTrue(found.isPresent());
|
||||
assertEquals("assignment-1", found.get().getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAssignmentById_NotFound() {
|
||||
Optional<RealmAssignmentDTO> found = realmAuthorizationService.getAssignmentById("non-existent");
|
||||
assertFalse(found.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCanManageRealm_SuperAdmin() {
|
||||
realmAuthorizationService.setSuperAdmin("user-1", true);
|
||||
assertTrue(realmAuthorizationService.canManageRealm("user-1", "any-realm"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCanManageRealm_WithAssignment() {
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
assertTrue(realmAuthorizationService.canManageRealm("user-1", "realm1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCanManageRealm_NoAccess() {
|
||||
assertFalse(realmAuthorizationService.canManageRealm("user-1", "realm1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsSuperAdmin_True() {
|
||||
realmAuthorizationService.setSuperAdmin("user-1", true);
|
||||
assertTrue(realmAuthorizationService.isSuperAdmin("user-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsSuperAdmin_False() {
|
||||
assertFalse(realmAuthorizationService.isSuperAdmin("user-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAuthorizedRealms_SuperAdmin() {
|
||||
realmAuthorizationService.setSuperAdmin("user-1", true);
|
||||
List<String> realms = realmAuthorizationService.getAuthorizedRealms("user-1");
|
||||
assertTrue(realms.isEmpty()); // Super admin retourne liste vide
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAuthorizedRealms_WithAssignments() {
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
List<String> realms = realmAuthorizationService.getAuthorizedRealms("user-1");
|
||||
assertEquals(1, realms.size());
|
||||
assertEquals("realm1", realms.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAssignRealmToUser_Success() {
|
||||
doNothing().when(auditService).logSuccess(
|
||||
any(TypeActionAudit.class),
|
||||
anyString(),
|
||||
anyString(),
|
||||
anyString(),
|
||||
anyString(),
|
||||
anyString(),
|
||||
anyString()
|
||||
);
|
||||
|
||||
RealmAssignmentDTO result = realmAuthorizationService.assignRealmToUser(assignment);
|
||||
assertNotNull(result);
|
||||
assertNotNull(result.getId());
|
||||
assertTrue(result.isActive());
|
||||
assertNotNull(result.getAssignedAt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAssignRealmToUser_NoUserId() {
|
||||
assignment.setUserId(null);
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAssignRealmToUser_NoRealmName() {
|
||||
assignment.setRealmName(null);
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAssignRealmToUser_Duplicate() {
|
||||
doNothing().when(auditService).logSuccess(any(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRevokeRealmFromUser_Success() {
|
||||
doNothing().when(auditService).logSuccess(any(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
realmAuthorizationService.revokeRealmFromUser("user-1", "realm1");
|
||||
assertFalse(realmAuthorizationService.canManageRealm("user-1", "realm1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRevokeRealmFromUser_NotExists() {
|
||||
// Ne doit pas lever d'exception si l'assignation n'existe pas
|
||||
assertDoesNotThrow(() -> {
|
||||
realmAuthorizationService.revokeRealmFromUser("user-1", "realm1");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRevokeAllRealmsFromUser() {
|
||||
doNothing().when(auditService).logSuccess(any(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
realmAuthorizationService.revokeAllRealmsFromUser("user-1");
|
||||
assertTrue(realmAuthorizationService.getAssignmentsByUser("user-1").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSetSuperAdmin_True() {
|
||||
doNothing().when(auditService).logSuccess(any(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
realmAuthorizationService.setSuperAdmin("user-1", true);
|
||||
assertTrue(realmAuthorizationService.isSuperAdmin("user-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSetSuperAdmin_False() {
|
||||
doNothing().when(auditService).logSuccess(any(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
realmAuthorizationService.setSuperAdmin("user-1", true);
|
||||
realmAuthorizationService.setSuperAdmin("user-1", false);
|
||||
assertFalse(realmAuthorizationService.isSuperAdmin("user-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeactivateAssignment_Success() {
|
||||
doNothing().when(auditService).logSuccess(any(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
realmAuthorizationService.deactivateAssignment(assignment.getId());
|
||||
Optional<RealmAssignmentDTO> found = realmAuthorizationService.getAssignmentById(assignment.getId());
|
||||
assertTrue(found.isPresent());
|
||||
assertFalse(found.get().isActive());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeactivateAssignment_NotFound() {
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
realmAuthorizationService.deactivateAssignment("non-existent");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testActivateAssignment_Success() {
|
||||
doNothing().when(auditService).logSuccess(any(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
realmAuthorizationService.deactivateAssignment(assignment.getId());
|
||||
realmAuthorizationService.activateAssignment(assignment.getId());
|
||||
Optional<RealmAssignmentDTO> found = realmAuthorizationService.getAssignmentById(assignment.getId());
|
||||
assertTrue(found.isPresent());
|
||||
assertTrue(found.get().isActive());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCountAssignmentsByUser() {
|
||||
doNothing().when(auditService).logSuccess(any(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
long count = realmAuthorizationService.countAssignmentsByUser("user-1");
|
||||
assertEquals(1, count);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCountUsersByRealm() {
|
||||
doNothing().when(auditService).logSuccess(any(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
long count = realmAuthorizationService.countUsersByRealm("realm1");
|
||||
assertEquals(1, count);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAssignmentExists_True() {
|
||||
doNothing().when(auditService).logSuccess(any(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
assertTrue(realmAuthorizationService.assignmentExists("user-1", "realm1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAssignmentExists_False() {
|
||||
assertFalse(realmAuthorizationService.assignmentExists("user-1", "realm1"));
|
||||
}
|
||||
}
|
||||
|
||||
package dev.lions.user.manager.service.impl;
|
||||
|
||||
import dev.lions.user.manager.dto.realm.RealmAssignmentDTO;
|
||||
import dev.lions.user.manager.enums.audit.TypeActionAudit;
|
||||
import dev.lions.user.manager.service.AuditService;
|
||||
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 java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* Tests unitaires pour RealmAuthorizationServiceImpl
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class RealmAuthorizationServiceImplTest {
|
||||
|
||||
@Mock
|
||||
private AuditService auditService;
|
||||
|
||||
@InjectMocks
|
||||
private RealmAuthorizationServiceImpl realmAuthorizationService;
|
||||
|
||||
private RealmAssignmentDTO assignment;
|
||||
|
||||
@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();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllAssignments_Empty() {
|
||||
List<RealmAssignmentDTO> assignments = realmAuthorizationService.getAllAssignments();
|
||||
assertTrue(assignments.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllAssignments_WithAssignments() {
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
List<RealmAssignmentDTO> assignments = realmAuthorizationService.getAllAssignments();
|
||||
assertEquals(1, assignments.size());
|
||||
assertEquals("assignment-1", assignments.get(0).getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAssignmentsByUser_Success() {
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
List<RealmAssignmentDTO> assignments = realmAuthorizationService.getAssignmentsByUser("user-1");
|
||||
assertEquals(1, assignments.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAssignmentsByUser_Empty() {
|
||||
List<RealmAssignmentDTO> assignments = realmAuthorizationService.getAssignmentsByUser("user-1");
|
||||
assertTrue(assignments.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAssignmentsByRealm_Success() {
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
List<RealmAssignmentDTO> assignments = realmAuthorizationService.getAssignmentsByRealm("realm1");
|
||||
assertEquals(1, assignments.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAssignmentById_Success() {
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
Optional<RealmAssignmentDTO> found = realmAuthorizationService.getAssignmentById("assignment-1");
|
||||
assertTrue(found.isPresent());
|
||||
assertEquals("assignment-1", found.get().getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAssignmentById_NotFound() {
|
||||
Optional<RealmAssignmentDTO> found = realmAuthorizationService.getAssignmentById("non-existent");
|
||||
assertFalse(found.isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCanManageRealm_SuperAdmin() {
|
||||
realmAuthorizationService.setSuperAdmin("user-1", true);
|
||||
assertTrue(realmAuthorizationService.canManageRealm("user-1", "any-realm"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCanManageRealm_WithAssignment() {
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
assertTrue(realmAuthorizationService.canManageRealm("user-1", "realm1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCanManageRealm_NoAccess() {
|
||||
assertFalse(realmAuthorizationService.canManageRealm("user-1", "realm1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsSuperAdmin_True() {
|
||||
realmAuthorizationService.setSuperAdmin("user-1", true);
|
||||
assertTrue(realmAuthorizationService.isSuperAdmin("user-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsSuperAdmin_False() {
|
||||
assertFalse(realmAuthorizationService.isSuperAdmin("user-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAuthorizedRealms_SuperAdmin() {
|
||||
realmAuthorizationService.setSuperAdmin("user-1", true);
|
||||
List<String> realms = realmAuthorizationService.getAuthorizedRealms("user-1");
|
||||
assertTrue(realms.isEmpty()); // Super admin retourne liste vide
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAuthorizedRealms_WithAssignments() {
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
List<String> realms = realmAuthorizationService.getAuthorizedRealms("user-1");
|
||||
assertEquals(1, realms.size());
|
||||
assertEquals("realm1", realms.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAssignRealmToUser_Success() {
|
||||
doNothing().when(auditService).logSuccess(
|
||||
any(TypeActionAudit.class),
|
||||
anyString(),
|
||||
anyString(),
|
||||
anyString(),
|
||||
anyString(),
|
||||
anyString(),
|
||||
anyString()
|
||||
);
|
||||
|
||||
RealmAssignmentDTO result = realmAuthorizationService.assignRealmToUser(assignment);
|
||||
assertNotNull(result);
|
||||
assertNotNull(result.getId());
|
||||
assertTrue(result.isActive());
|
||||
assertNotNull(result.getAssignedAt());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAssignRealmToUser_NoUserId() {
|
||||
assignment.setUserId(null);
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAssignRealmToUser_NoRealmName() {
|
||||
assignment.setRealmName(null);
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAssignRealmToUser_Duplicate() {
|
||||
doNothing().when(auditService).logSuccess(any(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRevokeRealmFromUser_Success() {
|
||||
doNothing().when(auditService).logSuccess(any(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
realmAuthorizationService.revokeRealmFromUser("user-1", "realm1");
|
||||
assertFalse(realmAuthorizationService.canManageRealm("user-1", "realm1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRevokeRealmFromUser_NotExists() {
|
||||
// Ne doit pas lever d'exception si l'assignation n'existe pas
|
||||
assertDoesNotThrow(() -> {
|
||||
realmAuthorizationService.revokeRealmFromUser("user-1", "realm1");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRevokeAllRealmsFromUser() {
|
||||
doNothing().when(auditService).logSuccess(any(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
realmAuthorizationService.revokeAllRealmsFromUser("user-1");
|
||||
assertTrue(realmAuthorizationService.getAssignmentsByUser("user-1").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSetSuperAdmin_True() {
|
||||
doNothing().when(auditService).logSuccess(any(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
realmAuthorizationService.setSuperAdmin("user-1", true);
|
||||
assertTrue(realmAuthorizationService.isSuperAdmin("user-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSetSuperAdmin_False() {
|
||||
doNothing().when(auditService).logSuccess(any(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
realmAuthorizationService.setSuperAdmin("user-1", true);
|
||||
realmAuthorizationService.setSuperAdmin("user-1", false);
|
||||
assertFalse(realmAuthorizationService.isSuperAdmin("user-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeactivateAssignment_Success() {
|
||||
doNothing().when(auditService).logSuccess(any(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
realmAuthorizationService.deactivateAssignment(assignment.getId());
|
||||
Optional<RealmAssignmentDTO> found = realmAuthorizationService.getAssignmentById(assignment.getId());
|
||||
assertTrue(found.isPresent());
|
||||
assertFalse(found.get().isActive());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeactivateAssignment_NotFound() {
|
||||
assertThrows(IllegalArgumentException.class, () -> {
|
||||
realmAuthorizationService.deactivateAssignment("non-existent");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void testActivateAssignment_Success() {
|
||||
doNothing().when(auditService).logSuccess(any(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
realmAuthorizationService.deactivateAssignment(assignment.getId());
|
||||
realmAuthorizationService.activateAssignment(assignment.getId());
|
||||
Optional<RealmAssignmentDTO> found = realmAuthorizationService.getAssignmentById(assignment.getId());
|
||||
assertTrue(found.isPresent());
|
||||
assertTrue(found.get().isActive());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCountAssignmentsByUser() {
|
||||
doNothing().when(auditService).logSuccess(any(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
long count = realmAuthorizationService.countAssignmentsByUser("user-1");
|
||||
assertEquals(1, count);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCountUsersByRealm() {
|
||||
doNothing().when(auditService).logSuccess(any(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
long count = realmAuthorizationService.countUsersByRealm("realm1");
|
||||
assertEquals(1, count);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAssignmentExists_True() {
|
||||
doNothing().when(auditService).logSuccess(any(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
|
||||
realmAuthorizationService.assignRealmToUser(assignment);
|
||||
assertTrue(realmAuthorizationService.assignmentExists("user-1", "realm1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAssignmentExists_False() {
|
||||
assertFalse(realmAuthorizationService.assignmentExists("user-1", "realm1"));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,350 +1,350 @@
|
||||
package dev.lions.user.manager.service.impl;
|
||||
|
||||
import dev.lions.user.manager.client.KeycloakAdminClient;
|
||||
import dev.lions.user.manager.dto.role.RoleDTO;
|
||||
import dev.lions.user.manager.enums.role.TypeRole;
|
||||
import dev.lions.user.manager.mapper.RoleMapper;
|
||||
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.*;
|
||||
import org.keycloak.representations.idm.ClientRepresentation;
|
||||
import org.keycloak.representations.idm.RoleRepresentation;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* Tests complets pour RoleServiceImpl pour atteindre 100% de couverture
|
||||
* Couvre updateRole, deleteRole pour CLIENT_ROLE, createRealmRole avec rôle existant, etc.
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class RoleServiceImplCompleteTest {
|
||||
|
||||
@Mock
|
||||
private KeycloakAdminClient keycloakAdminClient;
|
||||
|
||||
@Mock
|
||||
private Keycloak keycloakInstance;
|
||||
|
||||
@Mock
|
||||
private RealmResource realmResource;
|
||||
|
||||
@Mock
|
||||
private RolesResource rolesResource;
|
||||
|
||||
@Mock
|
||||
private RoleResource roleResource;
|
||||
|
||||
@Mock
|
||||
private ClientsResource clientsResource;
|
||||
|
||||
@Mock
|
||||
private ClientResource clientResource;
|
||||
|
||||
@InjectMocks
|
||||
private RoleServiceImpl roleService;
|
||||
|
||||
private static final String REALM = "test-realm";
|
||||
private static final String ROLE_ID = "role-123";
|
||||
private static final String ROLE_NAME = "test-role";
|
||||
private static final String CLIENT_NAME = "test-client";
|
||||
private static final String INTERNAL_CLIENT_ID = "internal-client-id";
|
||||
|
||||
@Test
|
||||
void testCreateRealmRole_RoleAlreadyExists() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.get(ROLE_NAME)).thenReturn(roleResource);
|
||||
|
||||
RoleRepresentation existingRole = new RoleRepresentation();
|
||||
existingRole.setName(ROLE_NAME);
|
||||
when(roleResource.toRepresentation()).thenReturn(existingRole);
|
||||
|
||||
RoleDTO roleDTO = RoleDTO.builder()
|
||||
.name(ROLE_NAME)
|
||||
.description("Test role")
|
||||
.build();
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () ->
|
||||
roleService.createRealmRole(roleDTO, REALM));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateRole_RealmRole_Success() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
|
||||
// Mock getRealmRoleById
|
||||
RoleRepresentation roleRep = new RoleRepresentation();
|
||||
roleRep.setId(ROLE_ID);
|
||||
roleRep.setName(ROLE_NAME);
|
||||
when(rolesResource.list()).thenReturn(List.of(roleRep));
|
||||
when(rolesResource.get(ROLE_NAME)).thenReturn(roleResource);
|
||||
when(roleResource.toRepresentation()).thenReturn(roleRep);
|
||||
|
||||
RoleDTO roleDTO = RoleDTO.builder()
|
||||
.id(ROLE_ID)
|
||||
.name(ROLE_NAME)
|
||||
.description("Updated description")
|
||||
.build();
|
||||
|
||||
RoleDTO result = roleService.updateRole(ROLE_ID, roleDTO, REALM, TypeRole.REALM_ROLE, null);
|
||||
|
||||
assertNotNull(result);
|
||||
verify(roleResource).update(any(RoleRepresentation.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateRole_RealmRole_NotFound() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.list()).thenReturn(Collections.emptyList());
|
||||
|
||||
RoleDTO roleDTO = RoleDTO.builder()
|
||||
.id(ROLE_ID)
|
||||
.name(ROLE_NAME)
|
||||
.build();
|
||||
|
||||
assertThrows(jakarta.ws.rs.NotFoundException.class, () ->
|
||||
roleService.updateRole(ROLE_ID, roleDTO, REALM, TypeRole.REALM_ROLE, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateRole_RealmRole_NoDescription() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
|
||||
RoleRepresentation roleRep = new RoleRepresentation();
|
||||
roleRep.setId(ROLE_ID);
|
||||
roleRep.setName(ROLE_NAME);
|
||||
when(rolesResource.list()).thenReturn(List.of(roleRep));
|
||||
when(rolesResource.get(ROLE_NAME)).thenReturn(roleResource);
|
||||
when(roleResource.toRepresentation()).thenReturn(roleRep);
|
||||
|
||||
RoleDTO roleDTO = RoleDTO.builder()
|
||||
.id(ROLE_ID)
|
||||
.name(ROLE_NAME)
|
||||
.description(null) // No description
|
||||
.build();
|
||||
|
||||
RoleDTO result = roleService.updateRole(ROLE_ID, roleDTO, REALM, TypeRole.REALM_ROLE, null);
|
||||
|
||||
assertNotNull(result);
|
||||
verify(roleResource).update(any(RoleRepresentation.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateRole_ClientRole_Success() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.clients()).thenReturn(clientsResource);
|
||||
|
||||
ClientRepresentation client = new ClientRepresentation();
|
||||
client.setId(INTERNAL_CLIENT_ID);
|
||||
when(clientsResource.findByClientId(CLIENT_NAME)).thenReturn(List.of(client));
|
||||
when(clientsResource.get(INTERNAL_CLIENT_ID)).thenReturn(clientResource);
|
||||
when(clientResource.roles()).thenReturn(rolesResource);
|
||||
|
||||
// Mock getRoleById
|
||||
RoleRepresentation roleRep = new RoleRepresentation();
|
||||
roleRep.setId(ROLE_ID);
|
||||
roleRep.setName(ROLE_NAME);
|
||||
when(rolesResource.list()).thenReturn(List.of(roleRep));
|
||||
when(rolesResource.get(ROLE_NAME)).thenReturn(roleResource);
|
||||
when(roleResource.toRepresentation()).thenReturn(roleRep);
|
||||
|
||||
RoleDTO roleDTO = RoleDTO.builder()
|
||||
.id(ROLE_ID)
|
||||
.name(ROLE_NAME)
|
||||
.description("Updated description")
|
||||
.build();
|
||||
|
||||
RoleDTO result = roleService.updateRole(ROLE_ID, roleDTO, REALM, TypeRole.CLIENT_ROLE, CLIENT_NAME);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(CLIENT_NAME, result.getClientId());
|
||||
verify(roleResource).update(any(RoleRepresentation.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateRole_ClientRole_ClientNotFound() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.clients()).thenReturn(clientsResource);
|
||||
when(clientsResource.findByClientId(CLIENT_NAME)).thenReturn(Collections.emptyList());
|
||||
|
||||
RoleDTO roleDTO = RoleDTO.builder()
|
||||
.id(ROLE_ID)
|
||||
.name(ROLE_NAME)
|
||||
.build();
|
||||
|
||||
// getRoleById is called first, which will throw NotFoundException when client is not found
|
||||
// Actually, getRoleById returns Optional.empty() when client is not found
|
||||
// So it will throw NotFoundException for role not found
|
||||
assertThrows(jakarta.ws.rs.NotFoundException.class, () ->
|
||||
roleService.updateRole(ROLE_ID, roleDTO, REALM, TypeRole.CLIENT_ROLE, CLIENT_NAME));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateRole_ClientRole_NotFound() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.clients()).thenReturn(clientsResource);
|
||||
|
||||
ClientRepresentation client = new ClientRepresentation();
|
||||
client.setId(INTERNAL_CLIENT_ID);
|
||||
when(clientsResource.findByClientId(CLIENT_NAME)).thenReturn(List.of(client));
|
||||
when(clientsResource.get(INTERNAL_CLIENT_ID)).thenReturn(clientResource);
|
||||
when(clientResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.list()).thenReturn(Collections.emptyList());
|
||||
|
||||
RoleDTO roleDTO = RoleDTO.builder()
|
||||
.id(ROLE_ID)
|
||||
.name(ROLE_NAME)
|
||||
.build();
|
||||
|
||||
assertThrows(jakarta.ws.rs.NotFoundException.class, () ->
|
||||
roleService.updateRole(ROLE_ID, roleDTO, REALM, TypeRole.CLIENT_ROLE, CLIENT_NAME));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateRole_UnsupportedType() {
|
||||
RoleDTO roleDTO = RoleDTO.builder()
|
||||
.id(ROLE_ID)
|
||||
.name(ROLE_NAME)
|
||||
.build();
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () ->
|
||||
roleService.updateRole(ROLE_ID, roleDTO, REALM, null, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteRole_ClientRole_Success() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.clients()).thenReturn(clientsResource);
|
||||
|
||||
ClientRepresentation client = new ClientRepresentation();
|
||||
client.setId(INTERNAL_CLIENT_ID);
|
||||
when(clientsResource.findByClientId(CLIENT_NAME)).thenReturn(List.of(client));
|
||||
when(clientsResource.get(INTERNAL_CLIENT_ID)).thenReturn(clientResource);
|
||||
when(clientResource.roles()).thenReturn(rolesResource);
|
||||
|
||||
// Mock getRoleById - getRoleById for CLIENT_ROLE only uses rolesResource.list()
|
||||
RoleRepresentation roleRep = new RoleRepresentation();
|
||||
roleRep.setId(ROLE_ID);
|
||||
roleRep.setName(ROLE_NAME);
|
||||
when(rolesResource.list()).thenReturn(List.of(roleRep));
|
||||
|
||||
roleService.deleteRole(ROLE_ID, REALM, TypeRole.CLIENT_ROLE, CLIENT_NAME);
|
||||
|
||||
verify(rolesResource).deleteRole(ROLE_NAME);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteRole_ClientRole_ClientNotFound() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.clients()).thenReturn(clientsResource);
|
||||
when(clientsResource.findByClientId(CLIENT_NAME)).thenReturn(Collections.emptyList());
|
||||
|
||||
// getRoleById is called first, which returns Optional.empty() when client is not found
|
||||
// So it will throw NotFoundException for role not found
|
||||
assertThrows(jakarta.ws.rs.NotFoundException.class, () ->
|
||||
roleService.deleteRole(ROLE_ID, REALM, TypeRole.CLIENT_ROLE, CLIENT_NAME));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteRole_ClientRole_NotFound() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.clients()).thenReturn(clientsResource);
|
||||
|
||||
ClientRepresentation client = new ClientRepresentation();
|
||||
client.setId(INTERNAL_CLIENT_ID);
|
||||
when(clientsResource.findByClientId(CLIENT_NAME)).thenReturn(List.of(client));
|
||||
when(clientsResource.get(INTERNAL_CLIENT_ID)).thenReturn(clientResource);
|
||||
when(clientResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.list()).thenReturn(Collections.emptyList());
|
||||
|
||||
assertThrows(jakarta.ws.rs.NotFoundException.class, () ->
|
||||
roleService.deleteRole(ROLE_ID, REALM, TypeRole.CLIENT_ROLE, CLIENT_NAME));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteRole_UnsupportedType() {
|
||||
assertThrows(IllegalArgumentException.class, () ->
|
||||
roleService.deleteRole(ROLE_ID, REALM, null, null));
|
||||
}
|
||||
|
||||
// Note: getRealmRoleById is private, so we test it indirectly through updateRole
|
||||
// The exception path is tested via updateRole_RealmRole_NotFound
|
||||
|
||||
@Test
|
||||
void testGetAllRealmRoles_Success() {
|
||||
when(keycloakAdminClient.realmExists(REALM)).thenReturn(true);
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
|
||||
RoleRepresentation role1 = new RoleRepresentation();
|
||||
role1.setName("role1");
|
||||
RoleRepresentation role2 = new RoleRepresentation();
|
||||
role2.setName("role2");
|
||||
when(rolesResource.list()).thenReturn(List.of(role1, role2));
|
||||
|
||||
var result = roleService.getAllRealmRoles(REALM);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(2, result.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealmRoles_With404InMessage() {
|
||||
when(keycloakAdminClient.realmExists(REALM)).thenReturn(true);
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.list()).thenThrow(new RuntimeException("Server response is: 404"));
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () ->
|
||||
roleService.getAllRealmRoles(REALM));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealmRoles_WithNotInMessage() {
|
||||
when(keycloakAdminClient.realmExists(REALM)).thenReturn(true);
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.list()).thenThrow(new RuntimeException("Not Found"));
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () ->
|
||||
roleService.getAllRealmRoles(REALM));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealmRoles_WithOtherException() {
|
||||
when(keycloakAdminClient.realmExists(REALM)).thenReturn(true);
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.list()).thenThrow(new RuntimeException("Connection error"));
|
||||
|
||||
assertThrows(RuntimeException.class, () ->
|
||||
roleService.getAllRealmRoles(REALM));
|
||||
}
|
||||
}
|
||||
|
||||
package dev.lions.user.manager.service.impl;
|
||||
|
||||
import dev.lions.user.manager.client.KeycloakAdminClient;
|
||||
import dev.lions.user.manager.dto.role.RoleDTO;
|
||||
import dev.lions.user.manager.enums.role.TypeRole;
|
||||
import dev.lions.user.manager.mapper.RoleMapper;
|
||||
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.*;
|
||||
import org.keycloak.representations.idm.ClientRepresentation;
|
||||
import org.keycloak.representations.idm.RoleRepresentation;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* Tests complets pour RoleServiceImpl pour atteindre 100% de couverture
|
||||
* Couvre updateRole, deleteRole pour CLIENT_ROLE, createRealmRole avec rôle existant, etc.
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class RoleServiceImplCompleteTest {
|
||||
|
||||
@Mock
|
||||
private KeycloakAdminClient keycloakAdminClient;
|
||||
|
||||
@Mock
|
||||
private Keycloak keycloakInstance;
|
||||
|
||||
@Mock
|
||||
private RealmResource realmResource;
|
||||
|
||||
@Mock
|
||||
private RolesResource rolesResource;
|
||||
|
||||
@Mock
|
||||
private RoleResource roleResource;
|
||||
|
||||
@Mock
|
||||
private ClientsResource clientsResource;
|
||||
|
||||
@Mock
|
||||
private ClientResource clientResource;
|
||||
|
||||
@InjectMocks
|
||||
private RoleServiceImpl roleService;
|
||||
|
||||
private static final String REALM = "test-realm";
|
||||
private static final String ROLE_ID = "role-123";
|
||||
private static final String ROLE_NAME = "test-role";
|
||||
private static final String CLIENT_NAME = "test-client";
|
||||
private static final String INTERNAL_CLIENT_ID = "internal-client-id";
|
||||
|
||||
@Test
|
||||
void testCreateRealmRole_RoleAlreadyExists() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.get(ROLE_NAME)).thenReturn(roleResource);
|
||||
|
||||
RoleRepresentation existingRole = new RoleRepresentation();
|
||||
existingRole.setName(ROLE_NAME);
|
||||
when(roleResource.toRepresentation()).thenReturn(existingRole);
|
||||
|
||||
RoleDTO roleDTO = RoleDTO.builder()
|
||||
.name(ROLE_NAME)
|
||||
.description("Test role")
|
||||
.build();
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () ->
|
||||
roleService.createRealmRole(roleDTO, REALM));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateRole_RealmRole_Success() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
|
||||
// Mock getRealmRoleById
|
||||
RoleRepresentation roleRep = new RoleRepresentation();
|
||||
roleRep.setId(ROLE_ID);
|
||||
roleRep.setName(ROLE_NAME);
|
||||
when(rolesResource.list()).thenReturn(List.of(roleRep));
|
||||
when(rolesResource.get(ROLE_NAME)).thenReturn(roleResource);
|
||||
when(roleResource.toRepresentation()).thenReturn(roleRep);
|
||||
|
||||
RoleDTO roleDTO = RoleDTO.builder()
|
||||
.id(ROLE_ID)
|
||||
.name(ROLE_NAME)
|
||||
.description("Updated description")
|
||||
.build();
|
||||
|
||||
RoleDTO result = roleService.updateRole(ROLE_ID, roleDTO, REALM, TypeRole.REALM_ROLE, null);
|
||||
|
||||
assertNotNull(result);
|
||||
verify(roleResource).update(any(RoleRepresentation.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateRole_RealmRole_NotFound() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.list()).thenReturn(Collections.emptyList());
|
||||
|
||||
RoleDTO roleDTO = RoleDTO.builder()
|
||||
.id(ROLE_ID)
|
||||
.name(ROLE_NAME)
|
||||
.build();
|
||||
|
||||
assertThrows(jakarta.ws.rs.NotFoundException.class, () ->
|
||||
roleService.updateRole(ROLE_ID, roleDTO, REALM, TypeRole.REALM_ROLE, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateRole_RealmRole_NoDescription() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
|
||||
RoleRepresentation roleRep = new RoleRepresentation();
|
||||
roleRep.setId(ROLE_ID);
|
||||
roleRep.setName(ROLE_NAME);
|
||||
when(rolesResource.list()).thenReturn(List.of(roleRep));
|
||||
when(rolesResource.get(ROLE_NAME)).thenReturn(roleResource);
|
||||
when(roleResource.toRepresentation()).thenReturn(roleRep);
|
||||
|
||||
RoleDTO roleDTO = RoleDTO.builder()
|
||||
.id(ROLE_ID)
|
||||
.name(ROLE_NAME)
|
||||
.description(null) // No description
|
||||
.build();
|
||||
|
||||
RoleDTO result = roleService.updateRole(ROLE_ID, roleDTO, REALM, TypeRole.REALM_ROLE, null);
|
||||
|
||||
assertNotNull(result);
|
||||
verify(roleResource).update(any(RoleRepresentation.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateRole_ClientRole_Success() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.clients()).thenReturn(clientsResource);
|
||||
|
||||
ClientRepresentation client = new ClientRepresentation();
|
||||
client.setId(INTERNAL_CLIENT_ID);
|
||||
when(clientsResource.findByClientId(CLIENT_NAME)).thenReturn(List.of(client));
|
||||
when(clientsResource.get(INTERNAL_CLIENT_ID)).thenReturn(clientResource);
|
||||
when(clientResource.roles()).thenReturn(rolesResource);
|
||||
|
||||
// Mock getRoleById
|
||||
RoleRepresentation roleRep = new RoleRepresentation();
|
||||
roleRep.setId(ROLE_ID);
|
||||
roleRep.setName(ROLE_NAME);
|
||||
when(rolesResource.list()).thenReturn(List.of(roleRep));
|
||||
when(rolesResource.get(ROLE_NAME)).thenReturn(roleResource);
|
||||
when(roleResource.toRepresentation()).thenReturn(roleRep);
|
||||
|
||||
RoleDTO roleDTO = RoleDTO.builder()
|
||||
.id(ROLE_ID)
|
||||
.name(ROLE_NAME)
|
||||
.description("Updated description")
|
||||
.build();
|
||||
|
||||
RoleDTO result = roleService.updateRole(ROLE_ID, roleDTO, REALM, TypeRole.CLIENT_ROLE, CLIENT_NAME);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(CLIENT_NAME, result.getClientId());
|
||||
verify(roleResource).update(any(RoleRepresentation.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateRole_ClientRole_ClientNotFound() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.clients()).thenReturn(clientsResource);
|
||||
when(clientsResource.findByClientId(CLIENT_NAME)).thenReturn(Collections.emptyList());
|
||||
|
||||
RoleDTO roleDTO = RoleDTO.builder()
|
||||
.id(ROLE_ID)
|
||||
.name(ROLE_NAME)
|
||||
.build();
|
||||
|
||||
// getRoleById is called first, which will throw NotFoundException when client is not found
|
||||
// Actually, getRoleById returns Optional.empty() when client is not found
|
||||
// So it will throw NotFoundException for role not found
|
||||
assertThrows(jakarta.ws.rs.NotFoundException.class, () ->
|
||||
roleService.updateRole(ROLE_ID, roleDTO, REALM, TypeRole.CLIENT_ROLE, CLIENT_NAME));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateRole_ClientRole_NotFound() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.clients()).thenReturn(clientsResource);
|
||||
|
||||
ClientRepresentation client = new ClientRepresentation();
|
||||
client.setId(INTERNAL_CLIENT_ID);
|
||||
when(clientsResource.findByClientId(CLIENT_NAME)).thenReturn(List.of(client));
|
||||
when(clientsResource.get(INTERNAL_CLIENT_ID)).thenReturn(clientResource);
|
||||
when(clientResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.list()).thenReturn(Collections.emptyList());
|
||||
|
||||
RoleDTO roleDTO = RoleDTO.builder()
|
||||
.id(ROLE_ID)
|
||||
.name(ROLE_NAME)
|
||||
.build();
|
||||
|
||||
assertThrows(jakarta.ws.rs.NotFoundException.class, () ->
|
||||
roleService.updateRole(ROLE_ID, roleDTO, REALM, TypeRole.CLIENT_ROLE, CLIENT_NAME));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUpdateRole_UnsupportedType() {
|
||||
RoleDTO roleDTO = RoleDTO.builder()
|
||||
.id(ROLE_ID)
|
||||
.name(ROLE_NAME)
|
||||
.build();
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () ->
|
||||
roleService.updateRole(ROLE_ID, roleDTO, REALM, null, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteRole_ClientRole_Success() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.clients()).thenReturn(clientsResource);
|
||||
|
||||
ClientRepresentation client = new ClientRepresentation();
|
||||
client.setId(INTERNAL_CLIENT_ID);
|
||||
when(clientsResource.findByClientId(CLIENT_NAME)).thenReturn(List.of(client));
|
||||
when(clientsResource.get(INTERNAL_CLIENT_ID)).thenReturn(clientResource);
|
||||
when(clientResource.roles()).thenReturn(rolesResource);
|
||||
|
||||
// Mock getRoleById - getRoleById for CLIENT_ROLE only uses rolesResource.list()
|
||||
RoleRepresentation roleRep = new RoleRepresentation();
|
||||
roleRep.setId(ROLE_ID);
|
||||
roleRep.setName(ROLE_NAME);
|
||||
when(rolesResource.list()).thenReturn(List.of(roleRep));
|
||||
|
||||
roleService.deleteRole(ROLE_ID, REALM, TypeRole.CLIENT_ROLE, CLIENT_NAME);
|
||||
|
||||
verify(rolesResource).deleteRole(ROLE_NAME);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteRole_ClientRole_ClientNotFound() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.clients()).thenReturn(clientsResource);
|
||||
when(clientsResource.findByClientId(CLIENT_NAME)).thenReturn(Collections.emptyList());
|
||||
|
||||
// getRoleById is called first, which returns Optional.empty() when client is not found
|
||||
// So it will throw NotFoundException for role not found
|
||||
assertThrows(jakarta.ws.rs.NotFoundException.class, () ->
|
||||
roleService.deleteRole(ROLE_ID, REALM, TypeRole.CLIENT_ROLE, CLIENT_NAME));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteRole_ClientRole_NotFound() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.clients()).thenReturn(clientsResource);
|
||||
|
||||
ClientRepresentation client = new ClientRepresentation();
|
||||
client.setId(INTERNAL_CLIENT_ID);
|
||||
when(clientsResource.findByClientId(CLIENT_NAME)).thenReturn(List.of(client));
|
||||
when(clientsResource.get(INTERNAL_CLIENT_ID)).thenReturn(clientResource);
|
||||
when(clientResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.list()).thenReturn(Collections.emptyList());
|
||||
|
||||
assertThrows(jakarta.ws.rs.NotFoundException.class, () ->
|
||||
roleService.deleteRole(ROLE_ID, REALM, TypeRole.CLIENT_ROLE, CLIENT_NAME));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteRole_UnsupportedType() {
|
||||
assertThrows(IllegalArgumentException.class, () ->
|
||||
roleService.deleteRole(ROLE_ID, REALM, null, null));
|
||||
}
|
||||
|
||||
// Note: getRealmRoleById is private, so we test it indirectly through updateRole
|
||||
// The exception path is tested via updateRole_RealmRole_NotFound
|
||||
|
||||
@Test
|
||||
void testGetAllRealmRoles_Success() {
|
||||
when(keycloakAdminClient.realmExists(REALM)).thenReturn(true);
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
|
||||
RoleRepresentation role1 = new RoleRepresentation();
|
||||
role1.setName("role1");
|
||||
RoleRepresentation role2 = new RoleRepresentation();
|
||||
role2.setName("role2");
|
||||
when(rolesResource.list()).thenReturn(List.of(role1, role2));
|
||||
|
||||
var result = roleService.getAllRealmRoles(REALM);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(2, result.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealmRoles_With404InMessage() {
|
||||
when(keycloakAdminClient.realmExists(REALM)).thenReturn(true);
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.list()).thenThrow(new RuntimeException("Server response is: 404"));
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () ->
|
||||
roleService.getAllRealmRoles(REALM));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealmRoles_WithNotInMessage() {
|
||||
when(keycloakAdminClient.realmExists(REALM)).thenReturn(true);
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.list()).thenThrow(new RuntimeException("Not Found"));
|
||||
|
||||
assertThrows(IllegalArgumentException.class, () ->
|
||||
roleService.getAllRealmRoles(REALM));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetAllRealmRoles_WithOtherException() {
|
||||
when(keycloakAdminClient.realmExists(REALM)).thenReturn(true);
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.list()).thenThrow(new RuntimeException("Connection error"));
|
||||
|
||||
assertThrows(RuntimeException.class, () ->
|
||||
roleService.getAllRealmRoles(REALM));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,245 +1,245 @@
|
||||
package dev.lions.user.manager.service.impl;
|
||||
|
||||
import dev.lions.user.manager.client.KeycloakAdminClient;
|
||||
import dev.lions.user.manager.dto.role.RoleDTO;
|
||||
import dev.lions.user.manager.enums.role.TypeRole;
|
||||
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.*;
|
||||
import org.keycloak.representations.idm.ClientRepresentation;
|
||||
import org.keycloak.representations.idm.RoleRepresentation;
|
||||
import org.keycloak.representations.idm.UserRepresentation;
|
||||
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.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* Tests supplémentaires pour RoleServiceImpl pour améliorer la couverture
|
||||
* Couvre les méthodes : userHasRole, roleExists, countUsersWithRole
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class RoleServiceImplExtendedTest {
|
||||
|
||||
@Mock
|
||||
private KeycloakAdminClient keycloakAdminClient;
|
||||
|
||||
@Mock
|
||||
private Keycloak keycloakInstance;
|
||||
|
||||
@Mock
|
||||
private RealmResource realmResource;
|
||||
|
||||
@Mock
|
||||
private RolesResource rolesResource;
|
||||
|
||||
@Mock
|
||||
private RoleResource roleResource;
|
||||
|
||||
@Mock
|
||||
private UsersResource usersResource;
|
||||
|
||||
@Mock
|
||||
private UserResource userResource;
|
||||
|
||||
@Mock
|
||||
private RoleMappingResource roleMappingResource;
|
||||
|
||||
@Mock
|
||||
private RoleScopeResource realmLevelRoleScopeResource;
|
||||
|
||||
@Mock
|
||||
private RoleScopeResource clientLevelRoleScopeResource;
|
||||
|
||||
@Mock
|
||||
private ClientsResource clientsResource;
|
||||
|
||||
@InjectMocks
|
||||
private RoleServiceImpl roleService;
|
||||
|
||||
private static final String REALM = "test-realm";
|
||||
private static final String USER_ID = "user-123";
|
||||
private static final String ROLE_NAME = "admin";
|
||||
private static final String CLIENT_NAME = "test-client";
|
||||
|
||||
@Test
|
||||
void testUserHasRole_RealmRole_True() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
when(usersResource.get(USER_ID)).thenReturn(userResource);
|
||||
when(userResource.roles()).thenReturn(roleMappingResource);
|
||||
when(roleMappingResource.realmLevel()).thenReturn(realmLevelRoleScopeResource);
|
||||
|
||||
RoleRepresentation role = new RoleRepresentation();
|
||||
role.setName(ROLE_NAME);
|
||||
when(realmLevelRoleScopeResource.listEffective()).thenReturn(List.of(role));
|
||||
|
||||
boolean result = roleService.userHasRole(USER_ID, ROLE_NAME, REALM, TypeRole.REALM_ROLE, null);
|
||||
|
||||
assertTrue(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUserHasRole_RealmRole_False() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
when(usersResource.get(USER_ID)).thenReturn(userResource);
|
||||
when(userResource.roles()).thenReturn(roleMappingResource);
|
||||
when(roleMappingResource.realmLevel()).thenReturn(realmLevelRoleScopeResource);
|
||||
when(realmLevelRoleScopeResource.listEffective()).thenReturn(Collections.emptyList());
|
||||
|
||||
boolean result = roleService.userHasRole(USER_ID, ROLE_NAME, REALM, TypeRole.REALM_ROLE, null);
|
||||
|
||||
assertFalse(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUserHasRole_ClientRole_True() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.clients()).thenReturn(clientsResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
when(usersResource.get(USER_ID)).thenReturn(userResource);
|
||||
when(userResource.roles()).thenReturn(roleMappingResource);
|
||||
|
||||
ClientRepresentation client = new ClientRepresentation();
|
||||
client.setId("client-123");
|
||||
when(clientsResource.findByClientId(CLIENT_NAME)).thenReturn(List.of(client));
|
||||
when(roleMappingResource.clientLevel("client-123")).thenReturn(clientLevelRoleScopeResource);
|
||||
|
||||
RoleRepresentation role = new RoleRepresentation();
|
||||
role.setName(ROLE_NAME);
|
||||
when(clientLevelRoleScopeResource.listEffective()).thenReturn(List.of(role));
|
||||
|
||||
boolean result = roleService.userHasRole(USER_ID, ROLE_NAME, REALM, TypeRole.CLIENT_ROLE, CLIENT_NAME);
|
||||
|
||||
assertTrue(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUserHasRole_ClientRole_ClientNotFound() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.clients()).thenReturn(clientsResource);
|
||||
when(clientsResource.findByClientId(CLIENT_NAME)).thenReturn(Collections.emptyList());
|
||||
|
||||
boolean result = roleService.userHasRole(USER_ID, ROLE_NAME, REALM, TypeRole.CLIENT_ROLE, CLIENT_NAME);
|
||||
|
||||
assertFalse(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUserHasRole_ClientRole_NullClientName() {
|
||||
boolean result = roleService.userHasRole(USER_ID, ROLE_NAME, REALM, TypeRole.CLIENT_ROLE, null);
|
||||
|
||||
assertFalse(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRoleExists_RealmRole_True() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.get(ROLE_NAME)).thenReturn(roleResource);
|
||||
|
||||
RoleRepresentation role = new RoleRepresentation();
|
||||
role.setName(ROLE_NAME);
|
||||
when(roleResource.toRepresentation()).thenReturn(role);
|
||||
|
||||
boolean result = roleService.roleExists(ROLE_NAME, REALM, TypeRole.REALM_ROLE, null);
|
||||
|
||||
assertTrue(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRoleExists_RealmRole_False() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.get(ROLE_NAME)).thenReturn(roleResource);
|
||||
when(roleResource.toRepresentation()).thenThrow(new jakarta.ws.rs.NotFoundException());
|
||||
|
||||
boolean result = roleService.roleExists(ROLE_NAME, REALM, TypeRole.REALM_ROLE, null);
|
||||
|
||||
assertFalse(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCountUsersWithRole_Success() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
|
||||
// Mock getRoleById
|
||||
RoleRepresentation roleRep = new RoleRepresentation();
|
||||
roleRep.setId("role-123");
|
||||
roleRep.setName(ROLE_NAME);
|
||||
when(rolesResource.list()).thenReturn(List.of(roleRep));
|
||||
|
||||
// Mock user list
|
||||
UserRepresentation user1 = new UserRepresentation();
|
||||
user1.setId("user-1");
|
||||
UserRepresentation user2 = new UserRepresentation();
|
||||
user2.setId("user-2");
|
||||
when(usersResource.list()).thenReturn(List.of(user1, user2));
|
||||
|
||||
// Mock userHasRole for each user
|
||||
when(usersResource.get("user-1")).thenReturn(userResource);
|
||||
when(usersResource.get("user-2")).thenReturn(userResource);
|
||||
when(userResource.roles()).thenReturn(roleMappingResource);
|
||||
when(roleMappingResource.realmLevel()).thenReturn(realmLevelRoleScopeResource);
|
||||
|
||||
RoleRepresentation role = new RoleRepresentation();
|
||||
role.setName(ROLE_NAME);
|
||||
// User 1 has role, user 2 doesn't
|
||||
when(realmLevelRoleScopeResource.listEffective())
|
||||
.thenReturn(List.of(role)) // user-1
|
||||
.thenReturn(Collections.emptyList()); // user-2
|
||||
|
||||
long count = roleService.countUsersWithRole("role-123", REALM, TypeRole.REALM_ROLE, null);
|
||||
|
||||
assertEquals(1, count);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCountUsersWithRole_RoleNotFound() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.list()).thenReturn(Collections.emptyList());
|
||||
|
||||
long count = roleService.countUsersWithRole("non-existent-role", REALM, TypeRole.REALM_ROLE, null);
|
||||
|
||||
assertEquals(0, count);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCountUsersWithRole_Exception() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
|
||||
RoleRepresentation roleRep = new RoleRepresentation();
|
||||
roleRep.setId("role-123");
|
||||
roleRep.setName(ROLE_NAME);
|
||||
when(rolesResource.list()).thenReturn(List.of(roleRep));
|
||||
when(usersResource.list()).thenThrow(new RuntimeException("Error"));
|
||||
|
||||
long count = roleService.countUsersWithRole("role-123", REALM, TypeRole.REALM_ROLE, null);
|
||||
|
||||
assertEquals(0, count);
|
||||
}
|
||||
}
|
||||
|
||||
package dev.lions.user.manager.service.impl;
|
||||
|
||||
import dev.lions.user.manager.client.KeycloakAdminClient;
|
||||
import dev.lions.user.manager.dto.role.RoleDTO;
|
||||
import dev.lions.user.manager.enums.role.TypeRole;
|
||||
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.*;
|
||||
import org.keycloak.representations.idm.ClientRepresentation;
|
||||
import org.keycloak.representations.idm.RoleRepresentation;
|
||||
import org.keycloak.representations.idm.UserRepresentation;
|
||||
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.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* Tests supplémentaires pour RoleServiceImpl pour améliorer la couverture
|
||||
* Couvre les méthodes : userHasRole, roleExists, countUsersWithRole
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class RoleServiceImplExtendedTest {
|
||||
|
||||
@Mock
|
||||
private KeycloakAdminClient keycloakAdminClient;
|
||||
|
||||
@Mock
|
||||
private Keycloak keycloakInstance;
|
||||
|
||||
@Mock
|
||||
private RealmResource realmResource;
|
||||
|
||||
@Mock
|
||||
private RolesResource rolesResource;
|
||||
|
||||
@Mock
|
||||
private RoleResource roleResource;
|
||||
|
||||
@Mock
|
||||
private UsersResource usersResource;
|
||||
|
||||
@Mock
|
||||
private UserResource userResource;
|
||||
|
||||
@Mock
|
||||
private RoleMappingResource roleMappingResource;
|
||||
|
||||
@Mock
|
||||
private RoleScopeResource realmLevelRoleScopeResource;
|
||||
|
||||
@Mock
|
||||
private RoleScopeResource clientLevelRoleScopeResource;
|
||||
|
||||
@Mock
|
||||
private ClientsResource clientsResource;
|
||||
|
||||
@InjectMocks
|
||||
private RoleServiceImpl roleService;
|
||||
|
||||
private static final String REALM = "test-realm";
|
||||
private static final String USER_ID = "user-123";
|
||||
private static final String ROLE_NAME = "admin";
|
||||
private static final String CLIENT_NAME = "test-client";
|
||||
|
||||
@Test
|
||||
void testUserHasRole_RealmRole_True() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
when(usersResource.get(USER_ID)).thenReturn(userResource);
|
||||
when(userResource.roles()).thenReturn(roleMappingResource);
|
||||
when(roleMappingResource.realmLevel()).thenReturn(realmLevelRoleScopeResource);
|
||||
|
||||
RoleRepresentation role = new RoleRepresentation();
|
||||
role.setName(ROLE_NAME);
|
||||
when(realmLevelRoleScopeResource.listEffective()).thenReturn(List.of(role));
|
||||
|
||||
boolean result = roleService.userHasRole(USER_ID, ROLE_NAME, REALM, TypeRole.REALM_ROLE, null);
|
||||
|
||||
assertTrue(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUserHasRole_RealmRole_False() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
when(usersResource.get(USER_ID)).thenReturn(userResource);
|
||||
when(userResource.roles()).thenReturn(roleMappingResource);
|
||||
when(roleMappingResource.realmLevel()).thenReturn(realmLevelRoleScopeResource);
|
||||
when(realmLevelRoleScopeResource.listEffective()).thenReturn(Collections.emptyList());
|
||||
|
||||
boolean result = roleService.userHasRole(USER_ID, ROLE_NAME, REALM, TypeRole.REALM_ROLE, null);
|
||||
|
||||
assertFalse(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUserHasRole_ClientRole_True() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.clients()).thenReturn(clientsResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
when(usersResource.get(USER_ID)).thenReturn(userResource);
|
||||
when(userResource.roles()).thenReturn(roleMappingResource);
|
||||
|
||||
ClientRepresentation client = new ClientRepresentation();
|
||||
client.setId("client-123");
|
||||
when(clientsResource.findByClientId(CLIENT_NAME)).thenReturn(List.of(client));
|
||||
when(roleMappingResource.clientLevel("client-123")).thenReturn(clientLevelRoleScopeResource);
|
||||
|
||||
RoleRepresentation role = new RoleRepresentation();
|
||||
role.setName(ROLE_NAME);
|
||||
when(clientLevelRoleScopeResource.listEffective()).thenReturn(List.of(role));
|
||||
|
||||
boolean result = roleService.userHasRole(USER_ID, ROLE_NAME, REALM, TypeRole.CLIENT_ROLE, CLIENT_NAME);
|
||||
|
||||
assertTrue(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUserHasRole_ClientRole_ClientNotFound() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.clients()).thenReturn(clientsResource);
|
||||
when(clientsResource.findByClientId(CLIENT_NAME)).thenReturn(Collections.emptyList());
|
||||
|
||||
boolean result = roleService.userHasRole(USER_ID, ROLE_NAME, REALM, TypeRole.CLIENT_ROLE, CLIENT_NAME);
|
||||
|
||||
assertFalse(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testUserHasRole_ClientRole_NullClientName() {
|
||||
boolean result = roleService.userHasRole(USER_ID, ROLE_NAME, REALM, TypeRole.CLIENT_ROLE, null);
|
||||
|
||||
assertFalse(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRoleExists_RealmRole_True() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.get(ROLE_NAME)).thenReturn(roleResource);
|
||||
|
||||
RoleRepresentation role = new RoleRepresentation();
|
||||
role.setName(ROLE_NAME);
|
||||
when(roleResource.toRepresentation()).thenReturn(role);
|
||||
|
||||
boolean result = roleService.roleExists(ROLE_NAME, REALM, TypeRole.REALM_ROLE, null);
|
||||
|
||||
assertTrue(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testRoleExists_RealmRole_False() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.get(ROLE_NAME)).thenReturn(roleResource);
|
||||
when(roleResource.toRepresentation()).thenThrow(new jakarta.ws.rs.NotFoundException());
|
||||
|
||||
boolean result = roleService.roleExists(ROLE_NAME, REALM, TypeRole.REALM_ROLE, null);
|
||||
|
||||
assertFalse(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCountUsersWithRole_Success() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
|
||||
// Mock getRoleById
|
||||
RoleRepresentation roleRep = new RoleRepresentation();
|
||||
roleRep.setId("role-123");
|
||||
roleRep.setName(ROLE_NAME);
|
||||
when(rolesResource.list()).thenReturn(List.of(roleRep));
|
||||
|
||||
// Mock user list
|
||||
UserRepresentation user1 = new UserRepresentation();
|
||||
user1.setId("user-1");
|
||||
UserRepresentation user2 = new UserRepresentation();
|
||||
user2.setId("user-2");
|
||||
when(usersResource.list()).thenReturn(List.of(user1, user2));
|
||||
|
||||
// Mock userHasRole for each user
|
||||
when(usersResource.get("user-1")).thenReturn(userResource);
|
||||
when(usersResource.get("user-2")).thenReturn(userResource);
|
||||
when(userResource.roles()).thenReturn(roleMappingResource);
|
||||
when(roleMappingResource.realmLevel()).thenReturn(realmLevelRoleScopeResource);
|
||||
|
||||
RoleRepresentation role = new RoleRepresentation();
|
||||
role.setName(ROLE_NAME);
|
||||
// User 1 has role, user 2 doesn't
|
||||
when(realmLevelRoleScopeResource.listEffective())
|
||||
.thenReturn(List.of(role)) // user-1
|
||||
.thenReturn(Collections.emptyList()); // user-2
|
||||
|
||||
long count = roleService.countUsersWithRole("role-123", REALM, TypeRole.REALM_ROLE, null);
|
||||
|
||||
assertEquals(1, count);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCountUsersWithRole_RoleNotFound() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.list()).thenReturn(Collections.emptyList());
|
||||
|
||||
long count = roleService.countUsersWithRole("non-existent-role", REALM, TypeRole.REALM_ROLE, null);
|
||||
|
||||
assertEquals(0, count);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCountUsersWithRole_Exception() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
|
||||
RoleRepresentation roleRep = new RoleRepresentation();
|
||||
roleRep.setId("role-123");
|
||||
roleRep.setName(ROLE_NAME);
|
||||
when(rolesResource.list()).thenReturn(List.of(roleRep));
|
||||
when(usersResource.list()).thenThrow(new RuntimeException("Error"));
|
||||
|
||||
long count = roleService.countUsersWithRole("role-123", REALM, TypeRole.REALM_ROLE, null);
|
||||
|
||||
assertEquals(0, count);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,128 +1,128 @@
|
||||
package dev.lions.user.manager.service.impl;
|
||||
|
||||
import dev.lions.user.manager.client.KeycloakAdminClient;
|
||||
import dev.lions.user.manager.dto.role.RoleAssignmentDTO;
|
||||
import dev.lions.user.manager.dto.role.RoleDTO;
|
||||
import dev.lions.user.manager.enums.role.TypeRole;
|
||||
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.*;
|
||||
import org.keycloak.representations.idm.RoleRepresentation;
|
||||
import org.keycloak.representations.idm.UserRepresentation;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class RoleServiceImplTest {
|
||||
|
||||
@Mock
|
||||
KeycloakAdminClient keycloakAdminClient;
|
||||
|
||||
@Mock
|
||||
Keycloak keycloakInstance;
|
||||
|
||||
@Mock
|
||||
RealmResource realmResource;
|
||||
|
||||
@Mock
|
||||
RolesResource rolesResource;
|
||||
|
||||
@Mock
|
||||
RoleResource roleResource;
|
||||
|
||||
@Mock
|
||||
UsersResource usersResource;
|
||||
|
||||
@Mock
|
||||
UserResource userResource;
|
||||
|
||||
@Mock
|
||||
RoleMappingResource roleMappingResource;
|
||||
|
||||
@Mock
|
||||
RoleScopeResource roleScopeResource;
|
||||
|
||||
@InjectMocks
|
||||
RoleServiceImpl roleService;
|
||||
|
||||
private static final String REALM = "test-realm";
|
||||
|
||||
@Test
|
||||
void testCreateRealmRole() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
|
||||
// Check not found initially, then return created role
|
||||
RoleRepresentation createdRep = new RoleRepresentation();
|
||||
createdRep.setName("role");
|
||||
createdRep.setId("1");
|
||||
when(rolesResource.get("role")).thenReturn(roleResource);
|
||||
when(roleResource.toRepresentation()).thenThrow(new jakarta.ws.rs.NotFoundException())
|
||||
.thenReturn(createdRep);
|
||||
|
||||
// Mock create
|
||||
doNothing().when(rolesResource).create(any(RoleRepresentation.class));
|
||||
|
||||
RoleDTO input = RoleDTO.builder().name("role").description("desc").build();
|
||||
|
||||
RoleDTO result = roleService.createRealmRole(input, REALM);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals("role", result.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteRole() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
|
||||
// find by id logic uses list()
|
||||
RoleRepresentation rep = new RoleRepresentation();
|
||||
rep.setId("1");
|
||||
rep.setName("role");
|
||||
when(rolesResource.list()).thenReturn(Collections.singletonList(rep));
|
||||
|
||||
roleService.deleteRole("1", REALM, TypeRole.REALM_ROLE, null);
|
||||
|
||||
verify(rolesResource).deleteRole("role");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAssignRolesToUser() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
when(usersResource.get("u1")).thenReturn(userResource);
|
||||
when(userResource.roles()).thenReturn(roleMappingResource);
|
||||
when(roleMappingResource.realmLevel()).thenReturn(roleScopeResource);
|
||||
|
||||
RoleRepresentation roleRep = new RoleRepresentation();
|
||||
roleRep.setName("role1");
|
||||
when(rolesResource.get("role1")).thenReturn(roleResource);
|
||||
when(roleResource.toRepresentation()).thenReturn(roleRep);
|
||||
|
||||
RoleAssignmentDTO assignment = RoleAssignmentDTO.builder()
|
||||
.userId("u1")
|
||||
.realmName(REALM)
|
||||
.typeRole(TypeRole.REALM_ROLE)
|
||||
.roleNames(Collections.singletonList("role1"))
|
||||
.build();
|
||||
|
||||
roleService.assignRolesToUser(assignment);
|
||||
|
||||
verify(roleScopeResource).add(anyList());
|
||||
}
|
||||
}
|
||||
package dev.lions.user.manager.service.impl;
|
||||
|
||||
import dev.lions.user.manager.client.KeycloakAdminClient;
|
||||
import dev.lions.user.manager.dto.role.RoleAssignmentDTO;
|
||||
import dev.lions.user.manager.dto.role.RoleDTO;
|
||||
import dev.lions.user.manager.enums.role.TypeRole;
|
||||
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.*;
|
||||
import org.keycloak.representations.idm.RoleRepresentation;
|
||||
import org.keycloak.representations.idm.UserRepresentation;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class RoleServiceImplTest {
|
||||
|
||||
@Mock
|
||||
KeycloakAdminClient keycloakAdminClient;
|
||||
|
||||
@Mock
|
||||
Keycloak keycloakInstance;
|
||||
|
||||
@Mock
|
||||
RealmResource realmResource;
|
||||
|
||||
@Mock
|
||||
RolesResource rolesResource;
|
||||
|
||||
@Mock
|
||||
RoleResource roleResource;
|
||||
|
||||
@Mock
|
||||
UsersResource usersResource;
|
||||
|
||||
@Mock
|
||||
UserResource userResource;
|
||||
|
||||
@Mock
|
||||
RoleMappingResource roleMappingResource;
|
||||
|
||||
@Mock
|
||||
RoleScopeResource roleScopeResource;
|
||||
|
||||
@InjectMocks
|
||||
RoleServiceImpl roleService;
|
||||
|
||||
private static final String REALM = "test-realm";
|
||||
|
||||
@Test
|
||||
void testCreateRealmRole() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
|
||||
// Check not found initially, then return created role
|
||||
RoleRepresentation createdRep = new RoleRepresentation();
|
||||
createdRep.setName("role");
|
||||
createdRep.setId("1");
|
||||
when(rolesResource.get("role")).thenReturn(roleResource);
|
||||
when(roleResource.toRepresentation()).thenThrow(new jakarta.ws.rs.NotFoundException())
|
||||
.thenReturn(createdRep);
|
||||
|
||||
// Mock create
|
||||
doNothing().when(rolesResource).create(any(RoleRepresentation.class));
|
||||
|
||||
RoleDTO input = RoleDTO.builder().name("role").description("desc").build();
|
||||
|
||||
RoleDTO result = roleService.createRealmRole(input, REALM);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals("role", result.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testDeleteRole() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
|
||||
// find by id logic uses list()
|
||||
RoleRepresentation rep = new RoleRepresentation();
|
||||
rep.setId("1");
|
||||
rep.setName("role");
|
||||
when(rolesResource.list()).thenReturn(Collections.singletonList(rep));
|
||||
|
||||
roleService.deleteRole("1", REALM, TypeRole.REALM_ROLE, null);
|
||||
|
||||
verify(rolesResource).deleteRole("role");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testAssignRolesToUser() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm(REALM)).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
when(usersResource.get("u1")).thenReturn(userResource);
|
||||
when(userResource.roles()).thenReturn(roleMappingResource);
|
||||
when(roleMappingResource.realmLevel()).thenReturn(roleScopeResource);
|
||||
|
||||
RoleRepresentation roleRep = new RoleRepresentation();
|
||||
roleRep.setName("role1");
|
||||
when(rolesResource.get("role1")).thenReturn(roleResource);
|
||||
when(roleResource.toRepresentation()).thenReturn(roleRep);
|
||||
|
||||
RoleAssignmentDTO assignment = RoleAssignmentDTO.builder()
|
||||
.userId("u1")
|
||||
.realmName(REALM)
|
||||
.typeRole(TypeRole.REALM_ROLE)
|
||||
.roleNames(Collections.singletonList("role1"))
|
||||
.build();
|
||||
|
||||
roleService.assignRolesToUser(assignment);
|
||||
|
||||
verify(roleScopeResource).add(anyList());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,244 +1,244 @@
|
||||
package dev.lions.user.manager.service.impl;
|
||||
|
||||
import dev.lions.user.manager.client.KeycloakAdminClient;
|
||||
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.*;
|
||||
import org.keycloak.representations.idm.RealmRepresentation;
|
||||
import org.keycloak.representations.idm.RoleRepresentation;
|
||||
import org.keycloak.representations.idm.UserRepresentation;
|
||||
import org.keycloak.representations.info.ServerInfoRepresentation;
|
||||
import org.keycloak.representations.info.SystemInfoRepresentation; // Correct import
|
||||
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.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
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
|
||||
KeycloakAdminClient keycloakAdminClient;
|
||||
|
||||
@Mock
|
||||
Keycloak keycloakInstance;
|
||||
|
||||
@Mock
|
||||
RealmsResource realmsResource;
|
||||
|
||||
@Mock
|
||||
RealmResource realmResource;
|
||||
|
||||
@Mock
|
||||
UsersResource usersResource;
|
||||
|
||||
@Mock
|
||||
RolesResource rolesResource;
|
||||
|
||||
@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;
|
||||
|
||||
// Correcting inner class usage if needed, but assuming standard Keycloak
|
||||
// representations
|
||||
// ServerInfoRepresentation contains SystemInfoRepresentation
|
||||
|
||||
@Test
|
||||
void testSyncUsersFromRealm() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm("realm")).thenReturn(realmResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
when(usersResource.list()).thenReturn(Collections.singletonList(new UserRepresentation()));
|
||||
|
||||
int count = syncService.syncUsersFromRealm("realm");
|
||||
assertEquals(1, count);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSyncRolesFromRealm() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm("realm")).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.list()).thenReturn(Collections.singletonList(new RoleRepresentation()));
|
||||
|
||||
int count = syncService.syncRolesFromRealm("realm");
|
||||
assertEquals(1, count);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSyncAllRealms() {
|
||||
when(keycloakAdminClient.getAllRealms()).thenReturn(Collections.singletonList("realm1"));
|
||||
|
||||
when(keycloakInstance.realm("realm1")).thenReturn(realmResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
when(usersResource.list()).thenReturn(Collections.emptyList());
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.list()).thenReturn(Collections.emptyList());
|
||||
|
||||
Map<String, Integer> result = syncService.syncAllRealms();
|
||||
assertTrue(result.containsKey("realm1"));
|
||||
assertEquals(0, result.get("realm1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsKeycloakAvailable() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.serverInfo()).thenReturn(serverInfoResource);
|
||||
when(serverInfoResource.getInfo()).thenReturn(new ServerInfoRepresentation());
|
||||
|
||||
assertTrue(syncService.isKeycloakAvailable());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetKeycloakHealthInfo() {
|
||||
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);
|
||||
|
||||
Map<String, Object> health = syncService.getKeycloakHealthInfo();
|
||||
assertEquals("UP", health.get("status"));
|
||||
assertEquals("1.0", health.get("version"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSyncUsersFromRealm_Exception() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm("realm")).thenReturn(realmResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
when(usersResource.list()).thenThrow(new RuntimeException("Connection error"));
|
||||
|
||||
assertThrows(RuntimeException.class, () -> syncService.syncUsersFromRealm("realm"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSyncRolesFromRealm_Exception() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm("realm")).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.list()).thenThrow(new RuntimeException("Connection error"));
|
||||
|
||||
assertThrows(RuntimeException.class, () -> syncService.syncRolesFromRealm("realm"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSyncAllRealms_WithException() {
|
||||
when(keycloakAdminClient.getAllRealms()).thenReturn(Collections.singletonList("realm1"));
|
||||
|
||||
when(keycloakInstance.realm("realm1")).thenReturn(realmResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
when(usersResource.list()).thenThrow(new RuntimeException("Sync error"));
|
||||
|
||||
Map<String, Integer> result = syncService.syncAllRealms();
|
||||
assertTrue(result.containsKey("realm1"));
|
||||
assertEquals(0, result.get("realm1")); // Should be 0 on error
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSyncAllRealms_ExceptionInFindAll() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.findAll()).thenThrow(new RuntimeException("Connection error"));
|
||||
|
||||
Map<String, Integer> result = syncService.syncAllRealms();
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
// 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
|
||||
|
||||
@Test
|
||||
void testForceSyncRealm_Exception() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm("realm")).thenReturn(realmResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
when(usersResource.list()).thenThrow(new RuntimeException("Sync error"));
|
||||
|
||||
Map<String, Object> stats = syncService.forceSyncRealm("realm");
|
||||
assertEquals("FAILURE", stats.get("status"));
|
||||
assertNotNull(stats.get("error"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsKeycloakAvailable_Exception() {
|
||||
when(keycloakAdminClient.getAllRealms()).thenThrow(new RuntimeException("Connection refused"));
|
||||
|
||||
assertFalse(syncService.isKeycloakAvailable());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetKeycloakHealthInfo_Exception() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.serverInfo()).thenReturn(serverInfoResource);
|
||||
when(serverInfoResource.getInfo()).thenThrow(new RuntimeException("Connection error"));
|
||||
|
||||
Map<String, Object> health = syncService.getKeycloakHealthInfo();
|
||||
assertNotNull(health);
|
||||
// Either status=DOWN (HTTP fallback also fails) or status=UP (HTTP fallback succeeds)
|
||||
assertNotNull(health.get("status"));
|
||||
}
|
||||
|
||||
@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"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetLastSyncStatus() {
|
||||
dev.lions.user.manager.server.impl.entity.SyncHistoryEntity entity =
|
||||
new dev.lions.user.manager.server.impl.entity.SyncHistoryEntity();
|
||||
entity.setStatus("completed");
|
||||
entity.setSyncType("USER");
|
||||
entity.setItemsProcessed(5);
|
||||
entity.setSyncDate(java.time.LocalDateTime.now());
|
||||
when(syncHistoryRepository.findLatestByRealm(eq("realm"), eq(1)))
|
||||
.thenReturn(Collections.singletonList(entity));
|
||||
|
||||
Map<String, Object> status = syncService.getLastSyncStatus("realm");
|
||||
assertEquals("completed", status.get("status"));
|
||||
assertNotNull(status.get("lastSyncDate"));
|
||||
}
|
||||
}
|
||||
package dev.lions.user.manager.service.impl;
|
||||
|
||||
import dev.lions.user.manager.client.KeycloakAdminClient;
|
||||
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.*;
|
||||
import org.keycloak.representations.idm.RealmRepresentation;
|
||||
import org.keycloak.representations.idm.RoleRepresentation;
|
||||
import org.keycloak.representations.idm.UserRepresentation;
|
||||
import org.keycloak.representations.info.ServerInfoRepresentation;
|
||||
import org.keycloak.representations.info.SystemInfoRepresentation; // Correct import
|
||||
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.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
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
|
||||
KeycloakAdminClient keycloakAdminClient;
|
||||
|
||||
@Mock
|
||||
Keycloak keycloakInstance;
|
||||
|
||||
@Mock
|
||||
RealmsResource realmsResource;
|
||||
|
||||
@Mock
|
||||
RealmResource realmResource;
|
||||
|
||||
@Mock
|
||||
UsersResource usersResource;
|
||||
|
||||
@Mock
|
||||
RolesResource rolesResource;
|
||||
|
||||
@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;
|
||||
|
||||
// Correcting inner class usage if needed, but assuming standard Keycloak
|
||||
// representations
|
||||
// ServerInfoRepresentation contains SystemInfoRepresentation
|
||||
|
||||
@Test
|
||||
void testSyncUsersFromRealm() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm("realm")).thenReturn(realmResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
when(usersResource.list()).thenReturn(Collections.singletonList(new UserRepresentation()));
|
||||
|
||||
int count = syncService.syncUsersFromRealm("realm");
|
||||
assertEquals(1, count);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSyncRolesFromRealm() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm("realm")).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.list()).thenReturn(Collections.singletonList(new RoleRepresentation()));
|
||||
|
||||
int count = syncService.syncRolesFromRealm("realm");
|
||||
assertEquals(1, count);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSyncAllRealms() {
|
||||
when(keycloakAdminClient.getAllRealms()).thenReturn(Collections.singletonList("realm1"));
|
||||
|
||||
when(keycloakInstance.realm("realm1")).thenReturn(realmResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
when(usersResource.list()).thenReturn(Collections.emptyList());
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.list()).thenReturn(Collections.emptyList());
|
||||
|
||||
Map<String, Integer> result = syncService.syncAllRealms();
|
||||
assertTrue(result.containsKey("realm1"));
|
||||
assertEquals(0, result.get("realm1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsKeycloakAvailable() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.serverInfo()).thenReturn(serverInfoResource);
|
||||
when(serverInfoResource.getInfo()).thenReturn(new ServerInfoRepresentation());
|
||||
|
||||
assertTrue(syncService.isKeycloakAvailable());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetKeycloakHealthInfo() {
|
||||
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);
|
||||
|
||||
Map<String, Object> health = syncService.getKeycloakHealthInfo();
|
||||
assertEquals("UP", health.get("status"));
|
||||
assertEquals("1.0", health.get("version"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSyncUsersFromRealm_Exception() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm("realm")).thenReturn(realmResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
when(usersResource.list()).thenThrow(new RuntimeException("Connection error"));
|
||||
|
||||
assertThrows(RuntimeException.class, () -> syncService.syncUsersFromRealm("realm"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSyncRolesFromRealm_Exception() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm("realm")).thenReturn(realmResource);
|
||||
when(realmResource.roles()).thenReturn(rolesResource);
|
||||
when(rolesResource.list()).thenThrow(new RuntimeException("Connection error"));
|
||||
|
||||
assertThrows(RuntimeException.class, () -> syncService.syncRolesFromRealm("realm"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSyncAllRealms_WithException() {
|
||||
when(keycloakAdminClient.getAllRealms()).thenReturn(Collections.singletonList("realm1"));
|
||||
|
||||
when(keycloakInstance.realm("realm1")).thenReturn(realmResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
when(usersResource.list()).thenThrow(new RuntimeException("Sync error"));
|
||||
|
||||
Map<String, Integer> result = syncService.syncAllRealms();
|
||||
assertTrue(result.containsKey("realm1"));
|
||||
assertEquals(0, result.get("realm1")); // Should be 0 on error
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSyncAllRealms_ExceptionInFindAll() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realms()).thenReturn(realmsResource);
|
||||
when(realmsResource.findAll()).thenThrow(new RuntimeException("Connection error"));
|
||||
|
||||
Map<String, Integer> result = syncService.syncAllRealms();
|
||||
assertTrue(result.isEmpty());
|
||||
}
|
||||
|
||||
// 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
|
||||
|
||||
@Test
|
||||
void testForceSyncRealm_Exception() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.realm("realm")).thenReturn(realmResource);
|
||||
when(realmResource.users()).thenReturn(usersResource);
|
||||
when(usersResource.list()).thenThrow(new RuntimeException("Sync error"));
|
||||
|
||||
Map<String, Object> stats = syncService.forceSyncRealm("realm");
|
||||
assertEquals("FAILURE", stats.get("status"));
|
||||
assertNotNull(stats.get("error"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testIsKeycloakAvailable_Exception() {
|
||||
when(keycloakAdminClient.getAllRealms()).thenThrow(new RuntimeException("Connection refused"));
|
||||
|
||||
assertFalse(syncService.isKeycloakAvailable());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetKeycloakHealthInfo_Exception() {
|
||||
when(keycloakAdminClient.getInstance()).thenReturn(keycloakInstance);
|
||||
when(keycloakInstance.serverInfo()).thenReturn(serverInfoResource);
|
||||
when(serverInfoResource.getInfo()).thenThrow(new RuntimeException("Connection error"));
|
||||
|
||||
Map<String, Object> health = syncService.getKeycloakHealthInfo();
|
||||
assertNotNull(health);
|
||||
// Either status=DOWN (HTTP fallback also fails) or status=UP (HTTP fallback succeeds)
|
||||
assertNotNull(health.get("status"));
|
||||
}
|
||||
|
||||
@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"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetLastSyncStatus() {
|
||||
dev.lions.user.manager.server.impl.entity.SyncHistoryEntity entity =
|
||||
new dev.lions.user.manager.server.impl.entity.SyncHistoryEntity();
|
||||
entity.setStatus("completed");
|
||||
entity.setSyncType("USER");
|
||||
entity.setItemsProcessed(5);
|
||||
entity.setSyncDate(java.time.LocalDateTime.now());
|
||||
when(syncHistoryRepository.findLatestByRealm(eq("realm"), eq(1)))
|
||||
.thenReturn(Collections.singletonList(entity));
|
||||
|
||||
Map<String, Object> status = syncService.getLastSyncStatus("realm");
|
||||
assertEquals("completed", status.get("status"));
|
||||
assertNotNull(status.get("lastSyncDate"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -756,7 +756,7 @@ class UserServiceImplCompleteTest {
|
||||
when(keycloakAdminClient.getUsers(REALM)).thenReturn(usersResource);
|
||||
UserRepresentation existing = new UserRepresentation();
|
||||
existing.setUsername("existinguser");
|
||||
when(usersResource.search("existinguser", 0, 1, true)).thenReturn(List.of(existing));
|
||||
when(usersResource.searchByUsername("existinguser", true)).thenReturn(List.of(existing));
|
||||
|
||||
assertTrue(userService.usernameExists("existinguser", REALM));
|
||||
}
|
||||
@@ -764,7 +764,7 @@ class UserServiceImplCompleteTest {
|
||||
@Test
|
||||
void testUsernameExists_False() {
|
||||
when(keycloakAdminClient.getUsers(REALM)).thenReturn(usersResource);
|
||||
when(usersResource.search("newuser", 0, 1, true)).thenReturn(Collections.emptyList());
|
||||
when(usersResource.searchByUsername("newuser", true)).thenReturn(Collections.emptyList());
|
||||
|
||||
assertFalse(userService.usernameExists("newuser", REALM));
|
||||
}
|
||||
@@ -772,7 +772,7 @@ class UserServiceImplCompleteTest {
|
||||
@Test
|
||||
void testUsernameExists_Exception() {
|
||||
when(keycloakAdminClient.getUsers(REALM)).thenReturn(usersResource);
|
||||
when(usersResource.search("user", 0, 1, true)).thenThrow(new RuntimeException("error"));
|
||||
when(usersResource.searchByUsername("user", true)).thenThrow(new RuntimeException("error"));
|
||||
|
||||
assertFalse(userService.usernameExists("user", REALM)); // returns false on exception
|
||||
}
|
||||
@@ -969,7 +969,7 @@ class UserServiceImplCompleteTest {
|
||||
when(usersResource.searchByEmail("john@test.com", true)).thenReturn(Collections.emptyList());
|
||||
// Username doesn't exist
|
||||
when(usersResource.search("\"john\"", 0, 1, true)).thenReturn(Collections.emptyList());
|
||||
when(usersResource.search("john", 0, 1, true)).thenReturn(Collections.emptyList());
|
||||
when(usersResource.searchByUsername("john", true)).thenReturn(Collections.emptyList());
|
||||
|
||||
// Mock create response
|
||||
jakarta.ws.rs.core.Response response = mock(jakarta.ws.rs.core.Response.class);
|
||||
@@ -998,7 +998,7 @@ class UserServiceImplCompleteTest {
|
||||
when(keycloakAdminClient.getUsers(REALM)).thenReturn(usersResource);
|
||||
// Email doesn't exist
|
||||
when(usersResource.searchByEmail("john@test.com", true)).thenReturn(Collections.emptyList());
|
||||
when(usersResource.search("john", 0, 1, true)).thenReturn(Collections.emptyList());
|
||||
when(usersResource.searchByUsername("john", true)).thenReturn(Collections.emptyList());
|
||||
|
||||
jakarta.ws.rs.core.Response response = mock(jakarta.ws.rs.core.Response.class);
|
||||
when(response.getStatus()).thenReturn(201);
|
||||
|
||||
@@ -219,7 +219,7 @@ class UserServiceImplExtendedTest {
|
||||
when(keycloakAdminClient.getUsers(REALM)).thenReturn(usersResource);
|
||||
when(usersResource.search("testuser", 0, 1, true)).thenThrow(new RuntimeException("Connection error"));
|
||||
|
||||
assertThrows(RuntimeException.class, () ->
|
||||
assertThrows(RuntimeException.class, () ->
|
||||
userService.getUserByUsername("testuser", REALM));
|
||||
}
|
||||
|
||||
@@ -265,7 +265,7 @@ class UserServiceImplExtendedTest {
|
||||
UserRepresentation existingUser = new UserRepresentation();
|
||||
existingUser.setUsername("existinguser");
|
||||
existingUser.setEnabled(true);
|
||||
when(usersResource.search("existinguser", 0, 1, true)).thenReturn(List.of(existingUser));
|
||||
when(usersResource.searchByUsername("existinguser", true)).thenReturn(List.of(existingUser));
|
||||
|
||||
UserDTO userDTO = UserDTO.builder()
|
||||
.username("existinguser")
|
||||
@@ -282,7 +282,7 @@ class UserServiceImplExtendedTest {
|
||||
@Test
|
||||
void testCreateUser_EmailExists() {
|
||||
when(keycloakAdminClient.getUsers(REALM)).thenReturn(usersResource);
|
||||
when(usersResource.search("newuser", 0, 1, true)).thenReturn(Collections.emptyList());
|
||||
when(usersResource.searchByUsername("newuser", true)).thenReturn(Collections.emptyList());
|
||||
// emailExists calls searchByEmail which should return a non-empty list
|
||||
UserRepresentation existingUser = new UserRepresentation();
|
||||
existingUser.setEmail("existing@example.com");
|
||||
@@ -304,7 +304,7 @@ class UserServiceImplExtendedTest {
|
||||
@Test
|
||||
void testCreateUser_StatusNot201() {
|
||||
when(keycloakAdminClient.getUsers(REALM)).thenReturn(usersResource);
|
||||
when(usersResource.search("newuser", 0, 1, true)).thenReturn(Collections.emptyList());
|
||||
when(usersResource.searchByUsername("newuser", true)).thenReturn(Collections.emptyList());
|
||||
|
||||
UserDTO userDTO = UserDTO.builder()
|
||||
.username("newuser")
|
||||
@@ -323,7 +323,7 @@ class UserServiceImplExtendedTest {
|
||||
@Test
|
||||
void testCreateUser_WithTemporaryPassword() {
|
||||
when(keycloakAdminClient.getUsers(REALM)).thenReturn(usersResource);
|
||||
when(usersResource.search("newuser", 0, 1, true)).thenReturn(Collections.emptyList());
|
||||
when(usersResource.searchByUsername("newuser", true)).thenReturn(Collections.emptyList());
|
||||
|
||||
UserDTO userDTO = UserDTO.builder()
|
||||
.username("newuser")
|
||||
@@ -354,7 +354,7 @@ class UserServiceImplExtendedTest {
|
||||
@Test
|
||||
void testCreateUser_Exception() {
|
||||
when(keycloakAdminClient.getUsers(REALM)).thenReturn(usersResource);
|
||||
when(usersResource.search("newuser", 0, 1, true)).thenThrow(new RuntimeException("Connection error"));
|
||||
when(usersResource.searchByUsername("newuser", true)).thenThrow(new RuntimeException("Connection error"));
|
||||
|
||||
UserDTO userDTO = UserDTO.builder()
|
||||
.username("newuser")
|
||||
|
||||
@@ -460,7 +460,7 @@ class UserServiceImplIntegrationTest {
|
||||
|
||||
UserRepresentation user = new UserRepresentation();
|
||||
user.setUsername("existinguser");
|
||||
when(usersResource.search("existinguser", 0, 1, true)).thenReturn(List.of(user));
|
||||
when(usersResource.searchByUsername("existinguser", true)).thenReturn(List.of(user));
|
||||
|
||||
boolean exists = userService.usernameExists("existinguser", REALM);
|
||||
|
||||
@@ -470,7 +470,7 @@ class UserServiceImplIntegrationTest {
|
||||
@Test
|
||||
void testUsernameExists_False() {
|
||||
when(keycloakAdminClient.getUsers(REALM)).thenReturn(usersResource);
|
||||
when(usersResource.search("nonexistent", 0, 1, true)).thenReturn(Collections.emptyList());
|
||||
when(usersResource.searchByUsername("nonexistent", true)).thenReturn(Collections.emptyList());
|
||||
|
||||
boolean exists = userService.usernameExists("nonexistent", REALM);
|
||||
|
||||
@@ -480,7 +480,7 @@ class UserServiceImplIntegrationTest {
|
||||
@Test
|
||||
void testUsernameExists_Exception() {
|
||||
when(keycloakAdminClient.getUsers(REALM)).thenReturn(usersResource);
|
||||
when(usersResource.search("erroruser", 0, 1, true)).thenThrow(new RuntimeException("Error"));
|
||||
when(usersResource.searchByUsername("erroruser", true)).thenThrow(new RuntimeException("Error"));
|
||||
|
||||
boolean exists = userService.usernameExists("erroruser", REALM);
|
||||
|
||||
|
||||
@@ -106,7 +106,7 @@ class UserServiceImplTest {
|
||||
UserDTO newUser = UserDTO.builder().username("newuser").email("new@example.com").build();
|
||||
|
||||
// Check exists
|
||||
when(usersResource.search("newuser", 0, 1, true)).thenReturn(Collections.emptyList());
|
||||
when(usersResource.searchByUsername("newuser", true)).thenReturn(Collections.emptyList());
|
||||
when(usersResource.searchByEmail("new@example.com", true)).thenReturn(Collections.emptyList());
|
||||
|
||||
// Mock creation response
|
||||
|
||||
Reference in New Issue
Block a user