From ee6ab31c1dd030db0d41c692f333875d3a63f0e1 Mon Sep 17 00:00:00 2001 From: sandushi Date: Fri, 9 Aug 2024 09:05:53 +0530 Subject: [PATCH 01/13] Remove powermock --- .../pom.xml | 10 +- ...DefaultSCIMUserStoreErrorResolverTest.java | 3 +- .../impl/IdentityResourceURLBuilderTest.java | 26 +-- .../common/impl/IdentitySCIMManagerTest.java | 40 ++-- .../common/impl/SCIMRoleManagerV2Test.java | 13 +- .../common/impl/SCIMUserManagerTest.java | 171 ++++++++---------- .../SCIMUserOperationListenerTest.java | 56 +++--- .../common/utils/AdminAttributeUtilTest.java | 39 ++-- .../utils/AdminAttributeUtilTestForGroup.java | 70 ++++--- .../common/utils/SCIMCommonUtilsTest.java | 61 +++---- pom.xml | 20 +- 11 files changed, 225 insertions(+), 284 deletions(-) diff --git a/components/org.wso2.carbon.identity.scim2.common/pom.xml b/components/org.wso2.carbon.identity.scim2.common/pom.xml index 6c6a15738..b30448a5d 100644 --- a/components/org.wso2.carbon.identity.scim2.common/pom.xml +++ b/components/org.wso2.carbon.identity.scim2.common/pom.xml @@ -173,12 +173,14 @@ testng - org.powermock - powermock-module-testng + org.mockito + mockito-core + test - org.powermock - powermock-api-mockito2 + org.mockito + mockito-testng + test org.jacoco diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/DefaultSCIMUserStoreErrorResolverTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/DefaultSCIMUserStoreErrorResolverTest.java index 6150cf4bd..fa52abbc4 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/DefaultSCIMUserStoreErrorResolverTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/DefaultSCIMUserStoreErrorResolverTest.java @@ -19,7 +19,6 @@ package org.wso2.carbon.identity.scim2.common.impl; import org.apache.http.HttpStatus; -import org.powermock.modules.testng.PowerMockTestCase; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.wso2.carbon.identity.scim2.common.extenstion.SCIMUserStoreException; @@ -31,7 +30,7 @@ /** * Contains the unit test cases for DefaultSCIMUserStoreErrorResolver. */ -public class DefaultSCIMUserStoreErrorResolverTest extends PowerMockTestCase { +public class DefaultSCIMUserStoreErrorResolverTest { @Test public void testGetOrder() { diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentityResourceURLBuilderTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentityResourceURLBuilderTest.java index 811f75bfc..e7469b101 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentityResourceURLBuilderTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentityResourceURLBuilderTest.java @@ -19,8 +19,8 @@ package org.wso2.carbon.identity.scim2.common.impl; import org.mockito.Mock; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; + +import org.mockito.MockedStatic; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -33,17 +33,16 @@ import java.util.HashMap; import java.util.Map; -import static org.mockito.Matchers.anyString; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; import static org.testng.Assert.assertEquals; +import static org.mockito.Mockito.mockStatic; /** * Contains the unit test cases for IdentityResourceURLBuilder. */ -@PrepareForTest({IdentityTenantUtil.class, ServiceURLBuilder.class}) -public class IdentityResourceURLBuilderTest extends PowerMockTestCase { +public class IdentityResourceURLBuilderTest { private static final Map DUMMY_ENDPOINT_URI_MAP = new HashMap() {{ put("Users", "https://localhost:9444/scim2/Users"); @@ -56,14 +55,17 @@ public class IdentityResourceURLBuilderTest extends PowerMockTestCase { @Mock ServiceURL mockServiceUrl; + private MockedStatic serviceURLBuilder; + private MockedStatic identityTenantUtil; + @BeforeMethod public void setUpMethod() { initMocks(this); - mockStatic(ServiceURLBuilder.class); - when(ServiceURLBuilder.create()).thenReturn(mockServiceURLBuilder); + serviceURLBuilder = mockStatic(ServiceURLBuilder.class); + serviceURLBuilder.when(() -> ServiceURLBuilder.create()).thenReturn(mockServiceURLBuilder); when(mockServiceURLBuilder.addPath(anyString())).thenReturn(mockServiceURLBuilder); - mockStatic(IdentityTenantUtil.class); + identityTenantUtil = mockStatic(IdentityTenantUtil.class); } @DataProvider(name = "dataProviderForBuild") @@ -82,7 +84,7 @@ public Object[][] dataProviderForBuild() { public void testBuild(boolean isTenantQualifiedUrlsEnabled, String url, String resource, boolean throwError, String expected) throws NotFoundException, URLBuilderException { - when(IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifiedUrlsEnabled); + identityTenantUtil.when(() -> IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifiedUrlsEnabled); when(mockServiceURLBuilder.build()).thenAnswer(invocationOnMock -> { if (throwError) { throw new URLBuilderException("Protocol of service URL is not available."); @@ -109,7 +111,7 @@ public Object[][] dataProviderForBuildThrowingNotFoundException() { public void testBuildThrowingNotFoundException(boolean isTenantQualifiedUrlsEnabled, String resource) throws URLBuilderException, NotFoundException { - when(IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifiedUrlsEnabled); + identityTenantUtil.when(() -> IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifiedUrlsEnabled); when(mockServiceURLBuilder.build()).thenThrow( new URLBuilderException("Protocol of service URL is not available.")); IdentityResourceURLBuilder identityResourceURLBuilder = new IdentityResourceURLBuilder(); diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentitySCIMManagerTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentitySCIMManagerTest.java index d3011bddc..8762697b0 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentitySCIMManagerTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentitySCIMManagerTest.java @@ -19,13 +19,11 @@ package org.wso2.carbon.identity.scim2.common.impl; import org.mockito.Mock; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.IObjectFactory; +import org.mockito.MockedStatic; import org.testng.annotations.BeforeMethod; -import org.testng.annotations.ObjectFactory; import org.testng.annotations.Test; +import org.testng.annotations.Listeners; +import org.mockito.testng.MockitoTestNGListener; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.identity.scim2.common.internal.SCIMCommonComponentHolder; import org.wso2.carbon.identity.scim2.common.test.utils.CommonTestUtils; @@ -44,19 +42,18 @@ import java.nio.file.Paths; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.anyString; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.fail; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.anyInt; /** * Contains the unit test cases for IdentitySCIMManager. */ -@PrepareForTest({SCIMCommonUtils.class, PrivilegedCarbonContext.class, SCIMCommonComponentHolder.class,CharonConfiguration.class}) -@PowerMockIgnore({"javax.xml.*","org.w3c.dom.*","org.xml.sax.*"}) -public class IdentitySCIMManagerTest extends PowerMockTestCase { +@Listeners(MockitoTestNGListener.class) +public class IdentitySCIMManagerTest { @Mock RealmService realmService; @@ -76,14 +73,17 @@ public class IdentitySCIMManagerTest extends PowerMockTestCase { private SCIMConfigProcessor scimConfigProcessor; private IdentitySCIMManager identitySCIMManager; + private MockedStatic scimCommonUtils; + private MockedStatic scimCommonComponentHolder; + @BeforeMethod public void setUp() throws Exception { - mockStatic(SCIMCommonUtils.class); - when(SCIMCommonUtils.getSCIMUserURL()).thenReturn("http://scimUserUrl:9443"); + scimCommonUtils = mockStatic(SCIMCommonUtils.class); + scimCommonUtils.when(() -> SCIMCommonUtils.getSCIMUserURL()).thenReturn("http://scimUserUrl:9443"); - mockStatic(SCIMCommonComponentHolder.class); - when(SCIMCommonComponentHolder.getRealmService()).thenReturn(realmService); + scimCommonComponentHolder = mockStatic(SCIMCommonComponentHolder.class); + scimCommonComponentHolder.when(() -> SCIMCommonComponentHolder.getRealmService()).thenReturn(realmService); scimConfigProcessor = SCIMConfigProcessor.getInstance(); String filePath = Paths @@ -91,7 +91,7 @@ public void setUp() throws Exception { scimConfigProcessor.buildConfigFromFile(filePath); identitySCIMManager = IdentitySCIMManager.getInstance(); - mockStatic(SCIMCommonComponentHolder.class); + scimCommonComponentHolder = mockStatic(SCIMCommonComponentHolder.class); when(realmService.getTenantManager()).thenReturn(mockedTenantManager); when(mockedTenantManager.getTenantId(anyString())).thenReturn(-1234); @@ -102,12 +102,6 @@ public void setUp() throws Exception { CommonTestUtils.initPrivilegedCarbonContext(); } - @ObjectFactory - public IObjectFactory getObjectFactory() { - - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } - @Test public void testGetInstance() throws Exception { diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManagerV2Test.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManagerV2Test.java index 96eca05c0..ea9b147bf 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManagerV2Test.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManagerV2Test.java @@ -19,13 +19,12 @@ package org.wso2.carbon.identity.scim2.common.impl; import org.mockito.Mock; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; +import org.mockito.MockedStatic; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import org.wso2.carbon.identity.core.ServiceURLBuilder; import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.role.v2.mgt.core.RoleManagementService; import org.wso2.carbon.identity.role.v2.mgt.core.exception.IdentityRoleManagementException; @@ -43,6 +42,7 @@ import java.util.List; import java.util.Map; +import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import static org.testng.Assert.assertEquals; @@ -50,8 +50,7 @@ /** * Contains the unit test cases for SCIMRoleManagerV2. */ -@PrepareForTest({IdentityUtil.class}) -public class SCIMRoleManagerV2Test extends PowerMockTestCase { +public class SCIMRoleManagerV2Test { private static final String SAMPLE_TENANT_DOMAIN = "carbon.super"; private static final String SAMPLE_VALID_ROLE_ID = "595f5508-f286-446a-86c4-5071e07b98fc"; @@ -64,6 +63,8 @@ public class SCIMRoleManagerV2Test extends PowerMockTestCase { private SCIMRoleManagerV2 scimRoleManagerV2; + private MockedStatic identityUtil; + @BeforeClass public void setUpClass() { @@ -73,7 +74,7 @@ public void setUpClass() { @BeforeMethod public void setUpMethod() { - PowerMockito.mockStatic(IdentityUtil.class); + identityUtil = mockStatic(IdentityUtil.class); scimRoleManagerV2 = new SCIMRoleManagerV2(roleManagementService, SAMPLE_TENANT_DOMAIN); } diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMUserManagerTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMUserManagerTest.java index fa83a8447..3dfa12549 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMUserManagerTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMUserManagerTest.java @@ -20,17 +20,11 @@ import org.apache.commons.lang.StringUtils; import org.mockito.Mock; +import org.mockito.MockedStatic; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.api.support.membermodification.MemberModifier; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.IObjectFactory; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; -import org.testng.annotations.ObjectFactory; import org.testng.annotations.Test; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.base.MultitenantConstants; @@ -107,14 +101,8 @@ import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.*; import static org.mockito.MockitoAnnotations.initMocks; -import static org.powermock.api.mockito.PowerMockito.doNothing; -import static org.powermock.api.mockito.PowerMockito.doReturn; -import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.spy; -import static org.powermock.api.mockito.PowerMockito.when; -import static org.powermock.api.mockito.PowerMockito.whenNew; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; @@ -122,13 +110,7 @@ /* * Unit tests for SCIMUserManager */ -@PrepareForTest({SCIMGroupHandler.class, IdentityUtil.class, SCIMUserSchemaExtensionBuilder.class, - SCIMAttributeSchema.class, AttributeMapper.class, ClaimMetadataHandler.class, SCIMCommonUtils.class, - IdentityTenantUtil.class, AbstractUserStoreManager.class, Group.class, UserCoreUtil.class, - ApplicationManagementService.class, RolePermissionManagementService.class, SCIMCommonComponentHolder.class, - SCIMUserManager.class, CarbonConstants.class}) -@PowerMockIgnore({"java.sql.*","javax.xml.*","org.w3c.dom.*","org.xml.sax.*"}) -public class SCIMUserManagerTest extends PowerMockTestCase { +public class SCIMUserManagerTest { private static final String USERNAME_LOCAL_CLAIM = "http://wso2.org/claims/username"; private static final String USERID_LOCAL_CLAIM = "http://wso2.org/claims/userid"; @@ -196,6 +178,14 @@ public class SCIMUserManagerTest extends PowerMockTestCase { @Mock private RolePermissionManagementService mockedRolePermissionManagementService; + private MockedStatic scimUserSchemaExtensionBuilder; + private MockedStatic identityUtil; + private MockedStatic scimCommonUtils; + private MockedStatic attributeMapper; + private MockedStatic claimMetadataHandler; + private MockedStatic carbonConstants; + private MockedStatic identityTenantUtil; + private MockedStatic userCoreUtil; @BeforeMethod public void setUp() throws Exception { @@ -265,19 +255,19 @@ public void testGetMe(Object[] cMap, HashMap required, String[] when(mockedClaimManager.getAllClaimMappings(anyString())).thenReturn((ClaimMapping[]) cMap); SCIMUserSchemaExtensionBuilder sb = spy(new SCIMUserSchemaExtensionBuilder()); - mockStatic(SCIMUserSchemaExtensionBuilder.class); - when(SCIMUserSchemaExtensionBuilder.getInstance()).thenReturn(sb); + scimUserSchemaExtensionBuilder = mockStatic(SCIMUserSchemaExtensionBuilder.class); + scimUserSchemaExtensionBuilder.when(() -> SCIMUserSchemaExtensionBuilder.getInstance()).thenReturn(sb); when(sb.getExtensionSchema()).thenReturn(mockedSCIMAttributeSchema); - mockStatic(IdentityUtil.class); - when(IdentityUtil.extractDomainFromName(anyString())).thenReturn("testPrimaryDomain"); + identityUtil = mockStatic(IdentityUtil.class); + identityUtil.when(() -> IdentityUtil.extractDomainFromName(anyString())).thenReturn("testPrimaryDomain"); - mockStatic(SCIMCommonUtils.class); - when(SCIMCommonUtils.convertLocalToSCIMDialect(anyMap(), anyMap())).thenReturn(new HashMap() {{ + scimCommonUtils = mockStatic(SCIMCommonUtils.class); + scimCommonUtils.when(() -> SCIMCommonUtils.convertLocalToSCIMDialect(anyMap(), anyMap())).thenReturn(new HashMap() {{ put(SCIMConstants.CommonSchemaConstants.ID_URI, "1f70378a-69bb-49cf-aa51-a0493c09110c"); }}); - mockedUserStoreManager = PowerMockito.mock(AbstractUserStoreManager.class); + mockedUserStoreManager = mock(AbstractUserStoreManager.class); MemberModifier.field(AbstractUserStoreManager.class, "userStoreManagerHolder") .set(mockedUserStoreManager, new HashMap()); @@ -285,8 +275,8 @@ public void testGetMe(Object[] cMap, HashMap required, String[] when(mockedUserStoreManager.getSecondaryUserStoreManager(anyString())).thenReturn(secondaryUserStoreManager); when(mockedUserStoreManager.isSCIMEnabled()).thenReturn(true); when(mockedUserStoreManager.getRoleListOfUser(anyString())).thenReturn(userRoles); - mockStatic(AttributeMapper.class); - when(AttributeMapper.constructSCIMObjectFromAttributes(any(), anyMap(), anyInt())).thenReturn(mockedUser); + attributeMapper = mockStatic(AttributeMapper.class); + attributeMapper.when(() -> AttributeMapper.constructSCIMObjectFromAttributes(any(), anyMap(), anyInt())).thenReturn(mockedUser); when(mockedUserStoreManager.getRealmConfiguration()).thenReturn(mockedRealmConfig); when(mockedRealmConfig.getEveryOneRoleName()).thenReturn("roleName"); when(mockedUserStoreManager.getTenantId()).thenReturn(1234567); @@ -294,10 +284,9 @@ public void testGetMe(Object[] cMap, HashMap required, String[] user.setUsername("testUserName"); user.setUserID(UUID.randomUUID().toString()); when(mockedUserStoreManager.getUser(anyString(), nullable(String.class))).thenReturn(user); - whenNew(GroupDAO.class).withAnyArguments().thenReturn(mockedGroupDAO); CommonTestUtils.initPrivilegedCarbonContext(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); - mockStatic(ClaimMetadataHandler.class); - when(ClaimMetadataHandler.getInstance()).thenReturn(mockClaimMetadataHandler); + claimMetadataHandler = mockStatic(ClaimMetadataHandler.class); + claimMetadataHandler.when(() -> ClaimMetadataHandler.getInstance()).thenReturn(mockClaimMetadataHandler); when(mockClaimMetadataHandler.getMappingsFromOtherDialectToCarbon(anyString(), anySet(), anyString())) .thenReturn(new HashSet()); @@ -309,16 +298,15 @@ public void testGetMe(Object[] cMap, HashMap required, String[] public void testGetGroup(String groupId, String roleName, String userStoreDomain, Object expected) throws Exception { - whenNew(GroupDAO.class).withAnyArguments().thenReturn(mockedGroupDAO); when(mockedGroupDAO.getGroupNameById(anyInt(), anyString())).thenReturn(roleName); - mockStatic(IdentityUtil.class); - when(IdentityUtil.extractDomainFromName(anyString())).thenReturn(userStoreDomain); + identityUtil = mockStatic(IdentityUtil.class); + identityUtil.when(() -> IdentityUtil.extractDomainFromName(anyString())).thenReturn(userStoreDomain); when(mockedUserStoreManager.getGroup(groupId, null)). thenReturn(buildUserCoreGroupResponse(roleName, groupId, userStoreDomain)); - mockStatic(SCIMCommonUtils.class); - when(SCIMCommonUtils.getSCIMGroupURL()).thenReturn("https://localhost:9443/scim2/Groups"); + scimCommonUtils = mockStatic(SCIMCommonUtils.class); + scimCommonUtils.when(() -> SCIMCommonUtils.getSCIMGroupURL()).thenReturn("https://localhost:9443/scim2/Groups"); - mockStatic(CarbonConstants.class); + carbonConstants = mockStatic(CarbonConstants.class); CarbonConstants.ENABLE_LEGACY_AUTHZ_RUNTIME = true; SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockedClaimManager); @@ -347,10 +335,9 @@ public void testGetGroupWithExceptions(String roleName, String userStoreDomain) MemberModifier.field(AbstractUserStoreManager.class, "userStoreManagerHolder") .set(mockedUserStoreManager, new HashMap()); - whenNew(GroupDAO.class).withAnyArguments().thenReturn(mockedGroupDAO); when(mockedGroupDAO.getGroupNameById(anyInt(), anyString())).thenReturn(roleName); - mockStatic(IdentityUtil.class); - when(IdentityUtil.extractDomainFromName(anyString())).thenReturn(userStoreDomain); + identityUtil = mockStatic(IdentityUtil.class); + identityUtil.when(() -> IdentityUtil.extractDomainFromName(anyString())).thenReturn(userStoreDomain); SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockedClaimManager); try { @@ -397,15 +384,14 @@ public void testListGroupsWithFilter(String filter, String roleName, String user Map attributes = new HashMap() {{ put(SCIMConstants.CommonSchemaConstants.ID_URI, "1"); }}; - whenNew(GroupDAO.class).withAnyArguments().thenReturn(mockedGroupDAO); when(mockedGroupDAO.getGroupNameList(anyString(), anyString(), anyInt(), anyString())) .thenReturn(list.toArray(new String[0])); - mockStatic(IdentityUtil.class); + identityUtil = mockStatic(IdentityUtil.class); when(mockedGroupDAO.isExistingGroup("testRole", 0)).thenReturn(true); when(mockedGroupDAO.getSCIMGroupAttributes(0, "testRole")).thenReturn(attributes); - when(IdentityUtil.extractDomainFromName(anyString())).thenReturn(userStoreDomain); + identityUtil.when(() -> IdentityUtil.extractDomainFromName(anyString())).thenReturn(userStoreDomain); - mockedUserStoreManager = PowerMockito.mock(AbstractUserStoreManager.class); + mockedUserStoreManager = mock(AbstractUserStoreManager.class); MemberModifier.field(AbstractUserStoreManager.class, "userStoreManagerHolder") .set(mockedUserStoreManager, new HashMap()); @@ -422,7 +408,6 @@ public void testListGroupsWithFilter(String filter, String roleName, String user anyInt(), nullable(String.class), nullable(String.class))).thenReturn(Arrays.asList(groupsArray.clone())); when(mockedUserStoreManager.getGroupByGroupName(roleName, null)). thenReturn(buildUserCoreGroupResponse(roleName, "123456789", null)); - whenNew(RealmConfiguration.class).withAnyArguments().thenReturn(mockRealmConfig); when(mockRealmConfig.getAdminRoleName()).thenReturn("admin"); when(mockRealmConfig.isPrimary()).thenReturn(false); when(mockRealmConfig.getUserStoreProperty(anyString())).thenReturn("value"); @@ -430,14 +415,14 @@ public void testListGroupsWithFilter(String filter, String roleName, String user when(mockIdentityUtil.extractDomainFromName(anyString())).thenReturn("value"); - mockStatic(CarbonConstants.class); + carbonConstants = mockStatic(CarbonConstants.class); CarbonConstants.ENABLE_LEGACY_AUTHZ_RUNTIME = true; Map scimToLocalClaimsMap = new HashMap<>(); scimToLocalClaimsMap.put("urn:ietf:params:scim:schemas:core:2.0:User:userName", "http://wso2.org/claims/username"); - mockStatic(SCIMCommonUtils.class); - when(SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimsMap); + scimCommonUtils = mockStatic(SCIMCommonUtils.class); + scimCommonUtils.when(() -> SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimsMap); SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockedClaimManager); GroupsGetResponse groupsResponse = scimUserManager.listGroupsWithGET(node, 1, 1, null, null, @@ -457,13 +442,13 @@ public void testListUsersWithGET(List use "http://wso2.org/claims/username"); scimToLocalClaimMap.put("urn:ietf:params:scim:schemas:core:2.0:id", "http://wso2.org/claims/userid"); - mockStatic(SCIMCommonUtils.class); - when(SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimMap); - when(SCIMCommonUtils.convertLocalToSCIMDialect(anyMap(), anyMap())).thenReturn(new HashMap() {{ + scimCommonUtils = mockStatic(SCIMCommonUtils.class); + scimCommonUtils.when(() -> SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimMap); + scimCommonUtils.when(() -> SCIMCommonUtils.convertLocalToSCIMDialect(anyMap(), anyMap())).thenReturn(new HashMap() {{ put(SCIMConstants.CommonSchemaConstants.ID_URI, "1f70378a-69bb-49cf-aa51-a0493c09110c"); }}); - mockedUserStoreManager = PowerMockito.mock(AbstractUserStoreManager.class); + mockedUserStoreManager = mock(AbstractUserStoreManager.class); when(mockedUserStoreManager.getUserListWithID("http://wso2.org/claims/userid", "*", null)).thenReturn(users); when(mockedUserStoreManager.getRoleListOfUserWithID(anyString())).thenReturn(new ArrayList<>()); @@ -475,9 +460,9 @@ public void testListUsersWithGET(List use when(mockedUserStoreManager.getSecondaryUserStoreManager("SECONDARY")).thenReturn(secondaryUserStoreManager); when(secondaryUserStoreManager.isSCIMEnabled()).thenReturn(isScimEnabledForSecondary); - mockStatic(IdentityTenantUtil.class); + identityTenantUtil = mockStatic(IdentityTenantUtil.class); - when(IdentityTenantUtil.getRealmService()).thenReturn(mockRealmService); + identityTenantUtil.when(() -> IdentityTenantUtil.getRealmService()).thenReturn(mockRealmService); when(mockRealmService.getBootstrapRealmConfiguration()).thenReturn(mockedRealmConfig); HashMap requiredClaimsMap = new HashMap<>(); @@ -544,13 +529,13 @@ public void testFilteringUsersWithGET(List() {{ + scimCommonUtils = mockStatic(SCIMCommonUtils.class); + scimCommonUtils.when(() -> SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimMap); + scimCommonUtils.when(() -> SCIMCommonUtils.convertLocalToSCIMDialect(anyMap(), anyMap())).thenReturn(new HashMap() {{ put(SCIMConstants.CommonSchemaConstants.ID_URI, "1f70378a-69bb-49cf-aa51-a0493c09110c"); }}); - mockedUserStoreManager = PowerMockito.mock(AbstractUserStoreManager.class); + mockedUserStoreManager = mock(AbstractUserStoreManager.class); when(mockedUserStoreManager.getUserListWithID("http://wso2.org/claims/userid", "*", null)).thenReturn(users); when(mockedUserStoreManager.getUserListWithID("http://wso2.org/claims/givenname", "testUser", "default")) @@ -565,11 +550,11 @@ public void testFilteringUsersWithGET(List() {{ + scimCommonUtils = mockStatic(SCIMCommonUtils.class); + scimCommonUtils.when(() -> SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimMap); + scimCommonUtils.when(() -> SCIMCommonUtils.convertLocalToSCIMDialect(anyMap(), anyMap())).thenReturn(new HashMap() {{ put(SCIMConstants.CommonSchemaConstants.ID_URI, "1f70378a-69bb-49cf-aa51-a0493c09110c"); }}); - mockedUserStoreManager = PowerMockito.mock(AbstractUserStoreManager.class); + mockedUserStoreManager = mock(AbstractUserStoreManager.class); when(mockedUserStoreManager.getUserListWithID(any(Condition.class), anyString(), anyString(), eq(count), anyInt(), nullable(String.class), nullable(String.class))).thenReturn(filteredUsersWithPagination); @@ -686,8 +671,8 @@ public void testFilteringUsersWithGETWithPagination(List IdentityTenantUtil.getRealmService()).thenReturn(mockRealmService); when(mockRealmService.getBootstrapRealmConfiguration()).thenReturn(mockedRealmConfig); ClaimMapping[] claimMappings = getTestClaimMappings(); @@ -705,9 +690,9 @@ public void testFilteringUsersWithGETWithPagination(List SCIMCommonUtils.isConsiderTotalRecordsForTotalResultOfLDAPEnabled()) .thenReturn(isConsiderTotalRecordsForTotalResultOfLDAPEnabled); - when(SCIMCommonUtils.isConsiderMaxLimitForTotalResultEnabled()) + scimCommonUtils.when(() -> SCIMCommonUtils.isConsiderMaxLimitForTotalResultEnabled()) .thenReturn(isConsiderMaxLimitForTotalResultEnabled); Map supportedByDefaultProperties = new HashMap() {{ @@ -964,13 +949,12 @@ public void testListApplicationRolesWithDomainParam(Map require when(abstractUserStoreManager.getGroupByGroupName(role, null)). thenReturn(buildUserCoreGroupResponse(role, "123456789", null)); } - whenNew(GroupDAO.class).withAnyArguments().thenReturn(mockedGroupDAO); when(mockedGroupDAO.isExistingGroup(anyString(), anyInt())).thenReturn(true); when(mockedGroupDAO.getSCIMGroupAttributes(anyInt(), anyString())).thenReturn(attributes); - mockStatic(UserCoreUtil.class); - when(UserCoreUtil.isEveryoneRole("role", mockedRealmConfig)).thenReturn(false); - mockStatic(SCIMCommonUtils.class); - when(SCIMCommonUtils.getSCIMGroupURL()).thenReturn("https://localhost:9443/scim2/Groups"); + userCoreUtil = mockStatic(UserCoreUtil.class); + userCoreUtil.when(() -> UserCoreUtil.isEveryoneRole("role", mockedRealmConfig)).thenReturn(false); + scimCommonUtils = mockStatic(SCIMCommonUtils.class); + scimCommonUtils.when(() -> SCIMCommonUtils.getSCIMGroupURL()).thenReturn("https://localhost:9443/scim2/Groups"); SCIMUserManager scimUserManager = new SCIMUserManager(abstractUserStoreManager, mockedClaimManager); GroupsGetResponse groupsResponse = scimUserManager @@ -1021,15 +1005,14 @@ public void testFilterApplicationRolesWithDomainParam(String filter, String[] ro when(abstractUserStoreManager.getGroupByGroupName(role, null)). thenReturn(buildUserCoreGroupResponse(role, "123456", "dummyDomain")); } - mockStatic(UserCoreUtil.class); - when(UserCoreUtil.isEveryoneRole("role", mockedRealmConfig)).thenReturn(false); - whenNew(GroupDAO.class).withAnyArguments().thenReturn(mockedGroupDAO); + userCoreUtil = mockStatic(UserCoreUtil.class); + userCoreUtil.when(() -> UserCoreUtil.isEveryoneRole("role", mockedRealmConfig)).thenReturn(false); when(mockedGroupDAO.isExistingGroup(anyString(), anyInt())).thenReturn(true); when(mockedGroupDAO.getSCIMGroupAttributes(anyInt(), anyString())).thenReturn(attributes); - mockStatic(SCIMCommonUtils.class); - when(SCIMCommonUtils.getSCIMGroupURL()).thenReturn("https://localhost:9443/scim2/Groups"); + scimCommonUtils = mockStatic(SCIMCommonUtils.class); + scimCommonUtils.when(() -> SCIMCommonUtils.getSCIMGroupURL()).thenReturn("https://localhost:9443/scim2/Groups"); - mockStatic(CarbonConstants.class); + carbonConstants = mockStatic(CarbonConstants.class); CarbonConstants.ENABLE_LEGACY_AUTHZ_RUNTIME = true; SCIMUserManager scimUserManager = new SCIMUserManager(abstractUserStoreManager, mockedClaimManager); @@ -1055,12 +1038,6 @@ public Object[][] applicationDomainWithFilters() { }; } - @ObjectFactory - public IObjectFactory getObjectFactory() { - - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } - @Test public void testGetEnterpriseUserSchemaWhenEnabled() throws Exception { @@ -1099,12 +1076,12 @@ public void testGetEnterpriseUserSchemaWhenEnabled() throws Exception { MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)).thenReturn(externalClaimMap); when(mockClaimMetadataManagementService.getLocalClaims(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) .thenReturn(localClaimMap); - mockStatic(SCIMCommonUtils.class); - when(SCIMCommonUtils.isEnterpriseUserExtensionEnabled()).thenReturn(true); + scimCommonUtils = mockStatic(SCIMCommonUtils.class); + scimCommonUtils.when(() -> SCIMCommonUtils.isEnterpriseUserExtensionEnabled()).thenReturn(true); SCIMUserSchemaExtensionBuilder sb = spy(new SCIMUserSchemaExtensionBuilder()); - mockStatic(SCIMUserSchemaExtensionBuilder.class); - when(SCIMUserSchemaExtensionBuilder.getInstance()).thenReturn(sb); + scimUserSchemaExtensionBuilder = mockStatic(SCIMUserSchemaExtensionBuilder.class); + scimUserSchemaExtensionBuilder.when(() -> SCIMUserSchemaExtensionBuilder.getInstance()).thenReturn(sb); when(sb.getExtensionSchema()).thenReturn(mockedSCIMAttributeSchema); when(mockedSCIMAttributeSchema.getSubAttributeSchema(anyString())).thenReturn(mockedAttributeSchema); when(mockedAttributeSchema.getType()).thenReturn(SCIMDefinitions.DataType.STRING); @@ -1117,8 +1094,8 @@ public void testGetEnterpriseUserSchemaWhenEnabled() throws Exception { @Test public void testGetEnterpriseUserSchemaWhenDisabled() throws Exception { - mockStatic(SCIMCommonUtils.class); - when(SCIMCommonUtils.isEnterpriseUserExtensionEnabled()).thenReturn(false); + scimCommonUtils = mockStatic(SCIMCommonUtils.class); + scimCommonUtils.when(() -> SCIMCommonUtils.isEnterpriseUserExtensionEnabled()).thenReturn(false); SCIMUserManager userManager = new SCIMUserManager(mockedUserStoreManager, mockClaimMetadataManagementService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); assertEquals(userManager.getEnterpriseUserSchema(), null); @@ -1349,7 +1326,7 @@ public void testGetUser(Boolean isGroupsVsRolesSeparationImprovementsEnabled, Ma when(user.getDomainQualifiedUsername()).thenReturn(domainQualifiedUserName); when(user.getUserID()).thenReturn((userId)); - mockedUserStoreManager = PowerMockito.mock(AbstractUserStoreManager.class); + mockedUserStoreManager = mock(AbstractUserStoreManager.class); when(mockedUserStoreManager.getUserWithID(anyString(), nullable(String[].class), anyString())).thenReturn(user); when(mockedUserStoreManager.getTenantId()).thenReturn(1234567); when(mockedUserStoreManager.getUserClaimValuesWithID(anyString(), any(), nullable(String.class))) @@ -1370,7 +1347,6 @@ public void testGetUser(Boolean isGroupsVsRolesSeparationImprovementsEnabled, Ma when(mockedRealmConfig.isPrimary()).thenReturn(true); when(mockedRealmConfig.getEveryOneRoleName()).thenReturn("Internal/everyone"); - PowerMockito.whenNew(GroupDAO.class).withAnyArguments().thenReturn(mockedGroupDAO); doNothing().when(mockedGroupDAO).addSCIMGroupAttributesToSCIMDisabledHybridRoles(anyInt(), any()); SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, @@ -1384,7 +1360,6 @@ public void testGetUser(Boolean isGroupsVsRolesSeparationImprovementsEnabled, Ma when(IdentityUtil.getProperty(SCIMCommonConstants.ENABLE_LOGIN_IDENTIFIERS)).thenReturn(enableLoginIdentifiers); when(IdentityUtil.extractDomainFromName(anyString())).thenReturn("Internal"); - PowerMockito.whenNew(SCIMGroupHandler.class).withArguments(anyInt()).thenReturn(mockedSCIMGroupHandler); when(mockedSCIMGroupHandler.listSCIMRoles()).thenReturn(scimRoles); when(mockedSCIMGroupHandler.getGroupWithAttributes(any(Group.class), anyString())) .thenAnswer(new Answer() { diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/listener/SCIMUserOperationListenerTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/listener/SCIMUserOperationListenerTest.java index 466dc8aba..e6d639d67 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/listener/SCIMUserOperationListenerTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/listener/SCIMUserOperationListenerTest.java @@ -19,12 +19,9 @@ package org.wso2.carbon.identity.scim2.common.listener; import org.mockito.Mock; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.IObjectFactory; +import org.mockito.MockedStatic; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; -import org.testng.annotations.ObjectFactory; import org.testng.annotations.Test; import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants; import org.wso2.carbon.identity.claim.metadata.mgt.ClaimMetadataManagementService; @@ -49,22 +46,13 @@ import java.util.Map; import java.util.UUID; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.spy; -import static org.powermock.api.mockito.PowerMockito.when; -import static org.powermock.api.mockito.PowerMockito.whenNew; +import static org.mockito.Mockito.*; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; -@PrepareForTest({UserCoreUtil.class, SCIMGroupHandler.class, SCIMCommonUtils.class, IdentityUtil.class, - IdentityTenantUtil.class}) -public class SCIMUserOperationListenerTest extends PowerMockTestCase { + +public class SCIMUserOperationListenerTest { private final String CARBON_SUPER = "carbon.super"; private String userName = "testUser"; @@ -93,22 +81,21 @@ public class SCIMUserOperationListenerTest extends PowerMockTestCase { @Mock GroupDAO groupDAO; - @ObjectFactory - public IObjectFactory getObjectFactory() { - - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } + private MockedStatic userCoreUtil; + private MockedStatic scimCommonUtils; + private MockedStatic identityTenantUtil; + private MockedStatic identityUtil; @BeforeMethod public void setUp() throws Exception { scimUserOperationListener = spy(new SCIMUserOperationListener()); - mockStatic(UserCoreUtil.class); - mockStatic(SCIMCommonUtils.class); - mockStatic(IdentityTenantUtil.class); + userCoreUtil = mockStatic(UserCoreUtil.class); + scimCommonUtils = mockStatic(SCIMCommonUtils.class); + identityTenantUtil = mockStatic(IdentityTenantUtil.class); SCIMCommonComponentHolder.setClaimManagementService(claimMetadataManagementService); when(userStoreManager.getTenantId()).thenReturn(-1234); - when(IdentityTenantUtil.getTenantDomain(anyInt())).thenReturn(CARBON_SUPER); + identityTenantUtil.when(() -> IdentityTenantUtil.getTenantDomain(anyInt())).thenReturn(CARBON_SUPER); } @DataProvider(name = "testGetExecutionOrderIdData") @@ -234,8 +221,8 @@ public void testDoPreSetUserClaimValues(boolean isEnabled, boolean isSCIMEnabled when(scimUserOperationListener.isEnable()).thenReturn(isEnabled); when(userStoreManager.isSCIMEnabled()).thenReturn(isSCIMEnabled); - mockStatic(IdentityUtil.class); - when(IdentityUtil.getProperty(FrameworkConstants.ENABLE_JIT_PROVISION_ENHANCE_FEATURE)).thenReturn("false"); + identityUtil = mockStatic(IdentityUtil.class); + identityUtil.when(() -> IdentityUtil.getProperty(FrameworkConstants.ENABLE_JIT_PROVISION_ENHANCE_FEATURE)).thenReturn("false"); assertTrue(scimUserOperationListener. doPreSetUserClaimValuesWithID(userId, claims, profile, userStoreManager)); @@ -426,7 +413,7 @@ public Object[][] testSCIMAttributesData() { @Test(dataProvider = "testSCIMAttributesData") public void testGetSCIMAttributes(Map claimsMap) throws Exception { - mockStatic(SCIMCommonUtils.class); + scimCommonUtils = mockStatic(SCIMCommonUtils.class); Map scimToLocalClaimsMap = new HashMap<>(); scimToLocalClaimsMap.put(SCIMConstants.CommonSchemaConstants.ID_URI, "http://wso2.org/claims/userid"); scimToLocalClaimsMap.put(SCIMConstants.CommonSchemaConstants.CREATED_URI, "http://wso2.org/claims/created"); @@ -435,13 +422,13 @@ public void testGetSCIMAttributes(Map claimsMap) throws Exceptio scimToLocalClaimsMap.put(SCIMConstants.UserSchemaConstants.USER_NAME_URI, "http://wso2.org/claims/username"); scimToLocalClaimsMap.put(SCIMConstants.CommonSchemaConstants.RESOURCE_TYPE_URI, "http://wso2.org/claims/resourceType"); - when(SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimsMap); + scimCommonUtils.when(() -> SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimsMap); assertNotNull(scimUserOperationListener.getSCIMAttributes(userName, claimsMap)); } @Test(dataProvider = "testSCIMAttributesData") public void testPopulateSCIMAttributes(Map claimsMap) throws Exception { - mockStatic(SCIMCommonUtils.class); + scimCommonUtils = mockStatic(SCIMCommonUtils.class); Map scimToLocalClaimsMap = new HashMap<>(); scimToLocalClaimsMap.put(SCIMConstants.CommonSchemaConstants.ID_URI, "http://wso2.org/claims/userid"); scimToLocalClaimsMap.put(SCIMConstants.CommonSchemaConstants.CREATED_URI, "http://wso2.org/claims/created"); @@ -450,16 +437,15 @@ public void testPopulateSCIMAttributes(Map claimsMap) throws Exc scimToLocalClaimsMap.put(SCIMConstants.UserSchemaConstants.USER_NAME_URI, "http://wso2.org/claims/username"); scimToLocalClaimsMap.put(SCIMConstants.CommonSchemaConstants.RESOURCE_TYPE_URI, "http://wso2.org/claims/resourceType"); - when(SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimsMap); + scimCommonUtils.when(() -> SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimsMap); assertNotNull(scimUserOperationListener.populateSCIMAttributes(userName, claimsMap)); } private void mockTestEnvironment(boolean isEnabled, boolean isSCIMEnabled, String domainName) throws Exception { when(scimUserOperationListener.isEnable()).thenReturn(isEnabled); when(userStoreManager.isSCIMEnabled()).thenReturn(isSCIMEnabled); - whenNew(GroupDAO.class).withNoArguments().thenReturn(groupDAO); - when(UserCoreUtil.getDomainName((RealmConfiguration) anyObject())).thenReturn(domainName); - when(UserCoreUtil.addDomainToName(anyString(), anyString())).thenReturn("testRoleNameWithDomain"); - when(SCIMCommonUtils.getGroupNameWithDomain(anyString())).thenReturn("testRoleNameWithDomain"); + userCoreUtil.when(() -> UserCoreUtil.getDomainName((RealmConfiguration) any())).thenReturn(domainName); + userCoreUtil.when(() -> UserCoreUtil.addDomainToName(anyString(), anyString())).thenReturn("testRoleNameWithDomain"); + scimCommonUtils.when(() ->SCIMCommonUtils.getGroupNameWithDomain(anyString())).thenReturn("testRoleNameWithDomain"); } } diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTest.java index 4ccc36dce..23d73e2c2 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTest.java @@ -20,8 +20,7 @@ import org.mockito.ArgumentCaptor; import org.mockito.Mock; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; +import org.mockito.MockedStatic; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -37,16 +36,9 @@ import java.util.Map; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.verify; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; +import static org.mockito.Mockito.*; -@PrepareForTest({SCIMCommonComponentHolder.class, ClaimsMgtUtil.class, IdentityTenantUtil.class, UserCoreUtil.class, - IdentityUtil.class, SCIMCommonUtils.class, AdminAttributeUtil.class}) -public class AdminAttributeUtilTest extends PowerMockTestCase { +public class AdminAttributeUtilTest { @Mock RealmService realmService; @@ -59,6 +51,11 @@ public class AdminAttributeUtilTest extends PowerMockTestCase { AdminAttributeUtil adminAttributeUtil; + private MockedStatic scimCommonComponentHolder; + private MockedStatic claimsMgtUtil; + +private MockedStatic identityTenantUtil; + @BeforeMethod public void setUp() throws Exception { adminAttributeUtil = new AdminAttributeUtil(); @@ -76,15 +73,15 @@ public Object[][] testUpdateAdminUserData() { public void testUpdateAdminUser(boolean validateSCIMID) throws Exception { String adminUsername = "admin"; - mockStatic(SCIMCommonComponentHolder.class); - mockStatic(ClaimsMgtUtil.class); - mockStatic(IdentityTenantUtil.class); - when(SCIMCommonComponentHolder.getRealmService()).thenReturn(realmService); + scimCommonComponentHolder = mockStatic(SCIMCommonComponentHolder.class); + claimsMgtUtil = mockStatic(ClaimsMgtUtil.class); + identityTenantUtil = mockStatic(IdentityTenantUtil.class); + scimCommonComponentHolder.when(() -> SCIMCommonComponentHolder.getRealmService()).thenReturn(realmService); when(realmService.getTenantUserRealm(anyInt())).thenReturn(userRealm); when(userRealm.getUserStoreManager()).thenReturn(userStoreManager); when(userStoreManager.isSCIMEnabled()).thenReturn(true); - when(ClaimsMgtUtil.getAdminUserNameFromTenantId(eq(realmService), anyInt())).thenReturn(adminUsername); - when(IdentityTenantUtil.getRealmService()).thenReturn(realmService); + claimsMgtUtil.when(() -> ClaimsMgtUtil.getAdminUserNameFromTenantId(eq(realmService), anyInt())).thenReturn(adminUsername); + identityTenantUtil.when(() -> IdentityTenantUtil.getRealmService()).thenReturn(realmService); when(userStoreManager.getUserClaimValue(anyString(), anyString(), anyString())).thenReturn(""); ArgumentCaptor argument = ArgumentCaptor.forClass(Map.class); @@ -94,10 +91,10 @@ public void testUpdateAdminUser(boolean validateSCIMID) throws Exception { @Test(expectedExceptions = UserStoreException.class) public void testUpdateAdminUser1() throws Exception { - mockStatic(SCIMCommonComponentHolder.class); - mockStatic(ClaimsMgtUtil.class); - mockStatic(IdentityTenantUtil.class); - when(SCIMCommonComponentHolder.getRealmService()).thenReturn(realmService); + scimCommonComponentHolder = mockStatic(SCIMCommonComponentHolder.class); + claimsMgtUtil = mockStatic(ClaimsMgtUtil.class); + identityTenantUtil = mockStatic(IdentityTenantUtil.class); + scimCommonComponentHolder.when(() -> SCIMCommonComponentHolder.getRealmService()).thenReturn(realmService); when(realmService.getTenantUserRealm(anyInt())).thenReturn(userRealm); when(userRealm.getUserStoreManager()).thenReturn(userStoreManager); when(userStoreManager.isSCIMEnabled()).thenThrow(new UserStoreException()); diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTestForGroup.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTestForGroup.java index 0377636ae..3c43e1689 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTestForGroup.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTestForGroup.java @@ -20,8 +20,7 @@ import org.mockito.ArgumentCaptor; import org.mockito.Mock; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; +import org.mockito.MockedStatic; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -38,18 +37,12 @@ import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.util.UserCoreUtil; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.verify; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; -import static org.powermock.api.mockito.PowerMockito.whenNew; +import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.any; + import static org.testng.Assert.assertEquals; -@PrepareForTest({SCIMCommonComponentHolder.class, ClaimsMgtUtil.class, IdentityTenantUtil.class, UserCoreUtil.class, - IdentityUtil.class, SCIMCommonUtils.class, AdminAttributeUtil.class}) -public class AdminAttributeUtilTestForGroup extends PowerMockTestCase { +public class AdminAttributeUtilTestForGroup { @Mock RealmService realmService; @@ -68,6 +61,13 @@ public class AdminAttributeUtilTestForGroup extends PowerMockTestCase { AdminAttributeUtil adminAttributeUtil; + private MockedStatic scimCommonComponentHolder; + private MockedStatic claimsMgtUtil; + private MockedStatic identityTenantUtil; + private MockedStatic userCoreUtil; + private MockedStatic identityUtil; + private MockedStatic scimCommonUtils; + @BeforeMethod public void setUp() throws Exception { adminAttributeUtil = new AdminAttributeUtil(); @@ -93,13 +93,13 @@ public Object[][] testUpdateAdminGroupData() { public void testUpdateAdminGroup(String domainName) throws Exception { String roleNameWithDomain = "TESTDOMAIN/admin"; - mockStatic(SCIMCommonComponentHolder.class); - mockStatic(ClaimsMgtUtil.class); - mockStatic(IdentityTenantUtil.class); - mockStatic(UserCoreUtil.class); - mockStatic(IdentityUtil.class); - mockStatic(SCIMCommonUtils.class); - when(SCIMCommonComponentHolder.getRealmService()).thenReturn(realmService); + scimCommonComponentHolder = mockStatic(SCIMCommonComponentHolder.class); + claimsMgtUtil = mockStatic(ClaimsMgtUtil.class); + identityTenantUtil = mockStatic(IdentityTenantUtil.class); + userCoreUtil = mockStatic(UserCoreUtil.class); + identityUtil = mockStatic(IdentityUtil.class); + scimCommonUtils = mockStatic(SCIMCommonUtils.class); + scimCommonComponentHolder.when(() -> SCIMCommonComponentHolder.getRealmService()).thenReturn(realmService); when(realmService.getTenantUserRealm(anyInt())).thenReturn(userRealm); when(userRealm.getUserStoreManager()).thenReturn(userStoreManager); when(userStoreManager.isSCIMEnabled()).thenReturn(true); @@ -107,11 +107,10 @@ public void testUpdateAdminGroup(String domainName) throws Exception { when(userStoreManager.getRealmConfiguration()).thenReturn(realmConfiguration); when(userStoreManager.isRoleAndGroupSeparationEnabled()).thenReturn(true); when(realmConfiguration.getAdminRoleName()).thenReturn("admin"); - when(UserCoreUtil.getDomainName((RealmConfiguration) anyObject())).thenReturn(domainName); - when(IdentityUtil.getPrimaryDomainName()).thenReturn("TESTDOMAIN"); - when(UserCoreUtil.addDomainToName(anyString(), anyString())).thenReturn(roleNameWithDomain); - when(SCIMCommonUtils.getGroupNameWithDomain(anyString())).thenReturn(roleNameWithDomain); - whenNew(SCIMGroupHandler.class).withAnyArguments().thenReturn(scimGroupHandler); + userCoreUtil.when(() -> UserCoreUtil.getDomainName((RealmConfiguration) any())).thenReturn(domainName); + identityUtil.when(() -> IdentityUtil.getPrimaryDomainName()).thenReturn("TESTDOMAIN"); + userCoreUtil.when(() -> UserCoreUtil.addDomainToName(anyString(), anyString())).thenReturn(roleNameWithDomain); + scimCommonUtils.when(() -> SCIMCommonUtils.getGroupNameWithDomain(anyString())).thenReturn(roleNameWithDomain); ArgumentCaptor argument = ArgumentCaptor.forClass(String.class); CarbonConstants.ENABLE_LEGACY_AUTHZ_RUNTIME = true; @@ -125,24 +124,23 @@ public void testUpdateAdminGroup(String domainName) throws Exception { public void testUpdateAdminGroup1() throws Exception { String roleNameWithDomain = "TESTDOMAIN/admin"; - mockStatic(SCIMCommonComponentHolder.class); - mockStatic(ClaimsMgtUtil.class); - mockStatic(IdentityTenantUtil.class); - mockStatic(UserCoreUtil.class); - mockStatic(IdentityUtil.class); - mockStatic(SCIMCommonUtils.class); - when(SCIMCommonComponentHolder.getRealmService()).thenReturn(realmService); + scimCommonComponentHolder = mockStatic(SCIMCommonComponentHolder.class); + claimsMgtUtil = mockStatic(ClaimsMgtUtil.class); + identityTenantUtil = mockStatic(IdentityTenantUtil.class); + userCoreUtil = mockStatic(UserCoreUtil.class); + identityUtil = mockStatic(IdentityUtil.class); + scimCommonUtils = mockStatic(SCIMCommonUtils.class); + scimCommonComponentHolder.when(() -> SCIMCommonComponentHolder.getRealmService()).thenReturn(realmService); when(realmService.getTenantUserRealm(anyInt())).thenReturn(userRealm); when(userRealm.getUserStoreManager()).thenReturn(userStoreManager); when(userStoreManager.isSCIMEnabled()).thenReturn(true); when(userStoreManager.getTenantId()).thenReturn(1); when(userStoreManager.getRealmConfiguration()).thenReturn(realmConfiguration); when(realmConfiguration.getAdminRoleName()).thenReturn("admin"); - when(UserCoreUtil.getDomainName((RealmConfiguration) anyObject())).thenReturn("testDomain"); - when(IdentityUtil.getPrimaryDomainName()).thenReturn("TESTDOMAIN"); - when(UserCoreUtil.addDomainToName(anyString(), anyString())).thenReturn(roleNameWithDomain); - when(SCIMCommonUtils.getGroupNameWithDomain(anyString())).thenReturn(roleNameWithDomain); - whenNew(SCIMGroupHandler.class).withAnyArguments().thenReturn(scimGroupHandler); + userCoreUtil.when(() -> UserCoreUtil.getDomainName((RealmConfiguration) any())).thenReturn("testDomain"); + identityUtil.when(() -> IdentityUtil.getPrimaryDomainName()).thenReturn("TESTDOMAIN"); + userCoreUtil.when(() -> UserCoreUtil.addDomainToName(anyString(), anyString())).thenReturn(roleNameWithDomain); + scimCommonUtils.when(() -> SCIMCommonUtils.getGroupNameWithDomain(anyString())).thenReturn(roleNameWithDomain); when(scimGroupHandler.isGroupExisting(anyString())).thenThrow(new IdentitySCIMException("testException")); adminAttributeUtil.updateAdminGroup(1); diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/SCIMCommonUtilsTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/SCIMCommonUtilsTest.java index 21b298c53..658407d6a 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/SCIMCommonUtilsTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/SCIMCommonUtilsTest.java @@ -19,14 +19,10 @@ package org.wso2.carbon.identity.scim2.common.utils; import org.mockito.Mock; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; -import org.testng.IObjectFactory; +import org.mockito.MockedStatic; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; -import org.testng.annotations.ObjectFactory; import org.testng.annotations.Test; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.base.CarbonBaseConstants; @@ -41,16 +37,13 @@ import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; - -@PrepareForTest({IdentityUtil.class, UserCoreUtil.class, IdentityTenantUtil.class, ServiceURLBuilder.class}) -@PowerMockIgnore({"javax.xml.*","org.w3c.dom.*","org.xml.sax.*"}) -public class SCIMCommonUtilsTest extends PowerMockTestCase { +public class SCIMCommonUtilsTest { private static final String ID = "8a439cf6-3c6b-47d2-94bf-34d072495af3"; private static final String SCIM_URL = "https://localhost:9443/scim2"; @@ -71,28 +64,28 @@ public class SCIMCommonUtilsTest extends PowerMockTestCase { @Mock DefaultServiceURLBuilder defaultServiceURLBuilder1; - @ObjectFactory - public IObjectFactory getObjectFactory() { - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } + private MockedStatic userCoreUtil; + private MockedStatic identityTenantUtil; + private MockedStatic serviceURLBuilder; + private MockedStatic identityUtil; @BeforeMethod public void setUp() throws Exception { initMocks(this); - mockStatic(IdentityUtil.class); - mockStatic(UserCoreUtil.class); - mockStatic(IdentityTenantUtil.class); - mockStatic(ServiceURLBuilder.class); - when(IdentityUtil.getServerURL(anyString(), anyBoolean(), anyBoolean())).thenReturn(SCIM_URL); - when(IdentityUtil.getPrimaryDomainName()).thenReturn(UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME); - when(ServiceURLBuilder.create()).thenReturn(defaultServiceURLBuilder); + identityUtil = mockStatic(IdentityUtil.class); + userCoreUtil = mockStatic(UserCoreUtil.class); + identityTenantUtil = mockStatic(IdentityTenantUtil.class); + serviceURLBuilder = mockStatic(ServiceURLBuilder.class); + identityUtil.when(() -> IdentityUtil.getServerURL(anyString(), anyBoolean(), anyBoolean())).thenReturn(SCIM_URL); + identityUtil.when(() -> IdentityUtil.getPrimaryDomainName()).thenReturn(UserCoreConstants.PRIMARY_DEFAULT_DOMAIN_NAME); + serviceURLBuilder.when(() -> ServiceURLBuilder.create()).thenReturn(defaultServiceURLBuilder); when(defaultServiceURLBuilder.build()).thenReturn(serviceURL); when(defaultServiceURLBuilder.addPath(SCIMCommonConstants.SCIM2_ENDPOINT)).thenReturn (defaultServiceURLBuilder1); when(defaultServiceURLBuilder1.build()).thenReturn(serviceURL1); when(serviceURL1.getAbsolutePublicURL()).thenReturn("https://localhost:9443/scim2"); when(serviceURL.getAbsolutePublicURL()).thenReturn("https://localhost:9443"); - when(IdentityTenantUtil.getTenantDomainFromContext()).thenReturn("carbon.super"); + identityTenantUtil.when(() -> IdentityTenantUtil.getTenantDomainFromContext()).thenReturn("carbon.super"); } @AfterMethod @@ -103,7 +96,7 @@ public void tearDown() throws Exception { @Test(dataProvider = "tenantURLQualifyData") public void testGetSCIMUserURL(boolean isTenantQualifyURLEnabled) throws Exception { - when(IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); + identityTenantUtil.when(() -> IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); String scimUserURL = SCIMCommonUtils.getSCIMUserURL(ID); assertEquals(scimUserURL, scimUserLocation + "/" + ID); } @@ -111,7 +104,7 @@ public void testGetSCIMUserURL(boolean isTenantQualifyURLEnabled) throws Excepti @Test(dataProvider = "tenantURLQualifyData") public void testGetSCIMUserURLForNullId(boolean isTenantQualifyURLEnabled) throws Exception { - when(IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); + identityTenantUtil.when(() -> IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); String scimUserURL = SCIMCommonUtils.getSCIMUserURL(null); assertEquals(scimUserURL, null); } @@ -119,7 +112,7 @@ public void testGetSCIMUserURLForNullId(boolean isTenantQualifyURLEnabled) throw @Test(dataProvider = "tenantURLQualifyData") public void testGetSCIMGroupURL(boolean isTenantQualifyURLEnabled) throws Exception { - when(IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); + identityTenantUtil.when(() -> IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); String scimGroupURL = SCIMCommonUtils.getSCIMGroupURL(ID); assertEquals(scimGroupURL, scimGroupLocation + "/" + ID); } @@ -127,7 +120,7 @@ public void testGetSCIMGroupURL(boolean isTenantQualifyURLEnabled) throws Except @Test(dataProvider = "tenantURLQualifyData") public void testGetSCIMGroupURLForNullId(boolean isTenantQualifyURLEnabled) throws Exception { - when(IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); + identityTenantUtil.when(() -> IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); String scimGroupURL = SCIMCommonUtils.getSCIMGroupURL(null); assertEquals(scimGroupURL, null); } @@ -135,7 +128,7 @@ public void testGetSCIMGroupURLForNullId(boolean isTenantQualifyURLEnabled) thro @Test(dataProvider = "tenantURLQualifyData") public void testGetSCIMServiceProviderConfigURL(boolean isTenantQualifyURLEnabled) throws Exception { - when(IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); + identityTenantUtil.when(() -> IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); String scimServiceProviderConfigURL = SCIMCommonUtils.getSCIMServiceProviderConfigURL(ID); assertEquals(scimServiceProviderConfigURL, scimServiceProviderConfig); } @@ -143,7 +136,7 @@ public void testGetSCIMServiceProviderConfigURL(boolean isTenantQualifyURLEnable @Test(dataProvider = "tenantURLQualifyData") public void testGetSCIMUserURL1(boolean isTenantQualifyURLEnabled) throws Exception { - when(IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); + identityTenantUtil.when(() -> IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); String scimUsersURL = SCIMCommonUtils.getSCIMUserURL(); assertEquals(scimUsersURL, scimUserLocation); } @@ -151,7 +144,7 @@ public void testGetSCIMUserURL1(boolean isTenantQualifyURLEnabled) throws Except @Test(dataProvider = "tenantURLQualifyData") public void testGetSCIMGroupURL1(boolean isTenantQualifyURLEnabled) throws Exception { - when(IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); + identityTenantUtil.when(() -> IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); String scimGroupsURL = SCIMCommonUtils.getSCIMGroupURL(); assertEquals(scimGroupsURL, scimGroupLocation); } @@ -159,7 +152,7 @@ public void testGetSCIMGroupURL1(boolean isTenantQualifyURLEnabled) throws Excep @Test(dataProvider = "tenantURLQualifyData") public void testGetSCIMServiceProviderConfigURL1(boolean isTenantQualifyURLEnabled) throws Exception { - when(IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); + identityTenantUtil.when(() -> IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); String scimServiceProviderConfigURL = SCIMCommonUtils.getSCIMServiceProviderConfigURL(); assertEquals(scimServiceProviderConfigURL, scimServiceProviderConfig); } @@ -167,7 +160,7 @@ public void testGetSCIMServiceProviderConfigURL1(boolean isTenantQualifyURLEnabl @Test(dataProvider = "tenantURLQualifyData") public void testGetSCIMResourceTypeURL(boolean isTenantQualifyURLEnabled) throws Exception { - when(IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); + identityTenantUtil.when(() -> IdentityTenantUtil.isTenantQualifiedUrlsEnabled()).thenReturn(isTenantQualifyURLEnabled); String scimResourceTypeURL = SCIMCommonUtils.getSCIMResourceTypeURL(); assertEquals(scimResourceTypeURL, scimResourceType); } @@ -249,7 +242,7 @@ public void testSetThreadLocalIsManagedThroughSCIMEP(Boolean value, Boolean expe public void testGetGlobalConsumerId() throws Exception { String tenantDomain = "testTenantDomain"; CommonTestUtils.initPrivilegedCarbonContext(tenantDomain); - when(IdentityTenantUtil.getTenantDomainFromContext()).thenReturn(tenantDomain); + identityTenantUtil.when(() -> IdentityTenantUtil.getTenantDomainFromContext()).thenReturn(tenantDomain); assertEquals(SCIMCommonUtils.getGlobalConsumerId(), tenantDomain); } @@ -257,7 +250,7 @@ public void testGetGlobalConsumerId() throws Exception { public void testGetUserConsumerId() throws Exception { String userConsumerId = "testConsumerId"; CommonTestUtils.initPrivilegedCarbonContext(); - when(UserCoreUtil.addTenantDomainToEntry(anyString(), anyString())).thenReturn(userConsumerId); + userCoreUtil.when(() -> UserCoreUtil.addTenantDomainToEntry(anyString(), anyString())).thenReturn(userConsumerId); assertEquals(SCIMCommonUtils.getUserConsumerId(), userConsumerId); } diff --git a/pom.xml b/pom.xml index 52d30c9ba..1d84407dd 100644 --- a/pom.xml +++ b/pom.xml @@ -230,15 +230,9 @@ test - org.powermock - powermock-module-testng - ${powermock.version} - test - - - org.powermock - powermock-api-mockito2 - ${powermock.version} + org.mockito + mockito-testng + ${mockito-testng.version} test @@ -328,12 +322,12 @@ 1.7.21 - 6.9.10 + 7.10.1 0.8.4 - 2.23.4 - 2.0.2 - 2.22.2 + 3.2.5 + 5.3.1 + 0.5.2 1.10.1 From 6e835c8533e70a7135436874af57b134beafc23a Mon Sep 17 00:00:00 2001 From: kumuditha Date: Tue, 27 Aug 2024 11:37:07 +0530 Subject: [PATCH 02/13] Fix unit tests SCIMCommonUtilsTest --- .../identity/scim2/common/utils/SCIMCommonUtilsTest.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/SCIMCommonUtilsTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/SCIMCommonUtilsTest.java index 658407d6a..493cdb9d0 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/SCIMCommonUtilsTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/SCIMCommonUtilsTest.java @@ -89,7 +89,11 @@ public void setUp() throws Exception { } @AfterMethod - public void tearDown() throws Exception { + public void tearDown() { + identityUtil.close(); + userCoreUtil.close(); + identityTenantUtil.close(); + serviceURLBuilder.close(); System.clearProperty(CarbonBaseConstants.CARBON_HOME); } From 16694e0dac7c36e2288ec2e094eada70309b27d9 Mon Sep 17 00:00:00 2001 From: kumuditha Date: Tue, 27 Aug 2024 11:38:32 +0530 Subject: [PATCH 03/13] Fix unit tests AdminAttributeUtilTest --- .../common/utils/AdminAttributeUtilTest.java | 24 +++++++++++-------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTest.java index 23d73e2c2..0fde819e8 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTest.java @@ -21,22 +21,22 @@ import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockedStatic; +import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; -import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.scim2.common.internal.SCIMCommonComponentHolder; import org.wso2.carbon.stratos.common.util.ClaimsMgtUtil; import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.core.UserStoreManager; import org.wso2.carbon.user.core.service.RealmService; -import org.wso2.carbon.user.core.util.UserCoreUtil; import java.util.Map; import static org.mockito.Mockito.*; +import static org.mockito.MockitoAnnotations.initMocks; public class AdminAttributeUtilTest { @@ -53,12 +53,22 @@ public class AdminAttributeUtilTest { private MockedStatic scimCommonComponentHolder; private MockedStatic claimsMgtUtil; - -private MockedStatic identityTenantUtil; + private MockedStatic identityTenantUtil; @BeforeMethod public void setUp() throws Exception { + initMocks(this); adminAttributeUtil = new AdminAttributeUtil(); + scimCommonComponentHolder = mockStatic(SCIMCommonComponentHolder.class); + claimsMgtUtil = mockStatic(ClaimsMgtUtil.class); + identityTenantUtil = mockStatic(IdentityTenantUtil.class); + } + + @AfterMethod + public void tearDown() throws Exception { + scimCommonComponentHolder.close(); + claimsMgtUtil.close(); + identityTenantUtil.close(); } @DataProvider(name = "testUpdateAdminUserData") @@ -73,9 +83,6 @@ public Object[][] testUpdateAdminUserData() { public void testUpdateAdminUser(boolean validateSCIMID) throws Exception { String adminUsername = "admin"; - scimCommonComponentHolder = mockStatic(SCIMCommonComponentHolder.class); - claimsMgtUtil = mockStatic(ClaimsMgtUtil.class); - identityTenantUtil = mockStatic(IdentityTenantUtil.class); scimCommonComponentHolder.when(() -> SCIMCommonComponentHolder.getRealmService()).thenReturn(realmService); when(realmService.getTenantUserRealm(anyInt())).thenReturn(userRealm); when(userRealm.getUserStoreManager()).thenReturn(userStoreManager); @@ -91,9 +98,6 @@ public void testUpdateAdminUser(boolean validateSCIMID) throws Exception { @Test(expectedExceptions = UserStoreException.class) public void testUpdateAdminUser1() throws Exception { - scimCommonComponentHolder = mockStatic(SCIMCommonComponentHolder.class); - claimsMgtUtil = mockStatic(ClaimsMgtUtil.class); - identityTenantUtil = mockStatic(IdentityTenantUtil.class); scimCommonComponentHolder.when(() -> SCIMCommonComponentHolder.getRealmService()).thenReturn(realmService); when(realmService.getTenantUserRealm(anyInt())).thenReturn(userRealm); when(userRealm.getUserStoreManager()).thenReturn(userStoreManager); From 88d43d42a8545885bab50c386cc324989c96ae4c Mon Sep 17 00:00:00 2001 From: kumuditha Date: Tue, 27 Aug 2024 11:39:22 +0530 Subject: [PATCH 04/13] Fix unit tests AdminAttributeUtilTestForGroup --- .../utils/AdminAttributeUtilTestForGroup.java | 46 ++++++++++++------- 1 file changed, 29 insertions(+), 17 deletions(-) diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTestForGroup.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTestForGroup.java index 3c43e1689..255f0193e 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTestForGroup.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTestForGroup.java @@ -20,7 +20,9 @@ import org.mockito.ArgumentCaptor; import org.mockito.Mock; +import org.mockito.MockedConstruction; import org.mockito.MockedStatic; +import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -40,6 +42,7 @@ import static org.mockito.Mockito.*; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.MockitoAnnotations.initMocks; import static org.testng.Assert.assertEquals; public class AdminAttributeUtilTestForGroup { @@ -70,7 +73,24 @@ public class AdminAttributeUtilTestForGroup { @BeforeMethod public void setUp() throws Exception { + initMocks(this); adminAttributeUtil = new AdminAttributeUtil(); + scimCommonComponentHolder = mockStatic(SCIMCommonComponentHolder.class); + claimsMgtUtil = mockStatic(ClaimsMgtUtil.class); + identityTenantUtil = mockStatic(IdentityTenantUtil.class); + userCoreUtil = mockStatic(UserCoreUtil.class); + identityUtil = mockStatic(IdentityUtil.class); + scimCommonUtils = mockStatic(SCIMCommonUtils.class); + } + + @AfterMethod + public void tearDown() { + scimCommonComponentHolder.close(); + claimsMgtUtil.close(); + identityTenantUtil.close(); + userCoreUtil.close(); + identityUtil.close(); + scimCommonUtils.close(); } @DataProvider(name = "testUpdateAdminUserData") @@ -93,12 +113,6 @@ public Object[][] testUpdateAdminGroupData() { public void testUpdateAdminGroup(String domainName) throws Exception { String roleNameWithDomain = "TESTDOMAIN/admin"; - scimCommonComponentHolder = mockStatic(SCIMCommonComponentHolder.class); - claimsMgtUtil = mockStatic(ClaimsMgtUtil.class); - identityTenantUtil = mockStatic(IdentityTenantUtil.class); - userCoreUtil = mockStatic(UserCoreUtil.class); - identityUtil = mockStatic(IdentityUtil.class); - scimCommonUtils = mockStatic(SCIMCommonUtils.class); scimCommonComponentHolder.when(() -> SCIMCommonComponentHolder.getRealmService()).thenReturn(realmService); when(realmService.getTenantUserRealm(anyInt())).thenReturn(userRealm); when(userRealm.getUserStoreManager()).thenReturn(userStoreManager); @@ -112,24 +126,22 @@ public void testUpdateAdminGroup(String domainName) throws Exception { userCoreUtil.when(() -> UserCoreUtil.addDomainToName(anyString(), anyString())).thenReturn(roleNameWithDomain); scimCommonUtils.when(() -> SCIMCommonUtils.getGroupNameWithDomain(anyString())).thenReturn(roleNameWithDomain); - ArgumentCaptor argument = ArgumentCaptor.forClass(String.class); - CarbonConstants.ENABLE_LEGACY_AUTHZ_RUNTIME = true; - adminAttributeUtil.updateAdminGroup(1); - verify(scimGroupHandler).addMandatoryAttributes(argument.capture()); + try (MockedConstruction mocked = mockConstruction(SCIMGroupHandler.class, (mock, context) -> { + when(mock.isGroupExisting(anyString())).thenReturn(false); + })) { + ArgumentCaptor argument = ArgumentCaptor.forClass(String.class); + CarbonConstants.ENABLE_LEGACY_AUTHZ_RUNTIME = true; + adminAttributeUtil.updateAdminGroup(1); + verify(mocked.constructed().get(0)).addMandatoryAttributes(argument.capture()); - assertEquals(argument.getValue(), roleNameWithDomain); + assertEquals(argument.getValue(), roleNameWithDomain); + } } @Test(expectedExceptions = IdentitySCIMException.class) public void testUpdateAdminGroup1() throws Exception { String roleNameWithDomain = "TESTDOMAIN/admin"; - scimCommonComponentHolder = mockStatic(SCIMCommonComponentHolder.class); - claimsMgtUtil = mockStatic(ClaimsMgtUtil.class); - identityTenantUtil = mockStatic(IdentityTenantUtil.class); - userCoreUtil = mockStatic(UserCoreUtil.class); - identityUtil = mockStatic(IdentityUtil.class); - scimCommonUtils = mockStatic(SCIMCommonUtils.class); scimCommonComponentHolder.when(() -> SCIMCommonComponentHolder.getRealmService()).thenReturn(realmService); when(realmService.getTenantUserRealm(anyInt())).thenReturn(userRealm); when(userRealm.getUserStoreManager()).thenReturn(userStoreManager); From 1c74882ef438e2d1495be7480e6a590b9621bf04 Mon Sep 17 00:00:00 2001 From: kumuditha Date: Tue, 27 Aug 2024 11:40:06 +0530 Subject: [PATCH 05/13] Fix unit tests IdentityResourceURLBuilderTest --- .../scim2/common/impl/IdentityResourceURLBuilderTest.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentityResourceURLBuilderTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentityResourceURLBuilderTest.java index e7469b101..4d2d23921 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentityResourceURLBuilderTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentityResourceURLBuilderTest.java @@ -21,6 +21,7 @@ import org.mockito.Mock; import org.mockito.MockedStatic; +import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -68,6 +69,12 @@ public void setUpMethod() { identityTenantUtil = mockStatic(IdentityTenantUtil.class); } + @AfterMethod + public void tearDownMethod() { + serviceURLBuilder.close(); + identityTenantUtil.close(); + } + @DataProvider(name = "dataProviderForBuild") public Object[][] dataProviderForBuild() { From 05a67745adb5009264f4894115c31071ac5848d8 Mon Sep 17 00:00:00 2001 From: kumuditha Date: Tue, 27 Aug 2024 11:41:03 +0530 Subject: [PATCH 06/13] Fix unit tests IdentitySCIMManagerTest --- .../common/impl/IdentitySCIMManagerTest.java | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentitySCIMManagerTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentitySCIMManagerTest.java index 8762697b0..ff6d4118e 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentitySCIMManagerTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentitySCIMManagerTest.java @@ -20,23 +20,24 @@ import org.mockito.Mock; import org.mockito.MockedStatic; +import org.mockito.quality.Strictness; +import org.mockito.testng.MockitoSettings; +import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.testng.annotations.Listeners; import org.mockito.testng.MockitoTestNGListener; -import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.base.CarbonBaseConstants; import org.wso2.carbon.identity.scim2.common.internal.SCIMCommonComponentHolder; import org.wso2.carbon.identity.scim2.common.test.utils.CommonTestUtils; import org.wso2.carbon.identity.scim2.common.utils.SCIMCommonUtils; import org.wso2.carbon.identity.scim2.common.utils.SCIMConfigProcessor; import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.user.core.UserStoreManager; import org.wso2.carbon.user.core.claim.ClaimManager; import org.wso2.carbon.user.core.common.AbstractUserStoreManager; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.tenant.TenantManager; -import org.wso2.charon3.core.config.CharonConfiguration; import org.wso2.charon3.core.exceptions.CharonException; import org.wso2.charon3.core.extensions.UserManager; @@ -53,6 +54,7 @@ * Contains the unit test cases for IdentitySCIMManager. */ @Listeners(MockitoTestNGListener.class) +@MockitoSettings(strictness = Strictness.LENIENT) public class IdentitySCIMManagerTest { @Mock @@ -78,7 +80,6 @@ public class IdentitySCIMManagerTest { @BeforeMethod public void setUp() throws Exception { - scimCommonUtils = mockStatic(SCIMCommonUtils.class); scimCommonUtils.when(() -> SCIMCommonUtils.getSCIMUserURL()).thenReturn("http://scimUserUrl:9443"); @@ -91,8 +92,6 @@ public void setUp() throws Exception { scimConfigProcessor.buildConfigFromFile(filePath); identitySCIMManager = IdentitySCIMManager.getInstance(); - scimCommonComponentHolder = mockStatic(SCIMCommonComponentHolder.class); - when(realmService.getTenantManager()).thenReturn(mockedTenantManager); when(mockedTenantManager.getTenantId(anyString())).thenReturn(-1234); when(realmService.getTenantUserRealm(anyInt())).thenReturn(mockedUserRealm); @@ -102,6 +101,13 @@ public void setUp() throws Exception { CommonTestUtils.initPrivilegedCarbonContext(); } + @AfterMethod + public void tearDown() { + scimCommonComponentHolder.close(); + scimCommonUtils.close(); + System.clearProperty(CarbonBaseConstants.CARBON_HOME); + } + @Test public void testGetInstance() throws Exception { From 7636b55e62ff4000e9c7898b81151f3f31b4af06 Mon Sep 17 00:00:00 2001 From: kumuditha Date: Tue, 27 Aug 2024 11:42:03 +0530 Subject: [PATCH 07/13] Fix unit tests SCIMGroupHandlerTest --- .../common/group/SCIMGroupHandlerTest.java | 163 ++++++++++-------- 1 file changed, 94 insertions(+), 69 deletions(-) diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/group/SCIMGroupHandlerTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/group/SCIMGroupHandlerTest.java index 8bf0f8c25..be61bc7a6 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/group/SCIMGroupHandlerTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/group/SCIMGroupHandlerTest.java @@ -21,22 +21,26 @@ import org.apache.commons.lang.StringUtils; import org.mockito.ArgumentCaptor; import org.mockito.Mock; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; +import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import org.wso2.carbon.base.CarbonBaseConstants; import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.scim2.common.DAO.GroupDAO; import org.wso2.carbon.identity.scim2.common.exceptions.IdentitySCIMException; import org.wso2.carbon.identity.scim2.common.utils.SCIMCommonUtils; import org.wso2.charon3.core.objects.Group; +import org.wso2.charon3.core.utils.AttributeUtil; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.text.SimpleDateFormat; +import java.time.Instant; import java.util.Date; import java.util.HashMap; import java.util.Map; @@ -44,25 +48,21 @@ import java.util.Set; import java.util.HashSet; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.anyMap; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; -import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; -import static org.powermock.api.mockito.PowerMockito.whenNew; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.AssertJUnit.assertTrue; -@PrepareForTest({IdentityDatabaseUtil.class, StringUtils.class, SCIMCommonUtils.class, SCIMGroupHandler.class, - IdentityTenantUtil.class}) -@PowerMockIgnore("java.sql.*") -public class SCIMGroupHandlerTest extends PowerMockTestCase { +public class SCIMGroupHandlerTest { @Mock private GroupDAO mockedGroupDAO; @@ -73,16 +73,32 @@ public class SCIMGroupHandlerTest extends PowerMockTestCase { @Mock private PreparedStatement mockedPreparedStatement; + private MockedStatic scimCommonUtils; + private MockedStatic identityDatabaseUtil; + private MockedStatic identityTenantUtil; + private MockedStatic stringUtils; + @BeforeMethod public void setUp() throws Exception { initMocks(this); + scimCommonUtils = mockStatic(SCIMCommonUtils.class); + identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + identityTenantUtil = mockStatic(IdentityTenantUtil.class); + stringUtils = mockStatic(StringUtils.class); + } + + @AfterMethod + public void tearDown() throws Exception { + scimCommonUtils.close(); + identityDatabaseUtil.close(); + identityTenantUtil.close(); + stringUtils.close(); + System.clearProperty(CarbonBaseConstants.CARBON_HOME); } @Test public void testAddMandatoryAttributes() throws Exception { ResultSet resultSet = mock(ResultSet.class); - mockStatic(SCIMCommonUtils.class); - mockStatic(IdentityDatabaseUtil.class); when(SCIMCommonUtils.getSCIMGroupURL(anyString())).thenReturn("ID"); when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection); @@ -110,8 +126,6 @@ public void testGetGroupAttributesById() throws Exception { @Test public void testCreateSCIMAttributes() throws Exception { ResultSet resultSet = mock(ResultSet.class); - mockStatic(IdentityDatabaseUtil.class); - mockStatic(SCIMCommonUtils.class); Group group = new Group(); Date date = new Date(); @@ -132,8 +146,6 @@ public void testCreateSCIMAttributes() throws Exception { @Test public void testCreateSCIMAttributesExceptions() throws Exception { - mockStatic(IdentityDatabaseUtil.class); - mockStatic(SCIMCommonUtils.class); ResultSet resultSet = mock(ResultSet.class); Group group = new Group(); @@ -147,22 +159,26 @@ public void testCreateSCIMAttributesExceptions() throws Exception { when(connection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); when(mockedPreparedStatement.executeQuery()).thenReturn(resultSet); when(resultSet.next()).thenReturn(true); - whenNew(GroupDAO.class).withNoArguments().thenReturn(mockedGroupDAO); - when(mockedGroupDAO.isExistingGroup(SCIMCommonUtils.getGroupNameWithDomain("ALREADY_EXISTANT_GROUP_NAME"), 1)).thenReturn(false); - SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(1); - ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); - scimGroupHandler.createSCIMAttributes(group); - verify(mockedGroupDAO).addSCIMGroupAttributes(anyInt(), argumentCaptor.capture(), anyMap()); - assertEquals("testDisplayName", argumentCaptor.getValue()); + try (MockedConstruction mockedConstruction = Mockito.mockConstruction( + GroupDAO.class, + (mock, context) -> { + when(mock.isExistingGroup(SCIMCommonUtils.getGroupNameWithDomain("ALREADY_EXISTANT_GROUP_NAME"), 1)) + .thenReturn(false); + })) { + + SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(1); + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); + scimGroupHandler.createSCIMAttributes(group); + verify(mockedConstruction.constructed().get(0)) + .addSCIMGroupAttributes(anyInt(), argumentCaptor.capture(), anyMap()); + assertEquals("testDisplayName", argumentCaptor.getValue()); + } } @Test public void testGetGroupName() throws Exception { ResultSet resultSet = mock(ResultSet.class); - mockStatic(IdentityDatabaseUtil.class); - mockStatic(StringUtils.class); - mockStatic(SCIMCommonUtils.class); when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); @@ -185,9 +201,6 @@ public void testGetGroupId() throws Exception { public void testGetGroupWithAttributes() throws Exception { Group group = new Group(); ResultSet resultSet = mock(ResultSet.class); - mockStatic(SCIMCommonUtils.class); - mockStatic(IdentityDatabaseUtil.class); - mockStatic(StringUtils.class); Date date = new Date(2017, 10, 10, 10, 10, 10); Map attributes = new HashMap(); @@ -208,9 +221,6 @@ public void testGetGroupWithAttributes() throws Exception { public void testGetGroupWithAttributesSecondScenario() throws Exception { Group group = new Group(); ResultSet resultSet = mock(ResultSet.class); - mockStatic(IdentityDatabaseUtil.class); - mockStatic(IdentityTenantUtil.class); - mockStatic(SCIMCommonUtils.class); Date today = Calendar.getInstance().getTime(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); @@ -226,18 +236,28 @@ public void testGetGroupWithAttributesSecondScenario() throws Exception { when(resultSet.next()).thenReturn(true); when(mockedPreparedStatement.executeQuery()).thenReturn(resultSet); when(mockedGroupDAO.isExistingGroup("EXISTING_GROUP_NAME", 1)).thenReturn(true); - whenNew(GroupDAO.class).withNoArguments().thenReturn(mockedGroupDAO); - when(mockedGroupDAO.getSCIMGroupAttributes(anyInt(), anyString())).thenReturn(attributes); when(IdentityTenantUtil.getTenantDomain(1)).thenReturn("TENANT_DOMAIN"); when(SCIMCommonUtils.getSCIMGroupURL()).thenReturn("https://localhost:9443/t/TENANT_DOMAIN/Groups"); - assertEquals(new SCIMGroupHandler(1).getGroupWithAttributes(group, "EXISTING_GROUP_NAME"), group); + + Instant mockInstant = Instant.now(); + try (MockedStatic mockedAttributeUtil = Mockito.mockStatic(AttributeUtil.class)) { + mockedAttributeUtil.when(() -> AttributeUtil.parseDateTime(anyString())).thenReturn(mockInstant); + + try (MockedConstruction mockedConstruction = Mockito.mockConstruction( + GroupDAO.class, + (mock, context) -> { + when(mock.getSCIMGroupAttributes(anyInt(), anyString())).thenReturn(attributes); + })) { + + SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(1); + assertEquals(scimGroupHandler.getGroupWithAttributes(group, "EXISTING_GROUP_NAME"), group); + } + } } @Test public void testIsGroupExisting() throws Exception { ResultSet resultSet = mock(ResultSet.class); - mockStatic(IdentityDatabaseUtil.class); - mockStatic(SCIMCommonUtils.class); when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); @@ -254,61 +274,66 @@ public void testIsGroupExisting() throws Exception { @Test public void testDeleteGroupAttributes() throws Exception { ResultSet resultSet = mock(ResultSet.class); - mockStatic(IdentityDatabaseUtil.class); - mockStatic(SCIMCommonUtils.class); - when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); when(mockedPreparedStatement.executeQuery()).thenReturn(resultSet); - whenNew(GroupDAO.class).withNoArguments().thenReturn(mockedGroupDAO); when(resultSet.next()).thenReturn(true); - when(mockedGroupDAO.isExistingGroup(anyString(), anyInt())).thenReturn(true); - - SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(1); - ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); - scimGroupHandler.deleteGroupAttributes("GROUP_DELETABLE"); - verify(mockedGroupDAO).removeSCIMGroup(anyInt(), argumentCaptor.capture()); - assertEquals(argumentCaptor.getValue(),"GROUP_DELETABLE"); + try (MockedConstruction mockedConstruction = Mockito.mockConstruction( + GroupDAO.class, + (mock, context) -> { + when(mock.isExistingGroup(anyString(), anyInt())).thenReturn(true); + })) { + + SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(1); + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); + scimGroupHandler.deleteGroupAttributes("GROUP_DELETABLE"); + verify(mockedConstruction.constructed().get(0)).removeSCIMGroup(anyInt(), argumentCaptor.capture()); + assertEquals(argumentCaptor.getValue(), "GROUP_DELETABLE"); + } } @Test public void testUpdateRoleName() throws Exception { ResultSet resultSet = mock(ResultSet.class); - mockStatic(IdentityDatabaseUtil.class); - mockStatic(SCIMCommonUtils.class); when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection); - whenNew(GroupDAO.class).withNoArguments().thenReturn(mockedGroupDAO); - when(mockedGroupDAO.isExistingGroup(anyString(), anyInt())).thenReturn(true); - SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(1); - ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); - scimGroupHandler.updateRoleName("EXISTENT_ROLE_NAME", "NEW_ROLE_NAME"); - verify(mockedGroupDAO).updateRoleName(anyInt(),argumentCaptor.capture(),anyString()); - assertEquals(argumentCaptor.getValue(),"EXISTENT_ROLE_NAME"); + try (MockedConstruction mockedConstruction = Mockito.mockConstruction( + GroupDAO.class, + (mock, context) -> { + when(mock.isExistingGroup(anyString(), anyInt())).thenReturn(true); + })) { + + SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(1); + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); + scimGroupHandler.updateRoleName("EXISTENT_ROLE_NAME", "NEW_ROLE_NAME"); + verify(mockedConstruction.constructed().get(0)).updateRoleName(anyInt(), argumentCaptor.capture(), anyString()); + assertEquals(argumentCaptor.getValue(), "EXISTENT_ROLE_NAME"); + } } @Test(expectedExceptions = IdentitySCIMException.class) public void testUpdateRoleNameNonExistent() throws Exception { ResultSet resultSet = mock(ResultSet.class); - mockStatic(IdentityDatabaseUtil.class); - mockStatic(SCIMCommonUtils.class); when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection); - whenNew(GroupDAO.class).withNoArguments().thenReturn(mockedGroupDAO); - when(mockedGroupDAO.isExistingGroup("NON_EXISTENT_ROLE_NAME", 1)).thenReturn(false); - SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(1); - scimGroupHandler.updateRoleName("NON_EXISTENT_ROLE_NAME", "NEW_ROLE_NAME"); - // This method is to test the throwing of an IdentitySCIMException, hence no assertion. + try (MockedConstruction mockedConstruction = Mockito.mockConstruction( + GroupDAO.class, + (mock, context) -> { + when(mock.isExistingGroup("NON_EXISTENT_ROLE_NAME", 1)).thenReturn(false); + })) { + + SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(1); + scimGroupHandler.updateRoleName("NON_EXISTENT_ROLE_NAME", "NEW_ROLE_NAME"); + } } @Test public void testListSCIMRoles() throws Exception { Set groups = mock(HashSet.class); ResultSet resultSet = mock(ResultSet.class); - mockStatic(IdentityDatabaseUtil.class); when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); From 5d2e94615066505e13dc74000d268ca35f3b20d2 Mon Sep 17 00:00:00 2001 From: kumuditha Date: Tue, 27 Aug 2024 11:43:54 +0530 Subject: [PATCH 08/13] Fix unit tests SCIMRoleManagerTest --- .../common/impl/SCIMRoleManagerTest.java | 74 +++++++++++-------- 1 file changed, 42 insertions(+), 32 deletions(-) diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManagerTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManagerTest.java index 8ac8b3e76..5c0954b7e 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManagerTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManagerTest.java @@ -20,8 +20,9 @@ import org.apache.commons.lang.StringUtils; import org.mockito.Mock; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; +import org.mockito.MockedStatic; +import org.mockito.MockitoAnnotations; +import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; @@ -63,17 +64,17 @@ import java.util.HashSet; import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyListOf; +import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; -import static org.powermock.api.mockito.PowerMockito.doNothing; -import static org.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertThrows; import static org.testng.Assert.assertTrue; @@ -87,8 +88,7 @@ /** * Contains the unit test cases for SCIMRoleManager. */ -@PrepareForTest({SCIMCommonUtils.class, OrganizationManagementUtil.class}) -public class SCIMRoleManagerTest extends PowerMockTestCase { +public class SCIMRoleManagerTest { private static final String SAMPLE_TENANT_DOMAIN = "carbon.super"; private static final String SAMPLE_TENANT_DOMAIN2 = "abc.com"; @@ -121,6 +121,9 @@ public class SCIMRoleManagerTest extends PowerMockTestCase { @Mock RoleManagementService mockRoleManagementService; + private MockedStatic scimCommonUtils; + private MockedStatic organizationManagementUtil; + @BeforeClass public void setUpClass() { @@ -129,13 +132,20 @@ public void setUpClass() { @BeforeMethod public void setUpMethod() { - - mockStatic(SCIMCommonUtils.class); - mockStatic(OrganizationManagementUtil.class); + MockitoAnnotations.openMocks(this); + scimCommonUtils = mockStatic(SCIMCommonUtils.class); + organizationManagementUtil = mockStatic(OrganizationManagementUtil.class); when(SCIMCommonUtils.getSCIMRoleURL(nullable(String.class))).thenReturn(DUMMY_SCIM_URL); when(mockRoleManagementService.getSystemRoles()).thenReturn(SYSTEM_ROLES); } + @AfterMethod + public void tearDownMethod() { + + scimCommonUtils.close(); + organizationManagementUtil.close(); + } + @DataProvider(name = "dataProviderForCreateRoleExistingRole") public Object[][] dataProviderForCreateRoleExistingRole() { @@ -163,8 +173,8 @@ public void testCreateRoleAddRoleExistingRoleName() OrganizationManagementException { Role role = getDummyRole(SAMPLE_VALID_ROLE_ID2, SAMPLE_EXISTING_ROLE_NAME); - when(mockRoleManagementService.addRole(anyString(), anyListOf(String.class), anyListOf(String.class), - anyListOf(String.class), anyString())).thenThrow( + when(mockRoleManagementService.addRole(anyString(), anyList(), anyList(), + anyList(), anyString())).thenThrow( new IdentityRoleManagementException(ROLE_ALREADY_EXISTS.getCode(), "Role already exist for the role name: " + SAMPLE_EXISTING_ROLE_NAME)); when(OrganizationManagementUtil.isOrganization(anyString())).thenReturn(false); @@ -179,8 +189,8 @@ public void testCreateRoleAddRoleInvalidRoleName() Role role = getDummyRole(SAMPLE_VALID_ROLE_ID, SAMPLE_INVALID_ROLE_NAME); - when(mockRoleManagementService.addRole(anyString(), anyListOf(String.class), anyListOf(String.class), - anyListOf(String.class), anyString())). + when(mockRoleManagementService.addRole(anyString(), anyList(), anyList(), + anyList(), anyString())). thenThrow(new IdentityRoleManagementClientException(INVALID_REQUEST.getCode(), String.format("Invalid role name: %s. Role names with the prefix: %s, is not allowed" + " to be created from externally in the system.", SAMPLE_INVALID_ROLE_NAME, @@ -206,8 +216,8 @@ public void testCreateRoleUnexpectedServerError(String roleId, String roleDispla OrganizationManagementException { Role role = getDummyRole(roleId, roleDisplayName); - when(mockRoleManagementService.addRole(anyString(), anyListOf(String.class), anyListOf(String.class), - anyListOf(String.class), anyString())). + when(mockRoleManagementService.addRole(anyString(), anyList(), anyList(), + anyList(), anyString())). thenThrow(unExpectedErrorThrower(tenantDomain, sError, "Error while creating the role: %s in the tenantDomain: %s", roleDisplayName)); when(OrganizationManagementUtil.isOrganization(anyString())).thenReturn(false); @@ -235,8 +245,8 @@ public void testCreateRolePositive(String roleId, String roleDisplayName, String OrganizationManagementException { Role role = getDummyRole(roleId, roleDisplayName); - when(mockRoleManagementService.addRole(nullable(String.class), anyListOf(String.class), anyListOf(String.class), - anyListOf(String.class), anyString())).thenReturn(new RoleBasicInfo(roleId, roleDisplayName)); + when(mockRoleManagementService.addRole(nullable(String.class), anyList(), anyList(), + anyList(), anyString())).thenReturn(new RoleBasicInfo(roleId, roleDisplayName)); when(OrganizationManagementUtil.isOrganization(anyString())).thenReturn(false); SCIMRoleManager scimRoleManager = new SCIMRoleManager(mockRoleManagementService, tenantDomain); Role createdRole = scimRoleManager.createRole(role); @@ -633,10 +643,10 @@ public void testUpdateRoleUpdateRoleName(String roleId, String oldRoleName, Stri Role[] oldAndNewRoles = getOldAndNewRoleDummies(roleId, oldRoleName, newRoleName, type); when(mockRoleManagementService.updateRoleName(anyString(), anyString(), anyString())).thenReturn(roleBasicInfo); when(mockRoleManagementService.updateUserListOfRole( - eq(roleId), anyListOf(String.class), anyListOf(String.class), anyString())).thenReturn(roleBasicInfo); - when(mockRoleManagementService.updateGroupListOfRole(eq(roleId), anyListOf(String.class), - anyListOf(String.class), anyString())).thenReturn(roleBasicInfo); - when(mockRoleManagementService.setPermissionsForRole(eq(roleId), anyListOf(String.class), anyString())). + eq(roleId), anyList(), anyList(), anyString())).thenReturn(roleBasicInfo); + when(mockRoleManagementService.updateGroupListOfRole(eq(roleId), anyList(), + anyList(), anyString())).thenReturn(roleBasicInfo); + when(mockRoleManagementService.setPermissionsForRole(eq(roleId), anyList(), anyString())). thenReturn(roleBasicInfo); SCIMRoleManager scimRoleManager = new SCIMRoleManager(mockRoleManagementService, tenantDomain); @@ -725,7 +735,7 @@ public void testUpdateRoleUpdateUserListOfRoleThrowingErrors(String roleId, Stri when(mockRoleManagementService.updateRoleName(anyString(), anyString(), anyString())).thenReturn(roleBasicInfo); when(mockRoleManagementService.updateUserListOfRole( - anyString(), anyListOf(String.class), anyListOf(String.class), anyString())). + anyString(), anyList(), anyList(), anyString())). thenAnswer(invocationOnMock -> { String roleIdArg = invocationOnMock.getArgument(0); String tenantDomainArg = invocationOnMock.getArgument(3); @@ -770,7 +780,7 @@ public void testUpdateRoleUpdateGroupListOfRoleThrowingErrors(String roleId, Str Role[] oldAndNewRoles = getOldAndNewRoleDummies(roleId, oldRoleName, newRoleName, type); when(mockRoleManagementService.updateRoleName(anyString(), anyString(), anyString())).thenReturn(roleBasicInfo); when(mockRoleManagementService.updateGroupListOfRole( - anyString(), anyListOf(String.class), anyListOf(String.class), anyString())). + anyString(), anyList(), anyList(), anyString())). thenAnswer(invocationOnMock -> { String roleIdArg = invocationOnMock.getArgument(0); String tenantDomainArg = invocationOnMock.getArgument(3); @@ -785,8 +795,8 @@ public void testUpdateRoleUpdateGroupListOfRoleThrowingErrors(String roleId, Str if (unExpectedErrors != null) throw unExpectedErrors; return roleBasicInfo; }); - when(mockRoleManagementService.updateUserListOfRole(eq(roleId), anyListOf(String.class), - anyListOf(String.class), anyString())).thenReturn(roleBasicInfo); + when(mockRoleManagementService.updateUserListOfRole(eq(roleId), anyList(), + anyList(), anyString())).thenReturn(roleBasicInfo); SCIMRoleManager scimRoleManager = new SCIMRoleManager(mockRoleManagementService, tenantDomain); scimRoleManager.updateRole(oldAndNewRoles[0], oldAndNewRoles[1]); @@ -817,7 +827,7 @@ public void testRoleUpdatePermissionListOfRoleThrowingErrors(String roleId, Stri Role[] oldAndNewRoles = getOldAndNewRoleDummies(roleId, oldRoleName, newRoleName, permissionType); when(mockRoleManagementService.updateRoleName(anyString(), anyString(), anyString())).thenReturn(roleBasicInfo); when(mockRoleManagementService.setPermissionsForRole( - anyString(), anyListOf(String.class), anyString())). + anyString(), anyList(), anyString())). thenAnswer(invocationOnMock -> { String roleIdArg = invocationOnMock.getArgument(0); String tenantDomainArg = invocationOnMock.getArgument(2); @@ -838,10 +848,10 @@ public void testRoleUpdatePermissionListOfRoleThrowingErrors(String roleId, Stri if (unExpectedErrors != null) throw unExpectedErrors; return roleBasicInfo; }); - when(mockRoleManagementService.updateUserListOfRole(eq(roleId), anyListOf(String.class), - anyListOf(String.class), anyString())).thenReturn(roleBasicInfo); - when(mockRoleManagementService.updateGroupListOfRole(eq(roleId), anyListOf(String.class), - anyListOf(String.class), anyString())).thenReturn(roleBasicInfo); + when(mockRoleManagementService.updateUserListOfRole(eq(roleId), anyList(), + anyList(), anyString())).thenReturn(roleBasicInfo); + when(mockRoleManagementService.updateGroupListOfRole(eq(roleId), anyList(), + anyList(), anyString())).thenReturn(roleBasicInfo); SCIMRoleManager scimRoleManager = new SCIMRoleManager(mockRoleManagementService, tenantDomain); scimRoleManager.updateRole(oldAndNewRoles[0], oldAndNewRoles[1]); From 1347b99a20de2820f311d0dbe597668e981093ca Mon Sep 17 00:00:00 2001 From: kumuditha Date: Tue, 27 Aug 2024 11:44:30 +0530 Subject: [PATCH 09/13] Fix unit tests SCIMRoleManagerV2Test --- .../scim2/common/impl/SCIMRoleManagerV2Test.java | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManagerV2Test.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManagerV2Test.java index ea9b147bf..890de538f 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManagerV2Test.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManagerV2Test.java @@ -20,11 +20,12 @@ import org.mockito.Mock; import org.mockito.MockedStatic; +import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import org.wso2.carbon.identity.core.ServiceURLBuilder; +import org.wso2.carbon.base.CarbonBaseConstants; import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.role.v2.mgt.core.RoleManagementService; import org.wso2.carbon.identity.role.v2.mgt.core.exception.IdentityRoleManagementException; @@ -78,6 +79,12 @@ public void setUpMethod() { scimRoleManagerV2 = new SCIMRoleManagerV2(roleManagementService, SAMPLE_TENANT_DOMAIN); } + @AfterMethod + public void tearDown() { + identityUtil.close(); + System.clearProperty(CarbonBaseConstants.CARBON_HOME); + } + @DataProvider(name = "scimOperations") public Object[][] provideScimOperations() { From d0b195e3ce98f7c2650e289be4bd8f91b80192a2 Mon Sep 17 00:00:00 2001 From: kumuditha Date: Tue, 27 Aug 2024 11:45:17 +0530 Subject: [PATCH 10/13] Fix unit tests SCIMUserOperationListenerTest --- .../SCIMUserOperationListenerTest.java | 70 +++++++++++-------- 1 file changed, 41 insertions(+), 29 deletions(-) diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/listener/SCIMUserOperationListenerTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/listener/SCIMUserOperationListenerTest.java index e6d639d67..20b6ce6ea 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/listener/SCIMUserOperationListenerTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/listener/SCIMUserOperationListenerTest.java @@ -19,7 +19,10 @@ package org.wso2.carbon.identity.scim2.common.listener; import org.mockito.Mock; +import org.mockito.MockedConstruction; import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -30,7 +33,6 @@ import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.scim2.common.DAO.GroupDAO; import org.wso2.carbon.identity.scim2.common.exceptions.IdentitySCIMException; -import org.wso2.carbon.identity.scim2.common.group.SCIMGroupHandler; import org.wso2.carbon.identity.scim2.common.internal.SCIMCommonComponentHolder; import org.wso2.carbon.identity.scim2.common.utils.SCIMCommonUtils; import org.wso2.carbon.user.api.Permission; @@ -47,6 +49,7 @@ import java.util.UUID; import static org.mockito.Mockito.*; +import static org.mockito.MockitoAnnotations.initMocks; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; @@ -88,16 +91,25 @@ public class SCIMUserOperationListenerTest { @BeforeMethod public void setUp() throws Exception { - + initMocks(this); scimUserOperationListener = spy(new SCIMUserOperationListener()); userCoreUtil = mockStatic(UserCoreUtil.class); scimCommonUtils = mockStatic(SCIMCommonUtils.class); identityTenantUtil = mockStatic(IdentityTenantUtil.class); + identityUtil = mockStatic(IdentityUtil.class); SCIMCommonComponentHolder.setClaimManagementService(claimMetadataManagementService); when(userStoreManager.getTenantId()).thenReturn(-1234); identityTenantUtil.when(() -> IdentityTenantUtil.getTenantDomain(anyInt())).thenReturn(CARBON_SUPER); } + @AfterMethod + public void tearDown() { + userCoreUtil.close(); + scimCommonUtils.close(); + identityTenantUtil.close(); + identityUtil.close(); + } + @DataProvider(name = "testGetExecutionOrderIdData") public Object[][] testGetExecutionOrderIdData() { @@ -221,7 +233,6 @@ public void testDoPreSetUserClaimValues(boolean isEnabled, boolean isSCIMEnabled when(scimUserOperationListener.isEnable()).thenReturn(isEnabled); when(userStoreManager.isSCIMEnabled()).thenReturn(isSCIMEnabled); - identityUtil = mockStatic(IdentityUtil.class); identityUtil.when(() -> IdentityUtil.getProperty(FrameworkConstants.ENABLE_JIT_PROVISION_ENHANCE_FEATURE)).thenReturn("false"); assertTrue(scimUserOperationListener. @@ -294,19 +305,13 @@ public void testDoPostAddRole1() throws Exception { @Test(expectedExceptions = UserStoreException.class) public void testDoPostAddRole2() throws Exception { mockTestEnvironment(true, true, "testDomain"); - when(groupDAO.isExistingGroup(anyString(), anyInt())).thenThrow(new IdentitySCIMException - ("IdentitySCIMException")); - - scimUserOperationListener.doPostAddRoleWithID(roleName, userList, permissions, userStoreManager); - } - - @Test(dataProvider = "testDoPostAddRoleData") - public void testDoPreDeleteRole(boolean isEnabled, boolean isSCIMEnabled, boolean isGroupExisting, - String domainName) throws Exception { - mockTestEnvironment(isEnabled, isSCIMEnabled, domainName); - when(groupDAO.isExistingGroup(anyString(), anyInt())).thenReturn(isGroupExisting); - - assertTrue(scimUserOperationListener.doPreDeleteRole(roleName, userStoreManager)); + try (MockedConstruction mockedGroupDAO = Mockito.mockConstruction(GroupDAO.class, + (mock, context) -> { + when(mock.isExistingGroup(anyString(), anyInt())) + .thenThrow(new IdentitySCIMException("IdentitySCIMException")); + })) { + scimUserOperationListener.doPostAddRoleWithID(roleName, userList, permissions, userStoreManager); + } } @Test(expectedExceptions = UserStoreException.class) @@ -320,10 +325,13 @@ public void testDoPreDeleteRole1() throws Exception { @Test(expectedExceptions = UserStoreException.class) public void testDoPreDeleteRole2() throws Exception { mockTestEnvironment(true, true, "testDomain"); - when(groupDAO.isExistingGroup(anyString(), anyInt())).thenThrow(new IdentitySCIMException - ("IdentitySCIMException")); - - scimUserOperationListener.doPreDeleteRole(roleName, userStoreManager); + try (MockedConstruction mockedGroupDAO = Mockito.mockConstruction(GroupDAO.class, + (mock, context) -> { + when(mock.isExistingGroup(nullable(String.class), anyInt())) + .thenThrow(new IdentitySCIMException("IdentitySCIMException")); + })) { + scimUserOperationListener.doPreDeleteRole(roleName, userStoreManager); + } } @Test @@ -350,9 +358,12 @@ public Object[][] testDoPostUpdateRoleNameData() { @Test(dataProvider = "testDoPostUpdateRoleNameData") public void testDoPostUpdateRoleName(boolean isEnabled, boolean isSCIMEnabled, String domainName) throws Exception { mockTestEnvironment(isEnabled, isSCIMEnabled, domainName); - when(groupDAO.isExistingGroup(anyString(), anyInt())).thenReturn(true); - - assertTrue(scimUserOperationListener.doPostUpdateRoleName(roleName, roleName, userStoreManager)); + try (MockedConstruction mockedGroupDAO = Mockito.mockConstruction(GroupDAO.class, + (mock, context) -> { + when(mock.isExistingGroup(anyString(), anyInt())).thenReturn(true); + })) { + assertTrue(scimUserOperationListener.doPostUpdateRoleName(roleName, roleName, userStoreManager)); + } } @Test(expectedExceptions = UserStoreException.class) @@ -366,10 +377,13 @@ public void testDoPostUpdateRoleName1() throws Exception { @Test(expectedExceptions = UserStoreException.class) public void testDoPostUpdateRoleName2() throws Exception { mockTestEnvironment(true, true, "testDomain"); - when(groupDAO.isExistingGroup(anyString(), anyInt())) - .thenThrow(new IdentitySCIMException("IdentitySCIMException")); - - scimUserOperationListener.doPostUpdateRoleName(roleName, roleName, userStoreManager); + try (MockedConstruction mockedGroupDAO = Mockito.mockConstruction(GroupDAO.class, + (mock, context) -> { + when(mock.isExistingGroup(anyString(), anyInt())) + .thenThrow(new IdentitySCIMException("IdentitySCIMException")); + })) { + scimUserOperationListener.doPostUpdateRoleName(roleName, roleName, userStoreManager); + } } @Test @@ -413,7 +427,6 @@ public Object[][] testSCIMAttributesData() { @Test(dataProvider = "testSCIMAttributesData") public void testGetSCIMAttributes(Map claimsMap) throws Exception { - scimCommonUtils = mockStatic(SCIMCommonUtils.class); Map scimToLocalClaimsMap = new HashMap<>(); scimToLocalClaimsMap.put(SCIMConstants.CommonSchemaConstants.ID_URI, "http://wso2.org/claims/userid"); scimToLocalClaimsMap.put(SCIMConstants.CommonSchemaConstants.CREATED_URI, "http://wso2.org/claims/created"); @@ -428,7 +441,6 @@ public void testGetSCIMAttributes(Map claimsMap) throws Exceptio @Test(dataProvider = "testSCIMAttributesData") public void testPopulateSCIMAttributes(Map claimsMap) throws Exception { - scimCommonUtils = mockStatic(SCIMCommonUtils.class); Map scimToLocalClaimsMap = new HashMap<>(); scimToLocalClaimsMap.put(SCIMConstants.CommonSchemaConstants.ID_URI, "http://wso2.org/claims/userid"); scimToLocalClaimsMap.put(SCIMConstants.CommonSchemaConstants.CREATED_URI, "http://wso2.org/claims/created"); From 1a59e33c426b3aa233566c20ad4d29b8bebb8c0e Mon Sep 17 00:00:00 2001 From: kumuditha Date: Wed, 11 Sep 2024 12:02:58 +0530 Subject: [PATCH 11/13] Fix unit tests SCIMUserManagerTest --- .../common/impl/SCIMUserManagerTest.java | 188 ++++++++++-------- 1 file changed, 101 insertions(+), 87 deletions(-) diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMUserManagerTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMUserManagerTest.java index 3dfa12549..e7e9241ce 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMUserManagerTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMUserManagerTest.java @@ -1,7 +1,7 @@ /* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2017, WSO2 LLC. (https://www.wso2.org) * - * WSO2 Inc. licenses this file to you under the Apache License, + * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at @@ -20,13 +20,17 @@ import org.apache.commons.lang.StringUtils; import org.mockito.Mock; +import org.mockito.MockedConstruction; import org.mockito.MockedStatic; +import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; +import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.wso2.carbon.CarbonConstants; +import org.wso2.carbon.base.CarbonBaseConstants; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.identity.application.common.model.InboundProvisioningConfig; import org.wso2.carbon.identity.application.common.model.ServiceProvider; @@ -42,6 +46,9 @@ import org.wso2.carbon.identity.scim2.common.extenstion.SCIMUserStoreErrorResolver; import org.wso2.carbon.identity.scim2.common.group.SCIMGroupHandler; import org.wso2.carbon.identity.scim2.common.internal.SCIMCommonComponentHolder; +import org.wso2.carbon.user.core.UserStoreClientException; +import org.wso2.charon3.core.exceptions.NotImplementedException; +import org.wso2.charon3.core.extensions.UserManager; import org.wso2.charon3.core.objects.plainobjects.UsersGetResponse; import org.wso2.charon3.core.objects.plainobjects.GroupsGetResponse; import org.wso2.carbon.identity.scim2.common.test.utils.CommonTestUtils; @@ -79,11 +86,13 @@ import org.wso2.charon3.core.schema.SCIMDefinitions; import org.wso2.charon3.core.schema.SCIMResourceSchemaManager; import org.wso2.charon3.core.schema.SCIMResourceTypeSchema; +import org.wso2.charon3.core.utils.ResourceManagerUtil; import org.wso2.charon3.core.utils.codeutils.ExpressionNode; import org.wso2.charon3.core.utils.codeutils.FilterTreeManager; import org.wso2.charon3.core.utils.codeutils.Node; import org.wso2.charon3.core.utils.codeutils.SearchRequest; +import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -177,7 +186,6 @@ public class SCIMUserManagerTest { @Mock private RolePermissionManagementService mockedRolePermissionManagementService; - private MockedStatic scimUserSchemaExtensionBuilder; private MockedStatic identityUtil; private MockedStatic scimCommonUtils; @@ -185,12 +193,40 @@ public class SCIMUserManagerTest { private MockedStatic claimMetadataHandler; private MockedStatic carbonConstants; private MockedStatic identityTenantUtil; + private MockedStatic applicationManagementServiceMockedStatic; + private MockedStatic scimCommonComponentHolder; + private MockedStatic resourceManagerUtil; private MockedStatic userCoreUtil; @BeforeMethod - public void setUp() throws Exception { - + public void setUpMethod() { initMocks(this); + identityUtil = mockStatic(IdentityUtil.class); + scimCommonUtils = mockStatic(SCIMCommonUtils.class); + carbonConstants = mockStatic(CarbonConstants.class); + identityTenantUtil = mockStatic(IdentityTenantUtil.class); + applicationManagementServiceMockedStatic = mockStatic(ApplicationManagementService.class); + scimCommonComponentHolder = mockStatic(SCIMCommonComponentHolder.class); + scimUserSchemaExtensionBuilder = mockStatic(SCIMUserSchemaExtensionBuilder.class); + claimMetadataHandler = mockStatic(ClaimMetadataHandler.class); + resourceManagerUtil = mockStatic(ResourceManagerUtil.class); + SCIMUserSchemaExtensionBuilder mockSCIMUserSchemaExtensionBuilder = mock(SCIMUserSchemaExtensionBuilder.class); + scimUserSchemaExtensionBuilder.when(SCIMUserSchemaExtensionBuilder::getInstance).thenReturn(mockSCIMUserSchemaExtensionBuilder); + when(mockSCIMUserSchemaExtensionBuilder.getExtensionSchema()).thenReturn(mockedSCIMAttributeSchema); + } + + @AfterMethod + public void tearDown() { + identityUtil.close(); + scimCommonUtils.close(); + carbonConstants.close(); + identityTenantUtil.close(); + applicationManagementServiceMockedStatic.close(); + scimCommonComponentHolder.close(); + scimUserSchemaExtensionBuilder.close(); + claimMetadataHandler.close(); + resourceManagerUtil.close(); + System.clearProperty(CarbonBaseConstants.CARBON_HOME); } @DataProvider(name = "ClaimData") @@ -255,22 +291,20 @@ public void testGetMe(Object[] cMap, HashMap required, String[] when(mockedClaimManager.getAllClaimMappings(anyString())).thenReturn((ClaimMapping[]) cMap); SCIMUserSchemaExtensionBuilder sb = spy(new SCIMUserSchemaExtensionBuilder()); - scimUserSchemaExtensionBuilder = mockStatic(SCIMUserSchemaExtensionBuilder.class); - scimUserSchemaExtensionBuilder.when(() -> SCIMUserSchemaExtensionBuilder.getInstance()).thenReturn(sb); + scimUserSchemaExtensionBuilder.when(SCIMUserSchemaExtensionBuilder::getInstance).thenReturn(sb); when(sb.getExtensionSchema()).thenReturn(mockedSCIMAttributeSchema); - identityUtil = mockStatic(IdentityUtil.class); identityUtil.when(() -> IdentityUtil.extractDomainFromName(anyString())).thenReturn("testPrimaryDomain"); - scimCommonUtils = mockStatic(SCIMCommonUtils.class); scimCommonUtils.when(() -> SCIMCommonUtils.convertLocalToSCIMDialect(anyMap(), anyMap())).thenReturn(new HashMap() {{ put(SCIMConstants.CommonSchemaConstants.ID_URI, "1f70378a-69bb-49cf-aa51-a0493c09110c"); }}); mockedUserStoreManager = mock(AbstractUserStoreManager.class); - MemberModifier.field(AbstractUserStoreManager.class, "userStoreManagerHolder") - .set(mockedUserStoreManager, new HashMap()); + Field userStoreManagerHolderField = AbstractUserStoreManager.class.getDeclaredField("userStoreManagerHolder"); + userStoreManagerHolderField.setAccessible(true); + userStoreManagerHolderField.set(mockedUserStoreManager, new HashMap()); when(mockedUserStoreManager.getSecondaryUserStoreManager(anyString())).thenReturn(secondaryUserStoreManager); when(mockedUserStoreManager.isSCIMEnabled()).thenReturn(true); @@ -285,13 +319,13 @@ public void testGetMe(Object[] cMap, HashMap required, String[] user.setUserID(UUID.randomUUID().toString()); when(mockedUserStoreManager.getUser(anyString(), nullable(String.class))).thenReturn(user); CommonTestUtils.initPrivilegedCarbonContext(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); - claimMetadataHandler = mockStatic(ClaimMetadataHandler.class); - claimMetadataHandler.when(() -> ClaimMetadataHandler.getInstance()).thenReturn(mockClaimMetadataHandler); + claimMetadataHandler.when(ClaimMetadataHandler::getInstance).thenReturn(mockClaimMetadataHandler); when(mockClaimMetadataHandler.getMappingsFromOtherDialectToCarbon(anyString(), anySet(), anyString())) .thenReturn(new HashSet()); SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockedClaimManager); assertNotNull(scimUserManager.getMe("testUserName", required)); + attributeMapper.close(); } @Test(dataProvider = "groupName") @@ -299,14 +333,11 @@ public void testGetGroup(String groupId, String roleName, String userStoreDomain throws Exception { when(mockedGroupDAO.getGroupNameById(anyInt(), anyString())).thenReturn(roleName); - identityUtil = mockStatic(IdentityUtil.class); identityUtil.when(() -> IdentityUtil.extractDomainFromName(anyString())).thenReturn(userStoreDomain); when(mockedUserStoreManager.getGroup(groupId, null)). thenReturn(buildUserCoreGroupResponse(roleName, groupId, userStoreDomain)); - scimCommonUtils = mockStatic(SCIMCommonUtils.class); scimCommonUtils.when(() -> SCIMCommonUtils.getSCIMGroupURL()).thenReturn("https://localhost:9443/scim2/Groups"); - carbonConstants = mockStatic(CarbonConstants.class); CarbonConstants.ENABLE_LEGACY_AUTHZ_RUNTIME = true; SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockedClaimManager); @@ -332,11 +363,12 @@ public Object[][] groupName() throws Exception { @Test(dataProvider = "getGroupException") public void testGetGroupWithExceptions(String roleName, String userStoreDomain) throws Exception { - MemberModifier.field(AbstractUserStoreManager.class, "userStoreManagerHolder") - .set(mockedUserStoreManager, new HashMap()); + AbstractUserStoreManager mockedUserStoreManager = Mockito.mock(AbstractUserStoreManager.class); + Field field = AbstractUserStoreManager.class.getDeclaredField("userStoreManagerHolder"); + field.setAccessible(true); + field.set(mockedUserStoreManager, new HashMap()); when(mockedGroupDAO.getGroupNameById(anyInt(), anyString())).thenReturn(roleName); - identityUtil = mockStatic(IdentityUtil.class); identityUtil.when(() -> IdentityUtil.extractDomainFromName(anyString())).thenReturn(userStoreDomain); SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockedClaimManager); @@ -386,15 +418,16 @@ public void testListGroupsWithFilter(String filter, String roleName, String user }}; when(mockedGroupDAO.getGroupNameList(anyString(), anyString(), anyInt(), anyString())) .thenReturn(list.toArray(new String[0])); - identityUtil = mockStatic(IdentityUtil.class); when(mockedGroupDAO.isExistingGroup("testRole", 0)).thenReturn(true); when(mockedGroupDAO.getSCIMGroupAttributes(0, "testRole")).thenReturn(attributes); identityUtil.when(() -> IdentityUtil.extractDomainFromName(anyString())).thenReturn(userStoreDomain); mockedUserStoreManager = mock(AbstractUserStoreManager.class); - MemberModifier.field(AbstractUserStoreManager.class, "userStoreManagerHolder") - .set(mockedUserStoreManager, new HashMap()); + AbstractUserStoreManager mockedUserStoreManager = Mockito.mock(AbstractUserStoreManager.class); + Field field = AbstractUserStoreManager.class.getDeclaredField("userStoreManagerHolder"); + field.setAccessible(true); + field.set(mockedUserStoreManager, new HashMap()); when(mockedUserStoreManager.isExistingRole(anyString(), anyBoolean())).thenReturn(true); when(mockedUserStoreManager.getRealmConfiguration()).thenReturn(mockRealmConfig); @@ -415,13 +448,11 @@ public void testListGroupsWithFilter(String filter, String roleName, String user when(mockIdentityUtil.extractDomainFromName(anyString())).thenReturn("value"); - carbonConstants = mockStatic(CarbonConstants.class); CarbonConstants.ENABLE_LEGACY_AUTHZ_RUNTIME = true; Map scimToLocalClaimsMap = new HashMap<>(); scimToLocalClaimsMap.put("urn:ietf:params:scim:schemas:core:2.0:User:userName", "http://wso2.org/claims/username"); - scimCommonUtils = mockStatic(SCIMCommonUtils.class); scimCommonUtils.when(() -> SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimsMap); SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockedClaimManager); @@ -442,14 +473,11 @@ public void testListUsersWithGET(List use "http://wso2.org/claims/username"); scimToLocalClaimMap.put("urn:ietf:params:scim:schemas:core:2.0:id", "http://wso2.org/claims/userid"); - scimCommonUtils = mockStatic(SCIMCommonUtils.class); scimCommonUtils.when(() -> SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimMap); scimCommonUtils.when(() -> SCIMCommonUtils.convertLocalToSCIMDialect(anyMap(), anyMap())).thenReturn(new HashMap() {{ put(SCIMConstants.CommonSchemaConstants.ID_URI, "1f70378a-69bb-49cf-aa51-a0493c09110c"); }}); - mockedUserStoreManager = mock(AbstractUserStoreManager.class); - when(mockedUserStoreManager.getUserListWithID("http://wso2.org/claims/userid", "*", null)).thenReturn(users); when(mockedUserStoreManager.getRoleListOfUserWithID(anyString())).thenReturn(new ArrayList<>()); when(mockedUserStoreManager.getRealmConfiguration()).thenReturn(mockedRealmConfig); @@ -460,8 +488,6 @@ public void testListUsersWithGET(List use when(mockedUserStoreManager.getSecondaryUserStoreManager("SECONDARY")).thenReturn(secondaryUserStoreManager); when(secondaryUserStoreManager.isSCIMEnabled()).thenReturn(isScimEnabledForSecondary); - identityTenantUtil = mockStatic(IdentityTenantUtil.class); - identityTenantUtil.when(() -> IdentityTenantUtil.getRealmService()).thenReturn(mockRealmService); when(mockRealmService.getBootstrapRealmConfiguration()).thenReturn(mockedRealmConfig); @@ -529,7 +555,6 @@ public void testFilteringUsersWithGET(List SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimMap); scimCommonUtils.when(() -> SCIMCommonUtils.convertLocalToSCIMDialect(anyMap(), anyMap())).thenReturn(new HashMap() {{ put(SCIMConstants.CommonSchemaConstants.ID_URI, "1f70378a-69bb-49cf-aa51-a0493c09110c"); @@ -550,10 +575,8 @@ public void testFilteringUsersWithGET(List SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimMap); scimCommonUtils.when(() -> SCIMCommonUtils.convertLocalToSCIMDialect(anyMap(), anyMap())).thenReturn(new HashMap() {{ put(SCIMConstants.CommonSchemaConstants.ID_URI, "1f70378a-69bb-49cf-aa51-a0493c09110c"); @@ -671,7 +693,6 @@ public void testFilteringUsersWithGETWithPagination(List IdentityTenantUtil.getRealmService()).thenReturn(mockRealmService); when(mockRealmService.getBootstrapRealmConfiguration()).thenReturn(mockedRealmConfig); @@ -732,6 +753,7 @@ public void testFilteringUsersWithGETWithPagination(List require when(mockedGroupDAO.getSCIMGroupAttributes(anyInt(), anyString())).thenReturn(attributes); userCoreUtil = mockStatic(UserCoreUtil.class); userCoreUtil.when(() -> UserCoreUtil.isEveryoneRole("role", mockedRealmConfig)).thenReturn(false); - scimCommonUtils = mockStatic(SCIMCommonUtils.class); scimCommonUtils.when(() -> SCIMCommonUtils.getSCIMGroupURL()).thenReturn("https://localhost:9443/scim2/Groups"); - SCIMUserManager scimUserManager = new SCIMUserManager(abstractUserStoreManager, mockedClaimManager); - GroupsGetResponse groupsResponse = scimUserManager - .listGroupsWithGET(null, 1, null, null, null, "Application", requiredAttributes); + try (MockedConstruction mocked = mockConstruction(SCIMGroupHandler.class, + (mock, context) -> { + when(mock.listSCIMRoles()).thenReturn(new HashSet<>(Arrays.asList(roles))); + })) { + + CarbonConstants.ENABLE_LEGACY_AUTHZ_RUNTIME = true; + identityUtil.when(() -> IdentityUtil.extractDomainFromName(anyString())).thenReturn("Application"); + SCIMUserManager scimUserManager = new SCIMUserManager(abstractUserStoreManager, mockedClaimManager); + GroupsGetResponse groupsResponse = scimUserManager + .listGroupsWithGET(null, 1, null, null, null, "Application", requiredAttributes); - assertEquals(groupsResponse.getGroups().get(0).getDisplayName(), "Application/Apple"); - assertEquals(groupsResponse.getGroups().get(1).getDisplayName(), "Application/MyApp"); - assertEquals(groupsResponse.getGroups().size(), 2); + assertEquals(groupsResponse.getGroups().get(0).getDisplayName(), "Application/Apple"); + assertEquals(groupsResponse.getGroups().get(1).getDisplayName(), "Application/MyApp"); + assertEquals(groupsResponse.getGroups().size(), 2); + } + userCoreUtil.close(); } @DataProvider(name = "listApplicationRoles") @@ -1009,18 +1039,18 @@ public void testFilterApplicationRolesWithDomainParam(String filter, String[] ro userCoreUtil.when(() -> UserCoreUtil.isEveryoneRole("role", mockedRealmConfig)).thenReturn(false); when(mockedGroupDAO.isExistingGroup(anyString(), anyInt())).thenReturn(true); when(mockedGroupDAO.getSCIMGroupAttributes(anyInt(), anyString())).thenReturn(attributes); - scimCommonUtils = mockStatic(SCIMCommonUtils.class); scimCommonUtils.when(() -> SCIMCommonUtils.getSCIMGroupURL()).thenReturn("https://localhost:9443/scim2/Groups"); - carbonConstants = mockStatic(CarbonConstants.class); CarbonConstants.ENABLE_LEGACY_AUTHZ_RUNTIME = true; - + when(mockedUserStoreManager.getRealmConfiguration()).thenReturn(mockedRealmConfig); + identityUtil.when(() -> IdentityUtil.extractDomainFromName(anyString())).thenReturn("Application"); SCIMUserManager scimUserManager = new SCIMUserManager(abstractUserStoreManager, mockedClaimManager); GroupsGetResponse groupsResponse = scimUserManager .listGroupsWithGET(node, 1, null, null, null, "Application", requiredAttributes); assertEquals(groupsResponse.getGroups().get(0).getDisplayName(), "Application/MyApp"); assertEquals(groupsResponse.getGroups().size(), 1); + userCoreUtil.close(); } @DataProvider(name = "applicationDomainWithFilters") @@ -1076,11 +1106,9 @@ public void testGetEnterpriseUserSchemaWhenEnabled() throws Exception { MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)).thenReturn(externalClaimMap); when(mockClaimMetadataManagementService.getLocalClaims(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) .thenReturn(localClaimMap); - scimCommonUtils = mockStatic(SCIMCommonUtils.class); scimCommonUtils.when(() -> SCIMCommonUtils.isEnterpriseUserExtensionEnabled()).thenReturn(true); SCIMUserSchemaExtensionBuilder sb = spy(new SCIMUserSchemaExtensionBuilder()); - scimUserSchemaExtensionBuilder = mockStatic(SCIMUserSchemaExtensionBuilder.class); scimUserSchemaExtensionBuilder.when(() -> SCIMUserSchemaExtensionBuilder.getInstance()).thenReturn(sb); when(sb.getExtensionSchema()).thenReturn(mockedSCIMAttributeSchema); when(mockedSCIMAttributeSchema.getSubAttributeSchema(anyString())).thenReturn(mockedAttributeSchema); @@ -1094,7 +1122,6 @@ public void testGetEnterpriseUserSchemaWhenEnabled() throws Exception { @Test public void testGetEnterpriseUserSchemaWhenDisabled() throws Exception { - scimCommonUtils = mockStatic(SCIMCommonUtils.class); scimCommonUtils.when(() -> SCIMCommonUtils.isEnterpriseUserExtensionEnabled()).thenReturn(false); SCIMUserManager userManager = new SCIMUserManager(mockedUserStoreManager, mockClaimMetadataManagementService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); @@ -1114,14 +1141,14 @@ public void testUpdateUserWithUsernameChange() throws Exception { newUser.setUserName("newUser"); newUser.setId("newUserId"); - mockStatic(ApplicationManagementService.class); when(ApplicationManagementService.getInstance()).thenReturn(applicationManagementService); when(applicationManagementService.getServiceProvider(anyString(), anyString())).thenReturn(null); SCIMUserManager scimUserManager = spy(new SCIMUserManager(mockedUserStoreManager, mockClaimMetadataManagementService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)); + resourceManagerUtil.when(() -> ResourceManagerUtil.getAllAttributeURIs(Mockito.any())) + .thenReturn(new HashMap<>()); doReturn(oldUser).when(scimUserManager).getUser(anyString(), anyMap()); - mockStatic(IdentityUtil.class); when(IdentityUtil.isUserStoreInUsernameCaseSensitive(anyString())).thenReturn(true); boolean hasExpectedBehaviour = false; @@ -1175,7 +1202,6 @@ public void testGetGroupPermissions(String roleName, String[] permission, Object SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockClaimMetadataManagementService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); - mockStatic(SCIMCommonComponentHolder.class); when(SCIMCommonComponentHolder.getRolePermissionManagementService()) .thenReturn(mockedRolePermissionManagementService); when(mockedRolePermissionManagementService.getRolePermissions(eq(roleName), anyInt())).thenReturn(permission); @@ -1309,7 +1335,6 @@ public void testGetUser(Boolean isGroupsVsRolesSeparationImprovementsEnabled, Ma groupsMap.put("Internal/admin", group3); groupsMap.put("Internal/everyone", group4); - mockStatic(SCIMCommonUtils.class); when(SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimsMap); when(SCIMCommonUtils.convertLocalToSCIMDialect(anyMap(), anyMap())).thenCallRealMethod(); when(SCIMCommonUtils.mandateDomainForUsernamesAndGroupNamesInResponse()). @@ -1317,8 +1342,8 @@ public void testGetUser(Boolean isGroupsVsRolesSeparationImprovementsEnabled, Ma when(SCIMCommonUtils.prependDomain(anyString())).thenCallRealMethod(); when(SCIMCommonUtils.isHybridRole(anyString())).thenCallRealMethod(); - mockStatic(CarbonConstants.class); CarbonConstants.ENABLE_LEGACY_AUTHZ_RUNTIME = true; + CommonTestUtils.initPrivilegedCarbonContext(); org.wso2.carbon.user.core.common.User user = mock(org.wso2.carbon.user.core.common.User.class); when(user.getUserStoreDomain()).thenReturn(userStoreDomainName); @@ -1352,7 +1377,6 @@ public void testGetUser(Boolean isGroupsVsRolesSeparationImprovementsEnabled, Ma SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockClaimMetadataManagementService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); - mockStatic(IdentityUtil.class); when(IdentityUtil.isGroupsVsRolesSeparationImprovementsEnabled()) .thenReturn(isGroupsVsRolesSeparationImprovementsEnabled); when(IdentityUtil.getProperty(SCIMCommonConstants.PRIMARY_LOGIN_IDENTIFIER_CLAIM)) @@ -1370,16 +1394,20 @@ public Group answer(InvocationOnMock invocation) throws Throwable { } }); - mockStatic(IdentityTenantUtil.class); - when(IdentityTenantUtil.getTenantId("carbon.super")).thenReturn(-1234); - User scimUser = scimUserManager.getUser(userId, requiredAttributes); - assertEquals(scimUser.getAttributeList().size(), expectedNoOfAttributes); - // Check whether the added multi valued attributes for the addresses attribute are contained. - assertEquals( - ((MultiValuedAttribute) scimUser.getAttribute("addresses")).getAttributeValues().size(), 2); - assertEquals(scimUser.getUserName(), expectedUserName); - assertEquals(scimUser.getGroups().size(), expectedNoOfGroups); - assertEquals(scimUser.getRoles().size(), expectedNoOfRoles); + try (MockedConstruction mocked = mockConstruction(SCIMGroupHandler.class, + (mock, context) -> { + when(mock.getGroupWithAttributes(any(),any())).thenReturn(group1); + })) { + when(IdentityTenantUtil.getTenantId("carbon.super")).thenReturn(-1234); + User scimUser = scimUserManager.getUser(userId, requiredAttributes); + assertEquals(scimUser.getAttributeList().size(), expectedNoOfAttributes); + // Check whether the added multi valued attributes for the addresses attribute are contained. + assertEquals( + ((MultiValuedAttribute) scimUser.getAttribute("addresses")).getAttributeValues().size(), 2); + assertEquals(scimUser.getUserName(), expectedUserName); + assertEquals(scimUser.getGroups().size(), expectedNoOfGroups); + assertEquals(scimUser.getRoles().size(), expectedNoOfRoles); + } } @DataProvider(name = "exceptionHandlingConfigurations") @@ -1399,7 +1427,6 @@ public void testGetUserWithInvalidUserID(Boolean isNotifyUserstoreStatusEnabled) Map scimToLocalClaimsMap = new HashMap<>(); scimToLocalClaimsMap.put(SCIMConstants.CommonSchemaConstants.ID_URI, USERID_LOCAL_CLAIM); - mockStatic(SCIMCommonUtils.class); when(SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimsMap); when(SCIMCommonUtils.isNotifyUserstoreStatusEnabled()).thenReturn(isNotifyUserstoreStatusEnabled); SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, @@ -1409,7 +1436,6 @@ public void testGetUserWithInvalidUserID(Boolean isNotifyUserstoreStatusEnabled) List scimUserStoreErrorResolvers = new ArrayList<>(); SCIMUserStoreErrorResolver scimUserStoreErrorResolver = new DefaultSCIMUserStoreErrorResolver(); scimUserStoreErrorResolvers.add(scimUserStoreErrorResolver); - mockStatic(SCIMCommonComponentHolder.class); when(SCIMCommonComponentHolder.getScimUserStoreErrorResolverList()).thenReturn(scimUserStoreErrorResolvers); scimUserManager.getUser(userId, requiredAttributes); // This method is for testing of throwing CharonException, hence no assertion. @@ -1424,9 +1450,8 @@ public void testGetUserWhenSCIMisDisabled() throws Exception { Map scimToLocalClaimsMap = new HashMap<>(); scimToLocalClaimsMap.put(SCIMConstants.CommonSchemaConstants.ID_URI, USERID_LOCAL_CLAIM); - mockStatic(SCIMCommonUtils.class); when(SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimsMap); - mockedUserStoreManager = PowerMockito.mock(AbstractUserStoreManager.class); + mockedUserStoreManager = Mockito.mock(AbstractUserStoreManager.class); SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockClaimMetadataManagementService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); org.wso2.carbon.user.core.common.User user = mock(org.wso2.carbon.user.core.common.User.class); @@ -1460,13 +1485,11 @@ public void testDeleteUserWithInvalidUserId() throws Exception { scimToLocalClaimsMap.put(SCIMConstants.CommonSchemaConstants.ID_URI, "userIdURI"); List coreUsers = new ArrayList<>(); - mockStatic(SCIMCommonUtils.class); when(SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimsMap); - AbstractUserStoreManager mockedUserStoreManager = PowerMockito.mock(AbstractUserStoreManager.class); + AbstractUserStoreManager mockedUserStoreManager = Mockito.mock(AbstractUserStoreManager.class); when(mockedUserStoreManager.getUserListWithID(anyString(), anyString(), anyString())).thenReturn(coreUsers); SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockClaimMetadataManagementService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); - mockStatic(ApplicationManagementService.class); when(ApplicationManagementService.getInstance()).thenReturn(applicationManagementService); when(applicationManagementService.getServiceProvider(anyString(), anyString())).thenReturn(null); scimUserManager.deleteUser(userId); @@ -1484,15 +1507,13 @@ public void testDeleteUserWhenSCIMisDisabled() throws Exception { coreUser.setUsername("coreUser"); coreUser.setUserStoreDomain("DomainName"); - mockStatic(SCIMCommonUtils.class); when(SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimsMap); - AbstractUserStoreManager mockedUserStoreManager = PowerMockito.mock(AbstractUserStoreManager.class); + AbstractUserStoreManager mockedUserStoreManager = Mockito.mock(AbstractUserStoreManager.class); when(mockedUserStoreManager.getUserWithID(anyString(), any(), anyString())).thenReturn(coreUser); when(mockedUserStoreManager.getSecondaryUserStoreManager("DomainName")).thenReturn(mockedUserStoreManager); when(mockedUserStoreManager.isSCIMEnabled()).thenReturn(false); SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockClaimMetadataManagementService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); - mockStatic(ApplicationManagementService.class); when(ApplicationManagementService.getInstance()).thenReturn(applicationManagementService); when(applicationManagementService.getServiceProvider(anyString(), anyString())).thenReturn(null); scimUserManager.deleteUser(userId); @@ -1509,9 +1530,8 @@ public void testDeleteUserWithUserStoreDomainMismatch() throws Exception { coreUser.setUsername("coreUser"); coreUser.setUserStoreDomain("PRIMARY"); - mockStatic(SCIMCommonUtils.class); when(SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimsMap); - AbstractUserStoreManager mockedUserStoreManager = PowerMockito.mock(AbstractUserStoreManager.class); + AbstractUserStoreManager mockedUserStoreManager = Mockito.mock(AbstractUserStoreManager.class); when(mockedUserStoreManager.getUserWithID(anyString(), any(), anyString())).thenReturn(coreUser); SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockClaimMetadataManagementService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); @@ -1519,7 +1539,6 @@ public void testDeleteUserWithUserStoreDomainMismatch() throws Exception { inboundProvisioningConfig.setProvisioningUserStore("SECONDARY"); ServiceProvider serviceProvider = new ServiceProvider(); serviceProvider.setInboundProvisioningConfig(inboundProvisioningConfig); - mockStatic(ApplicationManagementService.class); when(ApplicationManagementService.getInstance()).thenReturn(applicationManagementService); when(applicationManagementService.getServiceProvider(anyString(), anyString())).thenReturn(serviceProvider); scimUserManager.deleteUser(userId); @@ -1532,16 +1551,16 @@ public void testCreateUserWithInvalidUserStoreName() throws Exception { User user = new User(); user.setUserName("testUser"); - mockedUserStoreManager = PowerMockito.mock(AbstractUserStoreManager.class); when(mockedUserStoreManager.getSecondaryUserStoreManager(anyString())) .thenReturn(null); InboundProvisioningConfig inboundProvisioningConfig = new InboundProvisioningConfig(); inboundProvisioningConfig.setProvisioningUserStore("DomainName"); ServiceProvider serviceProvider = new ServiceProvider(); serviceProvider.setInboundProvisioningConfig(inboundProvisioningConfig); - mockStatic(ApplicationManagementService.class); when(ApplicationManagementService.getInstance()).thenReturn(applicationManagementService); when(applicationManagementService.getServiceProvider(anyString(), anyString())).thenReturn(serviceProvider); + when(mockedUserStoreManager.isExistingUser(nullable(String.class))) + .thenThrow(new UserStoreException(new UserStoreClientException("TestException"))); SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockClaimMetadataManagementService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); scimUserManager.createUser(user, null); @@ -1554,7 +1573,6 @@ public void testCreateUserWhenSCIMisDisabled() throws Exception { User user = new User(); user.setUserName("testUser"); - mockedUserStoreManager = PowerMockito.mock(AbstractUserStoreManager.class); when(mockedUserStoreManager.getSecondaryUserStoreManager(anyString())) .thenReturn(secondaryUserStoreManager); when(secondaryUserStoreManager.isSCIMEnabled()).thenReturn(false); @@ -1563,11 +1581,12 @@ public void testCreateUserWhenSCIMisDisabled() throws Exception { inboundProvisioningConfig.setProvisioningUserStore("DomainName"); ServiceProvider serviceProvider = new ServiceProvider(); serviceProvider.setInboundProvisioningConfig(inboundProvisioningConfig); - mockStatic(ApplicationManagementService.class); when(ApplicationManagementService.getInstance()).thenReturn(applicationManagementService); when(applicationManagementService.getServiceProvider(anyString(), anyString())).thenReturn(serviceProvider); SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockClaimMetadataManagementService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); + doThrow(new NotImplementedException()).when(mockedUser).setSchemas(Mockito.any(UserManager.class)); + mockedUser.setSchemas(Mockito.mock(UserManager.class)); scimUserManager.createUser(user, null); // This method is for testing of throwing CharonException, hence no assertion. } @@ -1589,18 +1608,16 @@ public void testCreateUserWithExistingUserName(String isLoginIdentifiersEnabled) user.setUserName("DomainName/testUser1"); String[] existingUserList = {"user1", "user2"}; - mockStatic(IdentityUtil.class); when(IdentityUtil.getProperty(SCIMCommonConstants.PRIMARY_LOGIN_IDENTIFIER_CLAIM)) .thenReturn("primaryLoginIdentifierClaim"); when(IdentityUtil.getProperty(SCIMCommonConstants.ENABLE_LOGIN_IDENTIFIERS)) .thenReturn(isLoginIdentifiersEnabled); when(IdentityUtil.extractDomainFromName(anyString())).thenCallRealMethod(); - mockStatic(ApplicationManagementService.class); when(ApplicationManagementService.getInstance()).thenReturn(applicationManagementService); when(applicationManagementService.getServiceProvider(anyString(), anyString())).thenReturn(null); - mockedUserStoreManager = PowerMockito.mock(AbstractUserStoreManager.class); + mockedUserStoreManager = Mockito.mock(AbstractUserStoreManager.class); when(mockedUserStoreManager.isExistingUserWithID(anyString())).thenReturn(true); when(mockedUserStoreManager.isExistingUser(anyString())).thenReturn(true); when(mockedUserStoreManager.getUserList(anyString(), anyString(), nullable(String.class))).thenReturn(existingUserList); @@ -1623,21 +1640,18 @@ public void testCreateUserWithConflictingLoginIdentifier() throws Exception { Map scimToLocalClaimMappings = new HashMap<>(); scimToLocalClaimMappings.put(SCIMConstants.UserSchemaConstants.DISPLAY_NAME_URI, DISPLAY_NAME_LOCAL_CLAIM); - mockStatic(IdentityUtil.class); when(IdentityUtil.getProperty(SCIMCommonConstants.PRIMARY_LOGIN_IDENTIFIER_CLAIM)) .thenReturn(DISPLAY_NAME_LOCAL_CLAIM); when(IdentityUtil.getProperty(SCIMCommonConstants.ENABLE_LOGIN_IDENTIFIERS)).thenReturn("true"); when(IdentityUtil.extractDomainFromName(anyString())).thenCallRealMethod(); - mockStatic(ApplicationManagementService.class); when(ApplicationManagementService.getInstance()).thenReturn(applicationManagementService); when(applicationManagementService.getServiceProvider(anyString(), anyString())).thenReturn(null); - mockStatic(SCIMCommonUtils.class); when(SCIMCommonUtils.convertSCIMtoLocalDialect(anyMap())).thenCallRealMethod(); when(SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimMappings); - mockedUserStoreManager = PowerMockito.mock(AbstractUserStoreManager.class); + mockedUserStoreManager = Mockito.mock(AbstractUserStoreManager.class); when(mockedUserStoreManager.getUserList(anyString(), anyString(), anyString())).thenReturn(null); when(mockedUserStoreManager.getSecondaryUserStoreManager(anyString())) .thenReturn(secondaryUserStoreManager); From 3838e4bd904a781a2e0f1a75c81d7a5be01b3b6a Mon Sep 17 00:00:00 2001 From: kumuditha Date: Tue, 24 Sep 2024 08:29:18 +0530 Subject: [PATCH 12/13] Address review comments --- .../common/group/SCIMGroupHandlerTest.java | 9 +- ...DefaultSCIMUserStoreErrorResolverTest.java | 2 +- .../impl/IdentityResourceURLBuilderTest.java | 2 +- .../common/impl/IdentitySCIMManagerTest.java | 31 +- .../common/impl/SCIMRoleManagerTest.java | 306 ++++++++++-------- .../common/impl/SCIMRoleManagerV2Test.java | 1 - .../common/impl/SCIMUserManagerTest.java | 1 - .../SCIMUserOperationListenerTest.java | 2 +- .../common/test/utils/CommonTestUtils.java | 2 +- .../common/utils/AdminAttributeUtilTest.java | 7 +- .../utils/AdminAttributeUtilTestForGroup.java | 7 +- .../common/utils/AttributeMapperTest.java | 2 +- .../utils/AuthenticationSchemaTest.java | 2 +- .../common/utils/SCIMCommonUtilsTest.java | 2 +- .../common/utils/SCIMConfigProcessorTest.java | 2 +- 15 files changed, 207 insertions(+), 171 deletions(-) diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/group/SCIMGroupHandlerTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/group/SCIMGroupHandlerTest.java index be61bc7a6..089989df0 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/group/SCIMGroupHandlerTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/group/SCIMGroupHandlerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2017, WSO2 LLC. (http://www.wso2.org) * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except @@ -27,7 +27,6 @@ import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import org.wso2.carbon.base.CarbonBaseConstants; import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.scim2.common.DAO.GroupDAO; @@ -79,7 +78,8 @@ public class SCIMGroupHandlerTest { private MockedStatic stringUtils; @BeforeMethod - public void setUp() throws Exception { + public void setUp() { + initMocks(this); scimCommonUtils = mockStatic(SCIMCommonUtils.class); identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); @@ -93,7 +93,6 @@ public void tearDown() throws Exception { identityDatabaseUtil.close(); identityTenantUtil.close(); stringUtils.close(); - System.clearProperty(CarbonBaseConstants.CARBON_HOME); } @Test @@ -315,7 +314,6 @@ public void testUpdateRoleName() throws Exception { @Test(expectedExceptions = IdentitySCIMException.class) public void testUpdateRoleNameNonExistent() throws Exception { - ResultSet resultSet = mock(ResultSet.class); when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection); @@ -327,6 +325,7 @@ public void testUpdateRoleNameNonExistent() throws Exception { SCIMGroupHandler scimGroupHandler = new SCIMGroupHandler(1); scimGroupHandler.updateRoleName("NON_EXISTENT_ROLE_NAME", "NEW_ROLE_NAME"); + // This method is to test the throwing of an IdentitySCIMException, hence no assertion. } } diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/DefaultSCIMUserStoreErrorResolverTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/DefaultSCIMUserStoreErrorResolverTest.java index fa52abbc4..76513ea49 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/DefaultSCIMUserStoreErrorResolverTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/DefaultSCIMUserStoreErrorResolverTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2021, WSO2 LLC. (http://www.wso2.org) * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentityResourceURLBuilderTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentityResourceURLBuilderTest.java index 4d2d23921..752e0f73f 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentityResourceURLBuilderTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentityResourceURLBuilderTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2021, WSO2 LLC. (http://www.wso2.org) * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentitySCIMManagerTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentitySCIMManagerTest.java index ff6d4118e..039b9238a 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentitySCIMManagerTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/IdentitySCIMManagerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2017, WSO2 LLC. (http://www.wso2.org) * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except @@ -20,22 +20,17 @@ import org.mockito.Mock; import org.mockito.MockedStatic; -import org.mockito.quality.Strictness; -import org.mockito.testng.MockitoSettings; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.testng.annotations.Listeners; import org.mockito.testng.MockitoTestNGListener; -import org.wso2.carbon.base.CarbonBaseConstants; import org.wso2.carbon.identity.scim2.common.internal.SCIMCommonComponentHolder; import org.wso2.carbon.identity.scim2.common.test.utils.CommonTestUtils; import org.wso2.carbon.identity.scim2.common.utils.SCIMCommonUtils; import org.wso2.carbon.identity.scim2.common.utils.SCIMConfigProcessor; import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.user.core.claim.ClaimManager; -import org.wso2.carbon.user.core.common.AbstractUserStoreManager; import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.tenant.TenantManager; import org.wso2.charon3.core.exceptions.CharonException; @@ -54,7 +49,6 @@ * Contains the unit test cases for IdentitySCIMManager. */ @Listeners(MockitoTestNGListener.class) -@MockitoSettings(strictness = Strictness.LENIENT) public class IdentitySCIMManagerTest { @Mock @@ -66,12 +60,6 @@ public class IdentitySCIMManagerTest { @Mock UserRealm mockedUserRealm; - @Mock - ClaimManager mockedClaimManager; - - @Mock - AbstractUserStoreManager mockedUserStoreManager; - private SCIMConfigProcessor scimConfigProcessor; private IdentitySCIMManager identitySCIMManager; @@ -84,20 +72,12 @@ public void setUp() throws Exception { scimCommonUtils.when(() -> SCIMCommonUtils.getSCIMUserURL()).thenReturn("http://scimUserUrl:9443"); scimCommonComponentHolder = mockStatic(SCIMCommonComponentHolder.class); - scimCommonComponentHolder.when(() -> SCIMCommonComponentHolder.getRealmService()).thenReturn(realmService); - scimConfigProcessor = SCIMConfigProcessor.getInstance(); String filePath = Paths .get(System.getProperty("user.dir"), "src", "test", "resources", "charon-config-test.xml").toString(); scimConfigProcessor.buildConfigFromFile(filePath); identitySCIMManager = IdentitySCIMManager.getInstance(); - when(realmService.getTenantManager()).thenReturn(mockedTenantManager); - when(mockedTenantManager.getTenantId(anyString())).thenReturn(-1234); - when(realmService.getTenantUserRealm(anyInt())).thenReturn(mockedUserRealm); - - when(mockedUserRealm.getClaimManager()).thenReturn(mockedClaimManager); - when(mockedUserRealm.getUserStoreManager()).thenReturn(mockedUserStoreManager); CommonTestUtils.initPrivilegedCarbonContext(); } @@ -105,7 +85,6 @@ public void setUp() throws Exception { public void tearDown() { scimCommonComponentHolder.close(); scimCommonUtils.close(); - System.clearProperty(CarbonBaseConstants.CARBON_HOME); } @Test @@ -125,6 +104,8 @@ public void testGetEncoder() throws Exception { public void testGetUserManager() throws Exception { when(SCIMCommonComponentHolder.getRealmService()).thenReturn(realmService); + when(realmService.getTenantManager()).thenReturn(mockedTenantManager); + when(realmService.getTenantUserRealm(anyInt())).thenReturn(mockedUserRealm); UserManager userManager = identitySCIMManager.getUserManager(); assertNotNull(userManager); } @@ -144,9 +125,11 @@ public void testGetUserManagerWithException() throws Exception { @Test public void testGetUserManagerWithException2() throws Exception { + when(SCIMCommonComponentHolder.getRealmService()).thenReturn(realmService); + when(realmService.getTenantManager()).thenReturn(mockedTenantManager); + when(mockedTenantManager.getTenantId(anyString())).thenThrow(new UserStoreException()); + try { - when(SCIMCommonComponentHolder.getRealmService()).thenReturn(realmService); - when(mockedTenantManager.getTenantId(anyString())).thenThrow(new UserStoreException()); identitySCIMManager.getUserManager(); fail("getUserManager() method should have thrown a CharonException"); } catch (CharonException e) { diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManagerTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManagerTest.java index 5c0954b7e..65796a7f4 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManagerTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManagerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2021, WSO2 LLC. (http://www.wso2.org) * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except @@ -21,11 +21,11 @@ import org.apache.commons.lang.StringUtils; import org.mockito.Mock; import org.mockito.MockedStatic; -import org.mockito.MockitoAnnotations; +import org.mockito.testng.MockitoTestNGListener; import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; +import org.testng.annotations.Listeners; import org.testng.annotations.Test; import org.wso2.carbon.identity.organization.management.service.exception.OrganizationManagementException; import org.wso2.carbon.identity.organization.management.service.util.OrganizationManagementUtil; @@ -74,7 +74,6 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import static org.mockito.MockitoAnnotations.initMocks; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertThrows; import static org.testng.Assert.assertTrue; @@ -88,6 +87,7 @@ /** * Contains the unit test cases for SCIMRoleManager. */ +@Listeners(MockitoTestNGListener.class) public class SCIMRoleManagerTest { private static final String SAMPLE_TENANT_DOMAIN = "carbon.super"; @@ -124,15 +124,9 @@ public class SCIMRoleManagerTest { private MockedStatic scimCommonUtils; private MockedStatic organizationManagementUtil; - @BeforeClass - public void setUpClass() { - - initMocks(this); - } - @BeforeMethod public void setUpMethod() { - MockitoAnnotations.openMocks(this); + scimCommonUtils = mockStatic(SCIMCommonUtils.class); organizationManagementUtil = mockStatic(OrganizationManagementUtil.class); when(SCIMCommonUtils.getSCIMRoleURL(nullable(String.class))).thenReturn(DUMMY_SCIM_URL); @@ -447,26 +441,31 @@ public void testListRolesWithGETInvalidLimit(String nodeType, Integer count) throws IdentityRoleManagementException { Node rootNode = generateNodeBasedOnNodeType(nodeType, null); - when(mockRoleManagementService.getRoles(anyInt(), anyInt(), nullable(String.class), nullable(String.class), anyString())). - thenAnswer(invocationOnMock -> { - Integer countArg = invocationOnMock.getArgument(0); - if (countArg != null && countArg < 0) { - String errorMessage = String.format("Invalid limit requested. Limit value should be " + - "greater than or equal to zero. limit: %s", count); - throw new IdentityRoleManagementClientException(INVALID_LIMIT.getCode(), errorMessage); - } - return null; - }); - when(mockRoleManagementService.getRoles(nullable(String.class), anyInt(), anyInt(), nullable(String.class), nullable(String.class), anyString())) - .thenAnswer(invocationOnMock -> { - Integer countArg = invocationOnMock.getArgument(1); - if (countArg != null && countArg < 0) { - String errorMessage = String.format("Invalid limit requested. Limit value should be " + - "greater than or equal to zero. limit: %s", count); - throw new IdentityRoleManagementClientException(INVALID_LIMIT.getCode(), errorMessage); - } - return null; - }); + + if ("Expression".equals(nodeType)) { + when(mockRoleManagementService.getRoles(nullable(String.class), anyInt(), anyInt(), nullable(String.class), + nullable(String.class), anyString())).thenAnswer(invocationOnMock -> { + Integer countArg = invocationOnMock.getArgument(1); + if (countArg != null && countArg < 0) { + String errorMessage = String.format("Invalid limit requested. Limit value should be " + + "greater than or equal to zero. limit: %s", count); + throw new IdentityRoleManagementClientException(INVALID_LIMIT.getCode(), errorMessage); + } + return null; + }); + } else { + when(mockRoleManagementService.getRoles(anyInt(), anyInt(), nullable(String.class), nullable(String.class), anyString())). + thenAnswer(invocationOnMock -> { + Integer countArg = invocationOnMock.getArgument(0); + if (countArg != null && countArg < 0) { + String errorMessage = String.format("Invalid limit requested. Limit value should be " + + "greater than or equal to zero. limit: %s", count); + throw new IdentityRoleManagementClientException(INVALID_LIMIT.getCode(), errorMessage); + } + return null; + }); + } + SCIMRoleManager roleManager = new SCIMRoleManager(mockRoleManagementService, SAMPLE_TENANT_DOMAIN); assertThrows(CharonException.class, () -> roleManager. listRolesWithGET(rootNode, 2, count, null, null)); @@ -486,28 +485,32 @@ public void testListRolesWithGETInvalidOffset(String nodeType, Integer startInde throws IdentityRoleManagementException { Node rootNode = generateNodeBasedOnNodeType(nodeType, null); - when(mockRoleManagementService.getRoles(anyInt(), anyInt(), nullable(String.class), nullable(String.class), anyString())). - thenAnswer(invocationOnMock -> { - Integer startIndexArg = invocationOnMock.getArgument(1); - if (startIndexArg != null && startIndexArg < 0) { - String errorMessage = - "Invalid offset requested. Offset value should be greater " + - "than or equal to zero. offset: " + startIndexArg; - throw new IdentityRoleManagementClientException(INVALID_LIMIT.getCode(), errorMessage); - } - return null; - }); - when(mockRoleManagementService.getRoles(nullable(String.class), anyInt(), anyInt(), nullable(String.class), nullable(String.class), anyString())) - .thenAnswer(invocationOnMock -> { - Integer startIndexArg = invocationOnMock.getArgument(2); - if (startIndexArg != null && startIndexArg < 0) { - String errorMessage = - "Invalid offset requested. offset value should be greater than or " + - "equal to zero. offset: " + startIndexArg; - throw new IdentityRoleManagementClientException(INVALID_LIMIT.getCode(), errorMessage); - } - return null; - }); + + if ("Expression".equals(nodeType)) { + when(mockRoleManagementService.getRoles(nullable(String.class), anyInt(), anyInt(), nullable(String.class), nullable(String.class), anyString())) + .thenAnswer(invocationOnMock -> { + Integer startIndexArg = invocationOnMock.getArgument(2); + if (startIndexArg != null && startIndexArg < 0) { + String errorMessage = + "Invalid offset requested. offset value should be greater than or " + + "equal to zero. offset: " + startIndexArg; + throw new IdentityRoleManagementClientException(INVALID_LIMIT.getCode(), errorMessage); + } + return null; + }); + } else { + when(mockRoleManagementService.getRoles(anyInt(), anyInt(), nullable(String.class), nullable(String.class), anyString())). + thenAnswer(invocationOnMock -> { + Integer startIndexArg = invocationOnMock.getArgument(1); + if (startIndexArg != null && startIndexArg < 0) { + String errorMessage = + "Invalid offset requested. Offset value should be greater " + + "than or equal to zero. offset: " + startIndexArg; + throw new IdentityRoleManagementClientException(INVALID_LIMIT.getCode(), errorMessage); + } + return null; + }); + } SCIMRoleManager roleManager = new SCIMRoleManager(mockRoleManagementService, SAMPLE_TENANT_DOMAIN); assertThrows(CharonException.class, () -> roleManager. @@ -529,13 +532,18 @@ public void testListRolesWithGETUnExpectedServerError(String nodeType, String te throws IdentityRoleManagementException { Node rootNode = generateNodeBasedOnNodeType(nodeType, "name"); - when(mockRoleManagementService.getRoles(anyInt(), anyInt(), nullable(String.class), nullable(String.class), anyString())). - thenThrow(unExpectedErrorThrower(tenantDomain, sError, - "Error while listing roles in tenantDomain: ")); - when(mockRoleManagementService.getRoles(anyString(), anyInt(), anyInt(), nullable(String.class), - nullable(String.class), anyString())). - thenThrow(unExpectedErrorThrower(tenantDomain, sError, - "Error while listing roles in tenantDomain: ")); + + if ("Expression".equals(nodeType)) { + when(mockRoleManagementService.getRoles(anyString(), anyInt(), anyInt(), nullable(String.class), + nullable(String.class), anyString())). + thenThrow(unExpectedErrorThrower(tenantDomain, sError, + "Error while listing roles in tenantDomain: ")); + } else { + when(mockRoleManagementService.getRoles(anyInt(), anyInt(), nullable(String.class), nullable(String.class), anyString())). + thenThrow(unExpectedErrorThrower(tenantDomain, sError, + "Error while listing roles in tenantDomain: ")); + } + SCIMRoleManager roleManager = new SCIMRoleManager(mockRoleManagementService, tenantDomain); assertThrows(CharonException.class, () -> roleManager. listRolesWithGET(rootNode, 2, 2, null, null)); @@ -588,12 +596,15 @@ public void testListRolesWithGETPositive(String nodeType, Object count, String o Node rootNode = generateNodeBasedOnNodeType(nodeType, "name", operation); List roleList = getDummyRoleBasicInfoList(); - when(mockRoleManagementService.getRoles(anyInt(), anyInt(), nullable(String.class), nullable(String.class), anyString())). - thenAnswer(invocationOnMock -> roleList); - when(mockRoleManagementService.getRoles(anyString(), nullable(Integer.class), anyInt(), nullable(String.class), - nullable(String.class), anyString())). - thenAnswer(invocationOnMock -> roleList); - when(mockRoleManagementService.getRolesCount(anyString())).thenAnswer(invocationOnMock -> 5); + if ("Expression".equals(nodeType)) { + when(mockRoleManagementService.getRoles(anyString(), nullable(Integer.class), anyInt(), nullable(String.class), + nullable(String.class), anyString())). + thenAnswer(invocationOnMock -> roleList); + } else { + when(mockRoleManagementService.getRoles(anyInt(), anyInt(), nullable(String.class), nullable(String.class), anyString())). + thenAnswer(invocationOnMock -> roleList); + when(mockRoleManagementService.getRolesCount(anyString())).thenAnswer(invocationOnMock -> 5); + } SCIMRoleManager roleManager = new SCIMRoleManager(mockRoleManagementService, SAMPLE_TENANT_DOMAIN); RolesGetResponse rolesResponse = roleManager.listRolesWithGET(rootNode, 2, (Integer) count, null, null); @@ -641,13 +652,41 @@ public void testUpdateRoleUpdateRoleName(String roleId, String oldRoleName, Stri RoleBasicInfo roleBasicInfo = new RoleBasicInfo(roleId, newRoleName); Role[] oldAndNewRoles = getOldAndNewRoleDummies(roleId, oldRoleName, newRoleName, type); - when(mockRoleManagementService.updateRoleName(anyString(), anyString(), anyString())).thenReturn(roleBasicInfo); - when(mockRoleManagementService.updateUserListOfRole( - eq(roleId), anyList(), anyList(), anyString())).thenReturn(roleBasicInfo); - when(mockRoleManagementService.updateGroupListOfRole(eq(roleId), anyList(), - anyList(), anyString())).thenReturn(roleBasicInfo); - when(mockRoleManagementService.setPermissionsForRole(eq(roleId), anyList(), anyString())). - thenReturn(roleBasicInfo); + + boolean isValidRoleId1 = roleId.equals(SAMPLE_VALID_ROLE_ID); + boolean isValidRoleId2 = roleId.equals(SAMPLE_VALID_ROLE_ID2); + boolean isOldRoleNameValid = oldRoleName.equals(SAMPLE_VALID_ROLE_NAME); + boolean isTenantDomain2 = tenantDomain.equals(SAMPLE_TENANT_DOMAIN2); + boolean isTenantDomain = tenantDomain.equals(SAMPLE_TENANT_DOMAIN); + boolean isNewRoleName2 = newRoleName.equals(SAMPLE_VALID_ROLE_NAME2); + boolean isNewRoleNameValid = newRoleName.equals(SAMPLE_VALID_ROLE_NAME); + + boolean isTypeEmptyDeleted = type.equals("EMPTY_DELETED"); + boolean isTypeEmptyNew = type.equals("EMPTY_NEW"); + boolean isTypeEmptyBoth = type.equals("EMPTY_BOTH"); + boolean isTypeEmptyOldPermission = type.equals("EMPTY_OLD_PERMISSION"); + boolean isTypeEmptyNewPermission = type.equals("NULL_NEW_PERMISSION"); + boolean isTypeAllEmptyPermission = type.equals("ALL_EMPTY_PERMISSION"); + boolean isTypeAllEqualPermission = type.equals("ALL_EQUAL_PERMISSION"); + + if ((isValidRoleId1 && (isNewRoleName2 && isTenantDomain2 || isNewRoleNameValid && isTenantDomain2)) || + (isValidRoleId2 && isOldRoleNameValid && isNewRoleName2 && (isTenantDomain && (isTypeEmptyDeleted || isTypeEmptyNew)))) { + when(mockRoleManagementService.updateUserListOfRole(eq(roleId), anyList(), anyList(), anyString())) + .thenReturn(roleBasicInfo); + when(mockRoleManagementService.updateGroupListOfRole(eq(roleId), anyList(), anyList(), anyString())) + .thenReturn(roleBasicInfo); + + if (isTypeEmptyDeleted || isTypeEmptyNew || isTypeEmptyBoth) { + when(mockRoleManagementService.updateRoleName(anyString(), anyString(), anyString())) + .thenReturn(roleBasicInfo); + } + + if (isTypeEmptyNewPermission || isTypeEmptyOldPermission || + isTypeAllEmptyPermission || isTypeAllEqualPermission) { + when(mockRoleManagementService.setPermissionsForRole(eq(roleId), anyList(), anyString())) + .thenReturn(roleBasicInfo); + } + } SCIMRoleManager scimRoleManager = new SCIMRoleManager(mockRoleManagementService, tenantDomain); scimRoleManager.updateRole(oldAndNewRoles[0], oldAndNewRoles[1]); @@ -901,29 +940,34 @@ public void testListRolesWithPOSTInvalidLimit(String nodeType, Integer count) throws IdentityRoleManagementException { Node rootNode = generateNodeBasedOnNodeType(nodeType, "name"); - when(mockRoleManagementService.getRoles(anyInt(), anyInt(), nullable(String.class), nullable(String.class), anyString())). - thenAnswer(invocationOnMock -> { - Integer countArg = invocationOnMock.getArgument(0); - if (countArg != null && countArg < 0) { - String errorMessage = - "Invalid limit requested. Limit value should be greater than or equal to zero. limit: " - + count; - throw new IdentityRoleManagementClientException(INVALID_LIMIT.getCode(), errorMessage); - } - return null; - }); - when(mockRoleManagementService.getRoles(anyString(), anyInt(), anyInt(), nullable(String.class), nullable(String.class), anyString())) - .thenAnswer(invocationOnMock -> { - Integer countArg = invocationOnMock.getArgument(1); - if (countArg != null && countArg < 0) { - String errorMessage = - "Invalid limit requested. Limit value should be greater than or equal to zero. limit: " - + count; - throw new IdentityRoleManagementClientException(INVALID_LIMIT.getCode(), errorMessage); - } - return null; - }); + if ("Expression".equals(nodeType)) { + when(mockRoleManagementService.getRoles(anyString(), anyInt(), anyInt(), nullable(String.class), nullable(String.class), anyString())) + .thenAnswer(invocationOnMock -> { + Integer countArg = invocationOnMock.getArgument(1); + + if (countArg != null && countArg < 0) { + String errorMessage = + "Invalid limit requested. Limit value should be greater than or equal to zero. limit: " + + count; + throw new IdentityRoleManagementClientException(INVALID_LIMIT.getCode(), errorMessage); + } + return null; + }); + } else { + when(mockRoleManagementService.getRoles(anyInt(), anyInt(), nullable(String.class), nullable(String.class), anyString())). + thenAnswer(invocationOnMock -> { + Integer countArg = invocationOnMock.getArgument(0); + if (countArg != null && countArg < 0) { + String errorMessage = + "Invalid limit requested. Limit value should be greater than or equal to zero. limit: " + + count; + throw new IdentityRoleManagementClientException(INVALID_LIMIT.getCode(), errorMessage); + } + return null; + }); + } + SCIMRoleManager roleManager = new SCIMRoleManager(mockRoleManagementService, SAMPLE_TENANT_DOMAIN); assertThrows(CharonException.class, () -> roleManager. listRolesWithPost(getDummySearchRequest(rootNode, 2, count, null, null))); @@ -943,30 +987,35 @@ public void testListRolesWithPOSTInvalidOffset(String nodeType, Integer startInd throws IdentityRoleManagementException { Node rootNode = generateNodeBasedOnNodeType(nodeType, "name"); - when(mockRoleManagementService.getRoles(anyInt(), anyInt(), nullable(String.class), nullable(String.class), anyString())). - thenAnswer(invocationOnMock -> { - Integer startIndexArg = invocationOnMock.getArgument(1); - if (startIndexArg != null && startIndexArg < 0) { - String errorMessage = - "Invalid limit requested. Limit value should be greater than or equal to zero. limit: " - + startIndexArg; - throw new IdentityRoleManagementClientException(INVALID_LIMIT.getCode(), errorMessage); - } - return null; - }); - when(mockRoleManagementService.getRoles(anyString(), anyInt(), anyInt(), nullable(String.class), nullable(String.class), anyString())) - .thenAnswer(invocationOnMock -> { - Integer startIndexArg = invocationOnMock.getArgument(2); + if ("Expression".equals(nodeType)) { + when(mockRoleManagementService.getRoles(anyString(), anyInt(), anyInt(), nullable(String.class), nullable(String.class), anyString())) + .thenAnswer(invocationOnMock -> { + Integer startIndexArg = invocationOnMock.getArgument(2); + + if (startIndexArg != null && startIndexArg < 0) { + String errorMessage = + "Invalid limit requested. Limit value should be greater than or equal to zero. limit: " + + startIndexArg; + throw new IdentityRoleManagementClientException(INVALID_LIMIT.getCode(), errorMessage); + } + return null; + }); + } else { + when(mockRoleManagementService.getRoles(anyInt(), anyInt(), nullable(String.class), nullable(String.class), anyString())). + thenAnswer(invocationOnMock -> { + Integer startIndexArg = invocationOnMock.getArgument(1); + + if (startIndexArg != null && startIndexArg < 0) { + String errorMessage = + "Invalid limit requested. Limit value should be greater than or equal to zero. limit: " + + startIndexArg; + throw new IdentityRoleManagementClientException(INVALID_LIMIT.getCode(), errorMessage); + } + return null; + }); + } - if (startIndexArg != null && startIndexArg < 0) { - String errorMessage = - "Invalid limit requested. Limit value should be greater than or equal to zero. limit: " - + startIndexArg; - throw new IdentityRoleManagementClientException(INVALID_LIMIT.getCode(), errorMessage); - } - return null; - }); SCIMRoleManager roleManager = new SCIMRoleManager(mockRoleManagementService, SAMPLE_TENANT_DOMAIN); assertThrows(CharonException.class, () -> roleManager. listRolesWithPost(getDummySearchRequest(rootNode, startIndex, 2, null, null))); @@ -987,12 +1036,16 @@ public void testListRolesWithPOSTUnExpectedServerError(String nodeType, String t Node rootNode = generateNodeBasedOnNodeType(nodeType, "name"); - when(mockRoleManagementService.getRoles(anyInt(), anyInt(), nullable(String.class), nullable(String.class), anyString())). - thenThrow(unExpectedErrorThrower(tenantDomain, sError, - "Error while listing roles in tenantDomain: ")); - when(mockRoleManagementService.getRoles(anyString(), anyInt(), anyInt(), nullable(String.class), - nullable(String.class), anyString())).thenThrow(unExpectedErrorThrower(tenantDomain, sError, - "Error while listing roles in tenantDomain: ")); + if ("Expression".equals(nodeType)) { + when(mockRoleManagementService.getRoles(anyString(), anyInt(), anyInt(), nullable(String.class), + nullable(String.class), anyString())).thenThrow(unExpectedErrorThrower(tenantDomain, sError, + "Error while listing roles in tenantDomain: ")); + } else { + when(mockRoleManagementService.getRoles(anyInt(), anyInt(), nullable(String.class), nullable(String.class), anyString())). + thenThrow(unExpectedErrorThrower(tenantDomain, sError, + "Error while listing roles in tenantDomain: ")); + } + SCIMRoleManager roleManager = new SCIMRoleManager(mockRoleManagementService, tenantDomain); assertThrows(CharonException.class, () -> roleManager. listRolesWithPost(getDummySearchRequest(rootNode, 2, 2, null, null))); @@ -1045,13 +1098,6 @@ public void testListRolesWithPOSTPositive(String nodeType, String operation) Node rootNode = generateNodeBasedOnNodeType(nodeType, "name", operation); - List roleList = getDummyRoleBasicInfoList(); - - when(mockRoleManagementService.getRoles(anyInt(), anyInt(), anyString(), anyString(), anyString())). - thenAnswer(invocationOnMock -> roleList); - when(mockRoleManagementService.getRoles(anyString(), anyInt(), anyInt(), anyString(), - anyString(), anyString())).thenAnswer(invocationOnMock -> roleList); - SCIMRoleManager roleManager = new SCIMRoleManager(mockRoleManagementService, SAMPLE_TENANT_DOMAIN); roleManager.listRolesWithPost(getDummySearchRequest(rootNode, 2, 3, null, null)); assertTrue(true, "listRolesWIthPost run successfully"); diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManagerV2Test.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManagerV2Test.java index 890de538f..7c0e8f005 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManagerV2Test.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManagerV2Test.java @@ -82,7 +82,6 @@ public void setUpMethod() { @AfterMethod public void tearDown() { identityUtil.close(); - System.clearProperty(CarbonBaseConstants.CARBON_HOME); } @DataProvider(name = "scimOperations") diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMUserManagerTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMUserManagerTest.java index e7e9241ce..707c19912 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMUserManagerTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMUserManagerTest.java @@ -226,7 +226,6 @@ public void tearDown() { scimUserSchemaExtensionBuilder.close(); claimMetadataHandler.close(); resourceManagerUtil.close(); - System.clearProperty(CarbonBaseConstants.CARBON_HOME); } @DataProvider(name = "ClaimData") diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/listener/SCIMUserOperationListenerTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/listener/SCIMUserOperationListenerTest.java index 20b6ce6ea..5b81a1e2b 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/listener/SCIMUserOperationListenerTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/listener/SCIMUserOperationListenerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2017, WSO2 LLC. (http://www.wso2.org) * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/test/utils/CommonTestUtils.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/test/utils/CommonTestUtils.java index af4dcc3ea..d19e7f2e2 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/test/utils/CommonTestUtils.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/test/utils/CommonTestUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2017, WSO2 LLC. (http://www.wso2.org) * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTest.java index 0fde819e8..997d53496 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTest.java @@ -35,7 +35,12 @@ import java.util.Map; -import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; public class AdminAttributeUtilTest { diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTestForGroup.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTestForGroup.java index 255f0193e..f8b78d9b2 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTestForGroup.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AdminAttributeUtilTestForGroup.java @@ -39,9 +39,14 @@ import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.util.UserCoreUtil; -import static org.mockito.Mockito.*; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import static org.testng.Assert.assertEquals; diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AttributeMapperTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AttributeMapperTest.java index f28d963d0..fea6895d8 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AttributeMapperTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AttributeMapperTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2017, WSO2 LLC. (http://www.wso2.org) * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AuthenticationSchemaTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AuthenticationSchemaTest.java index 34a025b25..996edb2eb 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AuthenticationSchemaTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/AuthenticationSchemaTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2017, WSO2 LLC. (http://www.wso2.org) * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/SCIMCommonUtilsTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/SCIMCommonUtilsTest.java index 493cdb9d0..28886d844 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/SCIMCommonUtilsTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/SCIMCommonUtilsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2017, WSO2 LLC. (http://www.wso2.org) * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/SCIMConfigProcessorTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/SCIMConfigProcessorTest.java index a69b231e9..0c79879ac 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/SCIMConfigProcessorTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/utils/SCIMConfigProcessorTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2017, WSO2 LLC. (http://www.wso2.org) * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except From 7817051385db5aae3cb110e4fd81670f4b143e02 Mon Sep 17 00:00:00 2001 From: kumuditha Date: Tue, 24 Sep 2024 12:30:51 +0530 Subject: [PATCH 13/13] Address review comments --- .../common/group/SCIMGroupHandlerTest.java | 9 ++----- .../common/impl/SCIMUserManagerTest.java | 27 ++++++++++++------- .../SCIMUserOperationListenerTest.java | 9 ++++++- 3 files changed, 27 insertions(+), 18 deletions(-) diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/group/SCIMGroupHandlerTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/group/SCIMGroupHandlerTest.java index 089989df0..ec8cabee0 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/group/SCIMGroupHandlerTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/group/SCIMGroupHandlerTest.java @@ -18,7 +18,6 @@ package org.wso2.carbon.identity.scim2.common.group; -import org.apache.commons.lang.StringUtils; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockedConstruction; @@ -75,7 +74,6 @@ public class SCIMGroupHandlerTest { private MockedStatic scimCommonUtils; private MockedStatic identityDatabaseUtil; private MockedStatic identityTenantUtil; - private MockedStatic stringUtils; @BeforeMethod public void setUp() { @@ -84,7 +82,6 @@ public void setUp() { scimCommonUtils = mockStatic(SCIMCommonUtils.class); identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); identityTenantUtil = mockStatic(IdentityTenantUtil.class); - stringUtils = mockStatic(StringUtils.class); } @AfterMethod @@ -92,7 +89,6 @@ public void tearDown() throws Exception { scimCommonUtils.close(); identityDatabaseUtil.close(); identityTenantUtil.close(); - stringUtils.close(); } @Test @@ -181,13 +177,12 @@ public void testGetGroupName() throws Exception { when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection); when(connection.prepareStatement(anyString())).thenReturn(mockedPreparedStatement); - when(StringUtils.isNotEmpty(nullable(String.class))).thenReturn(true); when(SCIMCommonUtils.getPrimaryFreeGroupName(nullable(String.class))).thenReturn("directors"); when(mockedPreparedStatement.executeQuery()).thenReturn(resultSet); when(mockedGroupDAO.getGroupNameById(1, "5")).thenReturn("directors"); + when(resultSet.next()).thenReturn(true).thenReturn(false); + when(resultSet.getString(1)).thenReturn("roleName"); assertEquals(new SCIMGroupHandler(1).getGroupName("5"), "directors", "asserting for existance"); - - when(StringUtils.isNotEmpty(nullable(String.class))).thenReturn(false); assertNull(new SCIMGroupHandler(1).getGroupName("NON_EXISITNG_GROUP_NAME"), "asserting for non existance"); } diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMUserManagerTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMUserManagerTest.java index 707c19912..07390bdd8 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMUserManagerTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/impl/SCIMUserManagerTest.java @@ -110,7 +110,14 @@ import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; @@ -362,7 +369,7 @@ public Object[][] groupName() throws Exception { @Test(dataProvider = "getGroupException") public void testGetGroupWithExceptions(String roleName, String userStoreDomain) throws Exception { - AbstractUserStoreManager mockedUserStoreManager = Mockito.mock(AbstractUserStoreManager.class); + AbstractUserStoreManager mockedUserStoreManager = mock(AbstractUserStoreManager.class); Field field = AbstractUserStoreManager.class.getDeclaredField("userStoreManagerHolder"); field.setAccessible(true); field.set(mockedUserStoreManager, new HashMap()); @@ -423,7 +430,7 @@ public void testListGroupsWithFilter(String filter, String roleName, String user mockedUserStoreManager = mock(AbstractUserStoreManager.class); - AbstractUserStoreManager mockedUserStoreManager = Mockito.mock(AbstractUserStoreManager.class); + AbstractUserStoreManager mockedUserStoreManager = mock(AbstractUserStoreManager.class); Field field = AbstractUserStoreManager.class.getDeclaredField("userStoreManagerHolder"); field.setAccessible(true); field.set(mockedUserStoreManager, new HashMap()); @@ -1450,7 +1457,7 @@ public void testGetUserWhenSCIMisDisabled() throws Exception { scimToLocalClaimsMap.put(SCIMConstants.CommonSchemaConstants.ID_URI, USERID_LOCAL_CLAIM); when(SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimsMap); - mockedUserStoreManager = Mockito.mock(AbstractUserStoreManager.class); + mockedUserStoreManager = mock(AbstractUserStoreManager.class); SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockClaimMetadataManagementService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); org.wso2.carbon.user.core.common.User user = mock(org.wso2.carbon.user.core.common.User.class); @@ -1485,7 +1492,7 @@ public void testDeleteUserWithInvalidUserId() throws Exception { List coreUsers = new ArrayList<>(); when(SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimsMap); - AbstractUserStoreManager mockedUserStoreManager = Mockito.mock(AbstractUserStoreManager.class); + AbstractUserStoreManager mockedUserStoreManager = mock(AbstractUserStoreManager.class); when(mockedUserStoreManager.getUserListWithID(anyString(), anyString(), anyString())).thenReturn(coreUsers); SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockClaimMetadataManagementService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); @@ -1507,7 +1514,7 @@ public void testDeleteUserWhenSCIMisDisabled() throws Exception { coreUser.setUserStoreDomain("DomainName"); when(SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimsMap); - AbstractUserStoreManager mockedUserStoreManager = Mockito.mock(AbstractUserStoreManager.class); + AbstractUserStoreManager mockedUserStoreManager = mock(AbstractUserStoreManager.class); when(mockedUserStoreManager.getUserWithID(anyString(), any(), anyString())).thenReturn(coreUser); when(mockedUserStoreManager.getSecondaryUserStoreManager("DomainName")).thenReturn(mockedUserStoreManager); when(mockedUserStoreManager.isSCIMEnabled()).thenReturn(false); @@ -1530,7 +1537,7 @@ public void testDeleteUserWithUserStoreDomainMismatch() throws Exception { coreUser.setUserStoreDomain("PRIMARY"); when(SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimsMap); - AbstractUserStoreManager mockedUserStoreManager = Mockito.mock(AbstractUserStoreManager.class); + AbstractUserStoreManager mockedUserStoreManager = mock(AbstractUserStoreManager.class); when(mockedUserStoreManager.getUserWithID(anyString(), any(), anyString())).thenReturn(coreUser); SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockClaimMetadataManagementService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); @@ -1585,7 +1592,7 @@ public void testCreateUserWhenSCIMisDisabled() throws Exception { SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockClaimMetadataManagementService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); doThrow(new NotImplementedException()).when(mockedUser).setSchemas(Mockito.any(UserManager.class)); - mockedUser.setSchemas(Mockito.mock(UserManager.class)); + mockedUser.setSchemas(mock(UserManager.class)); scimUserManager.createUser(user, null); // This method is for testing of throwing CharonException, hence no assertion. } @@ -1616,7 +1623,7 @@ public void testCreateUserWithExistingUserName(String isLoginIdentifiersEnabled) when(ApplicationManagementService.getInstance()).thenReturn(applicationManagementService); when(applicationManagementService.getServiceProvider(anyString(), anyString())).thenReturn(null); - mockedUserStoreManager = Mockito.mock(AbstractUserStoreManager.class); + mockedUserStoreManager = mock(AbstractUserStoreManager.class); when(mockedUserStoreManager.isExistingUserWithID(anyString())).thenReturn(true); when(mockedUserStoreManager.isExistingUser(anyString())).thenReturn(true); when(mockedUserStoreManager.getUserList(anyString(), anyString(), nullable(String.class))).thenReturn(existingUserList); @@ -1650,7 +1657,7 @@ public void testCreateUserWithConflictingLoginIdentifier() throws Exception { when(SCIMCommonUtils.convertSCIMtoLocalDialect(anyMap())).thenCallRealMethod(); when(SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimMappings); - mockedUserStoreManager = Mockito.mock(AbstractUserStoreManager.class); + mockedUserStoreManager = mock(AbstractUserStoreManager.class); when(mockedUserStoreManager.getUserList(anyString(), anyString(), anyString())).thenReturn(null); when(mockedUserStoreManager.getSecondaryUserStoreManager(anyString())) .thenReturn(secondaryUserStoreManager); diff --git a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/listener/SCIMUserOperationListenerTest.java b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/listener/SCIMUserOperationListenerTest.java index 5b81a1e2b..2b6a5a3d3 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/listener/SCIMUserOperationListenerTest.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/test/java/org/wso2/carbon/identity/scim2/common/listener/SCIMUserOperationListenerTest.java @@ -48,7 +48,14 @@ import java.util.Map; import java.util.UUID; -import static org.mockito.Mockito.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull;