diff --git a/components/org.wso2.carbon.identity.scim2.common/pom.xml b/components/org.wso2.carbon.identity.scim2.common/pom.xml index 5bd5e890c..de8acd065 100644 --- a/components/org.wso2.carbon.identity.scim2.common/pom.xml +++ b/components/org.wso2.carbon.identity.scim2.common/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.identity.inbound.provisioning.scim2 identity-inbound-provisioning-scim2 ../../pom.xml - 3.4.92-SNAPSHOT + 3.4.98-SNAPSHOT 4.0.0 @@ -177,12 +177,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/main/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManager.java b/components/org.wso2.carbon.identity.scim2.common/src/main/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManager.java index b0402b85d..e9976dc07 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/main/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManager.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/main/java/org/wso2/carbon/identity/scim2/common/impl/SCIMRoleManager.java @@ -39,6 +39,7 @@ import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.core.UserCoreConstants; import org.wso2.carbon.user.core.common.AbstractUserStoreManager; +import org.wso2.carbon.user.core.util.UserCoreUtil; import org.wso2.charon3.core.exceptions.BadRequestException; import org.wso2.charon3.core.exceptions.CharonException; import org.wso2.charon3.core.exceptions.ConflictException; @@ -812,11 +813,9 @@ private void prepareAddedRemovedUserLists(Set addedMembers, Set userStoreManager.getUserListWithID(SCIMConstants.CommonSchemaConstants.ID_URI, memberObject.get(SCIMConstants.CommonSchemaConstants.VALUE), null); if (isNotEmpty(userListWithID)) { - String tempDisplay = userListWithID.get(0).getUsername(); - if(StringUtils.isNotBlank(userListWithID.get(0).getUserStoreDomain())) { - tempDisplay = userListWithID.get(0).getUserStoreDomain() + "/" + tempDisplay; - } - memberObject.put(SCIMConstants.RoleSchemaConstants.DISPLAY, tempDisplay); + memberObject.put(SCIMConstants.RoleSchemaConstants.DISPLAY, + UserCoreUtil.addDomainToName(userListWithID.get(0).getUsername(), + userListWithID.get(0).getUserStoreDomain())); memberOperation.setValues(memberObject); } } diff --git a/components/org.wso2.carbon.identity.scim2.common/src/main/java/org/wso2/carbon/identity/scim2/common/impl/SCIMUserManager.java b/components/org.wso2.carbon.identity.scim2.common/src/main/java/org/wso2/carbon/identity/scim2/common/impl/SCIMUserManager.java index ed177f540..15b7258d0 100644 --- a/components/org.wso2.carbon.identity.scim2.common/src/main/java/org/wso2/carbon/identity/scim2/common/impl/SCIMUserManager.java +++ b/components/org.wso2.carbon.identity.scim2.common/src/main/java/org/wso2/carbon/identity/scim2/common/impl/SCIMUserManager.java @@ -1474,18 +1474,7 @@ private UsersGetResponse filterUsersBySingleAttribute(ExpressionNode node, Map paginateUsers(Set limit + offset, then return only the users bounded by the offset and the limit. AbstractSet usersSorted = new TreeSet<>( Comparator.comparing(org.wso2.carbon.user.core.common.User::getFullQualifiedUsername)); - if (users.size() > limit + offset) { + if (Integer.MAX_VALUE != limit && users.size() > limit + offset) { usersSorted.addAll(new ArrayList<>(sortedSet).subList(offset - 1, limit + offset - 1)); } else { // Return all the users from the offset. 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..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 @@ -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 @@ -18,12 +18,12 @@ package org.wso2.carbon.identity.scim2.common.group; -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.identity.core.util.IdentityDatabaseUtil; @@ -32,11 +32,13 @@ 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 +46,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 +71,29 @@ public class SCIMGroupHandlerTest extends PowerMockTestCase { @Mock private PreparedStatement mockedPreparedStatement; + private MockedStatic scimCommonUtils; + private MockedStatic identityDatabaseUtil; + private MockedStatic identityTenantUtil; + @BeforeMethod - public void setUp() throws Exception { + public void setUp() { + initMocks(this); + scimCommonUtils = mockStatic(SCIMCommonUtils.class); + identityDatabaseUtil = mockStatic(IdentityDatabaseUtil.class); + identityTenantUtil = mockStatic(IdentityTenantUtil.class); + } + + @AfterMethod + public void tearDown() throws Exception { + scimCommonUtils.close(); + identityDatabaseUtil.close(); + identityTenantUtil.close(); } @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 +121,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 +141,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,32 +154,35 @@ 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); - 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"); } @@ -185,9 +195,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 +215,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 +230,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 +268,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"); + // This method is to test the throwing of an IdentitySCIMException, hence no assertion. + } } @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); 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..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 @@ -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..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 @@ -19,8 +19,9 @@ 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.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -33,17 +34,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 +56,23 @@ 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); + } + + @AfterMethod + public void tearDownMethod() { + serviceURLBuilder.close(); + identityTenantUtil.close(); } @DataProvider(name = "dataProviderForBuild") @@ -82,7 +91,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 +118,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..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 @@ -19,44 +19,37 @@ 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.AfterMethod; import org.testng.annotations.BeforeMethod; -import org.testng.annotations.ObjectFactory; import org.testng.annotations.Test; -import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.testng.annotations.Listeners; +import org.mockito.testng.MockitoTestNGListener; 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; 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; @@ -67,45 +60,31 @@ public class IdentitySCIMManagerTest extends PowerMockTestCase { @Mock UserRealm mockedUserRealm; - @Mock - ClaimManager mockedClaimManager; - - @Mock - AbstractUserStoreManager mockedUserStoreManager; - private SCIMConfigProcessor scimConfigProcessor; private IdentitySCIMManager identitySCIMManager; + private MockedStatic scimCommonUtils; + private MockedStatic scimCommonComponentHolder; + @BeforeMethod public void setUp() throws Exception { + scimCommonUtils = mockStatic(SCIMCommonUtils.class); + scimCommonUtils.when(() -> SCIMCommonUtils.getSCIMUserURL()).thenReturn("http://scimUserUrl:9443"); - mockStatic(SCIMCommonUtils.class); - when(SCIMCommonUtils.getSCIMUserURL()).thenReturn("http://scimUserUrl:9443"); - - mockStatic(SCIMCommonComponentHolder.class); - when(SCIMCommonComponentHolder.getRealmService()).thenReturn(realmService); - + scimCommonComponentHolder = mockStatic(SCIMCommonComponentHolder.class); 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(); - mockStatic(SCIMCommonComponentHolder.class); - - 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(); } - @ObjectFactory - public IObjectFactory getObjectFactory() { - - return new org.powermock.modules.testng.PowerMockObjectFactory(); + @AfterMethod + public void tearDown() { + scimCommonComponentHolder.close(); + scimCommonUtils.close(); } @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 8ac8b3e76..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 @@ -20,11 +20,12 @@ 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.testng.annotations.BeforeClass; +import org.mockito.MockedStatic; +import org.mockito.testng.MockitoTestNGListener; +import org.testng.annotations.AfterMethod; 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; @@ -63,17 +64,16 @@ 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.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.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertThrows; import static org.testng.Assert.assertTrue; @@ -87,8 +87,8 @@ /** * Contains the unit test cases for SCIMRoleManager. */ -@PrepareForTest({SCIMCommonUtils.class, OrganizationManagementUtil.class}) -public class SCIMRoleManagerTest extends PowerMockTestCase { +@Listeners(MockitoTestNGListener.class) +public class SCIMRoleManagerTest { private static final String SAMPLE_TENANT_DOMAIN = "carbon.super"; private static final String SAMPLE_TENANT_DOMAIN2 = "abc.com"; @@ -121,21 +121,25 @@ public class SCIMRoleManagerTest extends PowerMockTestCase { @Mock RoleManagementService mockRoleManagementService; - @BeforeClass - public void setUpClass() { - - initMocks(this); - } + private MockedStatic scimCommonUtils; + private MockedStatic organizationManagementUtil; @BeforeMethod public void setUpMethod() { - mockStatic(SCIMCommonUtils.class); - mockStatic(OrganizationManagementUtil.class); + 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 +167,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 +183,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 +210,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 +239,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); @@ -437,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)); @@ -476,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. @@ -519,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)); @@ -578,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); @@ -631,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), 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())). - 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]); @@ -725,7 +774,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 +819,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 +834,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 +866,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 +887,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]); @@ -891,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))); @@ -933,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))); @@ -977,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))); @@ -1035,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 96eca05c0..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 @@ -19,13 +19,13 @@ 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.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.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; @@ -43,6 +43,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 +51,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 +64,8 @@ public class SCIMRoleManagerV2Test extends PowerMockTestCase { private SCIMRoleManagerV2 scimRoleManagerV2; + private MockedStatic identityUtil; + @BeforeClass public void setUpClass() { @@ -73,10 +75,15 @@ public void setUpClass() { @BeforeMethod public void setUpMethod() { - PowerMockito.mockStatic(IdentityUtil.class); + identityUtil = mockStatic(IdentityUtil.class); scimRoleManagerV2 = new SCIMRoleManagerV2(roleManagementService, SAMPLE_TENANT_DOMAIN); } + @AfterMethod + public void tearDown() { + identityUtil.close(); + } + @DataProvider(name = "scimOperations") public Object[][] provideScimOperations() { 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..3dd0fb46f 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,19 +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.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.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; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.identity.application.common.model.InboundProvisioningConfig; import org.wso2.carbon.identity.application.common.model.ServiceProvider; @@ -48,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; @@ -85,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; @@ -107,14 +110,15 @@ import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.nullable; +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.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 +126,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"; @@ -195,12 +193,46 @@ 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 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(); } @DataProvider(name = "ClaimData") @@ -265,28 +297,26 @@ 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.when(SCIMUserSchemaExtensionBuilder::getInstance).thenReturn(sb); when(sb.getExtensionSchema()).thenReturn(mockedSCIMAttributeSchema); - mockStatic(IdentityUtil.class); - when(IdentityUtil.extractDomainFromName(anyString())).thenReturn("testPrimaryDomain"); + identityUtil.when(() -> IdentityUtil.extractDomainFromName(anyString())).thenReturn("testPrimaryDomain"); - mockStatic(SCIMCommonUtils.class); - when(SCIMCommonUtils.convertLocalToSCIMDialect(anyMap(), anyMap())).thenReturn(new HashMap() {{ + 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()); + 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); 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,31 +324,26 @@ 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.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") 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.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.when(() -> SCIMCommonUtils.getSCIMGroupURL()).thenReturn("https://localhost:9443/scim2/Groups"); - mockStatic(CarbonConstants.class); CarbonConstants.ENABLE_LEGACY_AUTHZ_RUNTIME = true; SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockedClaimManager); @@ -344,13 +369,13 @@ 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 = mock(AbstractUserStoreManager.class); + Field field = AbstractUserStoreManager.class.getDeclaredField("userStoreManagerHolder"); + field.setAccessible(true); + field.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.when(() -> IdentityUtil.extractDomainFromName(anyString())).thenReturn(userStoreDomain); SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockedClaimManager); try { @@ -397,18 +422,18 @@ 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); 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()); + AbstractUserStoreManager mockedUserStoreManager = 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); @@ -422,7 +447,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 +454,12 @@ public void testListGroupsWithFilter(String filter, String roleName, String user when(mockIdentityUtil.extractDomainFromName(anyString())).thenReturn("value"); - 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.when(() -> SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimsMap); SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockedClaimManager); GroupsGetResponse groupsResponse = scimUserManager.listGroupsWithGET(node, 1, 1, null, null, @@ -457,14 +479,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"); - mockStatic(SCIMCommonUtils.class); - when(SCIMCommonUtils.getSCIMtoLocalMappings()).thenReturn(scimToLocalClaimMap); - when(SCIMCommonUtils.convertLocalToSCIMDialect(anyMap(), anyMap())).thenReturn(new HashMap() {{ + 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); - when(mockedUserStoreManager.getUserListWithID("http://wso2.org/claims/userid", "*", null)).thenReturn(users); when(mockedUserStoreManager.getRoleListOfUserWithID(anyString())).thenReturn(new ArrayList<>()); when(mockedUserStoreManager.getRealmConfiguration()).thenReturn(mockedRealmConfig); @@ -475,9 +494,7 @@ public void testListUsersWithGET(List use when(mockedUserStoreManager.getSecondaryUserStoreManager("SECONDARY")).thenReturn(secondaryUserStoreManager); when(secondaryUserStoreManager.isSCIMEnabled()).thenReturn(isScimEnabledForSecondary); - 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 +561,12 @@ public void testFilteringUsersWithGET(List() {{ + 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 +581,9 @@ public void testFilteringUsersWithGET(List() {{ + 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); @@ -659,7 +672,7 @@ public void testFilteringUsersWithGETWithPagination(List()); @@ -686,8 +699,7 @@ public void testFilteringUsersWithGETWithPagination(List IdentityTenantUtil.getRealmService()).thenReturn(mockRealmService); when(mockRealmService.getBootstrapRealmConfiguration()).thenReturn(mockedRealmConfig); ClaimMapping[] claimMappings = getTestClaimMappings(); @@ -705,9 +717,9 @@ public void testFilteringUsersWithGETWithPagination(List SCIMCommonUtils.isConsiderTotalRecordsForTotalResultOfLDAPEnabled()) .thenReturn(isConsiderTotalRecordsForTotalResultOfLDAPEnabled); - when(SCIMCommonUtils.isConsiderMaxLimitForTotalResultEnabled()) + scimCommonUtils.when(() -> SCIMCommonUtils.isConsiderMaxLimitForTotalResultEnabled()) .thenReturn(isConsiderMaxLimitForTotalResultEnabled); Map supportedByDefaultProperties = new HashMap() {{ @@ -747,6 +759,7 @@ public void testFilteringUsersWithGETWithPagination(List 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"); - - 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); + userCoreUtil = mockStatic(UserCoreUtil.class); + userCoreUtil.when(() -> UserCoreUtil.isEveryoneRole("role", mockedRealmConfig)).thenReturn(false); + scimCommonUtils.when(() -> SCIMCommonUtils.getSCIMGroupURL()).thenReturn("https://localhost:9443/scim2/Groups"); + + 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); + } + userCoreUtil.close(); } @DataProvider(name = "listApplicationRoles") @@ -1021,23 +1041,22 @@ 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.when(() -> SCIMCommonUtils.getSCIMGroupURL()).thenReturn("https://localhost:9443/scim2/Groups"); - 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") @@ -1055,12 +1074,6 @@ public Object[][] applicationDomainWithFilters() { }; } - @ObjectFactory - public IObjectFactory getObjectFactory() { - - return new org.powermock.modules.testng.PowerMockObjectFactory(); - } - @Test public void testGetEnterpriseUserSchemaWhenEnabled() throws Exception { @@ -1099,12 +1112,10 @@ 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.when(() -> SCIMCommonUtils.isEnterpriseUserExtensionEnabled()).thenReturn(true); SCIMUserSchemaExtensionBuilder sb = spy(new SCIMUserSchemaExtensionBuilder()); - mockStatic(SCIMUserSchemaExtensionBuilder.class); - when(SCIMUserSchemaExtensionBuilder.getInstance()).thenReturn(sb); + 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 +1128,7 @@ public void testGetEnterpriseUserSchemaWhenEnabled() throws Exception { @Test public void testGetEnterpriseUserSchemaWhenDisabled() throws Exception { - mockStatic(SCIMCommonUtils.class); - when(SCIMCommonUtils.isEnterpriseUserExtensionEnabled()).thenReturn(false); + scimCommonUtils.when(() -> SCIMCommonUtils.isEnterpriseUserExtensionEnabled()).thenReturn(false); SCIMUserManager userManager = new SCIMUserManager(mockedUserStoreManager, mockClaimMetadataManagementService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); assertEquals(userManager.getEnterpriseUserSchema(), null); @@ -1137,14 +1147,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; @@ -1198,7 +1208,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); @@ -1332,7 +1341,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()). @@ -1340,8 +1348,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); @@ -1349,7 +1357,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,13 +1378,11 @@ 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, mockClaimMetadataManagementService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); - mockStatic(IdentityUtil.class); when(IdentityUtil.isGroupsVsRolesSeparationImprovementsEnabled()) .thenReturn(isGroupsVsRolesSeparationImprovementsEnabled); when(IdentityUtil.getProperty(SCIMCommonConstants.PRIMARY_LOGIN_IDENTIFIER_CLAIM)) @@ -1384,7 +1390,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() { @@ -1395,16 +1400,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") @@ -1424,7 +1433,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, @@ -1434,7 +1442,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. @@ -1449,9 +1456,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 = 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,13 +1491,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 = 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); @@ -1509,15 +1513,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 = 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); @@ -1534,9 +1536,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 = mock(AbstractUserStoreManager.class); when(mockedUserStoreManager.getUserWithID(anyString(), any(), anyString())).thenReturn(coreUser); SCIMUserManager scimUserManager = new SCIMUserManager(mockedUserStoreManager, mockClaimMetadataManagementService, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); @@ -1544,7 +1545,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); @@ -1557,16 +1557,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); @@ -1579,7 +1579,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); @@ -1588,11 +1587,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(mock(UserManager.class)); scimUserManager.createUser(user, null); // This method is for testing of throwing CharonException, hence no assertion. } @@ -1614,18 +1614,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 = 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); @@ -1648,21 +1646,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 = 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 466dc8aba..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 @@ -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 @@ -19,12 +19,12 @@ 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.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.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; @@ -33,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; @@ -49,22 +48,21 @@ 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.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; 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 +91,30 @@ 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 { - + initMocks(this); 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); + identityUtil = mockStatic(IdentityUtil.class); SCIMCommonComponentHolder.setClaimManagementService(claimMetadataManagementService); when(userStoreManager.getTenantId()).thenReturn(-1234); - when(IdentityTenantUtil.getTenantDomain(anyInt())).thenReturn(CARBON_SUPER); + identityTenantUtil.when(() -> IdentityTenantUtil.getTenantDomain(anyInt())).thenReturn(CARBON_SUPER); + } + + @AfterMethod + public void tearDown() { + userCoreUtil.close(); + scimCommonUtils.close(); + identityTenantUtil.close(); + identityUtil.close(); } @DataProvider(name = "testGetExecutionOrderIdData") @@ -234,8 +240,7 @@ 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.when(() -> IdentityUtil.getProperty(FrameworkConstants.ENABLE_JIT_PROVISION_ENHANCE_FEATURE)).thenReturn("false"); assertTrue(scimUserOperationListener. doPreSetUserClaimValuesWithID(userId, claims, profile, userStoreManager)); @@ -307,19 +312,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) @@ -333,10 +332,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 @@ -363,9 +365,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) @@ -379,10 +384,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 @@ -426,7 +434,6 @@ public Object[][] testSCIMAttributesData() { @Test(dataProvider = "testSCIMAttributesData") public void testGetSCIMAttributes(Map claimsMap) throws Exception { - 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 +442,12 @@ 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); 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 +456,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/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 4ccc36dce..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 @@ -20,33 +20,30 @@ 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.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.Matchers.anyInt; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.eq; +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.powermock.api.mockito.PowerMockito.mockStatic; -import static org.powermock.api.mockito.PowerMockito.when; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; -@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,9 +56,24 @@ public class AdminAttributeUtilTest extends PowerMockTestCase { AdminAttributeUtil adminAttributeUtil; + private MockedStatic scimCommonComponentHolder; + private MockedStatic claimsMgtUtil; + 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") @@ -76,15 +88,12 @@ 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.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 +103,7 @@ 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.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..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 @@ -20,8 +20,9 @@ import org.mockito.ArgumentCaptor; import org.mockito.Mock; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.testng.PowerMockTestCase; +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; @@ -38,18 +39,18 @@ 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.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.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.when; +import static org.mockito.MockitoAnnotations.initMocks; 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,9 +69,33 @@ 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 { + 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,13 +118,7 @@ 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.when(() -> SCIMCommonComponentHolder.getRealmService()).thenReturn(realmService); when(realmService.getTenantUserRealm(anyInt())).thenReturn(userRealm); when(userRealm.getUserStoreManager()).thenReturn(userStoreManager); when(userStoreManager.isSCIMEnabled()).thenReturn(true); @@ -107,42 +126,38 @@ 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); - - ArgumentCaptor argument = ArgumentCaptor.forClass(String.class); - CarbonConstants.ENABLE_LEGACY_AUTHZ_RUNTIME = true; - adminAttributeUtil.updateAdminGroup(1); - verify(scimGroupHandler).addMandatoryAttributes(argument.capture()); - - assertEquals(argument.getValue(), roleNameWithDomain); + 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); + + 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); + } } @Test(expectedExceptions = IdentitySCIMException.class) 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.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/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 21b298c53..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 @@ -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,39 +64,43 @@ 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 - public void tearDown() throws Exception { + public void tearDown() { + identityUtil.close(); + userCoreUtil.close(); + identityTenantUtil.close(); + serviceURLBuilder.close(); System.clearProperty(CarbonBaseConstants.CARBON_HOME); } @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 +108,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 +116,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 +124,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 +132,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 +140,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 +148,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 +156,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 +164,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 +246,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 +254,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/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 diff --git a/components/org.wso2.carbon.identity.scim2.provider/pom.xml b/components/org.wso2.carbon.identity.scim2.provider/pom.xml index 6c2c59e8a..60e4b7c8c 100644 --- a/components/org.wso2.carbon.identity.scim2.provider/pom.xml +++ b/components/org.wso2.carbon.identity.scim2.provider/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.identity.inbound.provisioning.scim2 identity-inbound-provisioning-scim2 ../../pom.xml - 3.4.92-SNAPSHOT + 3.4.98-SNAPSHOT 4.0.0 diff --git a/features/org.wso2.carbon.identity.scim2.common.feature/pom.xml b/features/org.wso2.carbon.identity.scim2.common.feature/pom.xml index ed4907e3c..772735a74 100644 --- a/features/org.wso2.carbon.identity.scim2.common.feature/pom.xml +++ b/features/org.wso2.carbon.identity.scim2.common.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.identity.inbound.provisioning.scim2 identity-inbound-provisioning-scim2 ../../pom.xml - 3.4.92-SNAPSHOT + 3.4.98-SNAPSHOT 4.0.0 diff --git a/features/org.wso2.carbon.identity.scim2.common.feature/resources/org.wso2.carbon.identity.scim2.common.feature.default.json b/features/org.wso2.carbon.identity.scim2.common.feature/resources/org.wso2.carbon.identity.scim2.common.feature.default.json index 76480bbe0..9c0eb384b 100644 --- a/features/org.wso2.carbon.identity.scim2.common.feature/resources/org.wso2.carbon.identity.scim2.common.feature.default.json +++ b/features/org.wso2.carbon.identity.scim2.common.feature/resources/org.wso2.carbon.identity.scim2.common.feature.default.json @@ -4,7 +4,7 @@ "scim2.custom_user_schema_uri": "urn:scim:wso2:schema", "scim2.max_bulk_operations": "1000", "scim2.max_bulk_payload": "1048576", - "scim2.documentation_uri": "https://docs.wso2.com/display/IS580/Using+the+SCIM+2.0+REST+APIs", + "scim2.documentation_uri": "https://is.docs.wso2.com/en/latest/apis/scim2/", "scim2.oauth_bearer.primary": true, "scim2.http_basic.primary": false, "scim2.basic_auth_documentation_uri": "$ref{scim2.documentation_uri}", diff --git a/features/org.wso2.carbon.identity.scim2.provider.feature/pom.xml b/features/org.wso2.carbon.identity.scim2.provider.feature/pom.xml index 111fa8f22..b15b406c4 100644 --- a/features/org.wso2.carbon.identity.scim2.provider.feature/pom.xml +++ b/features/org.wso2.carbon.identity.scim2.provider.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.identity.inbound.provisioning.scim2 identity-inbound-provisioning-scim2 ../../pom.xml - 3.4.92-SNAPSHOT + 3.4.98-SNAPSHOT 4.0.0 diff --git a/features/org.wso2.carbon.identity.scim2.server.feature/pom.xml b/features/org.wso2.carbon.identity.scim2.server.feature/pom.xml index 8fd36bdf1..6241a2fee 100644 --- a/features/org.wso2.carbon.identity.scim2.server.feature/pom.xml +++ b/features/org.wso2.carbon.identity.scim2.server.feature/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.identity.inbound.provisioning.scim2 identity-inbound-provisioning-scim2 ../../pom.xml - 3.4.92-SNAPSHOT + 3.4.98-SNAPSHOT 4.0.0 diff --git a/pom.xml b/pom.xml index e360a4621..9075d0c76 100644 --- a/pom.xml +++ b/pom.xml @@ -28,7 +28,7 @@ identity-inbound-provisioning-scim2 pom 4.0.0 - 3.4.92-SNAPSHOT + 3.4.98-SNAPSHOT WSO2 Carbon - SCIM Provisioning Module SCIM 2.0 Implementation for C4 @@ -235,15 +235,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 @@ -333,12 +327,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