diff options
Diffstat (limited to 'ecomp-portal-BE-common/src/test')
34 files changed, 8231 insertions, 337 deletions
diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppContactUsControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppContactUsControllerTest.java index 522ef7ca..e35d3266 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppContactUsControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppContactUsControllerTest.java @@ -306,13 +306,13 @@ public class AppContactUsControllerTest extends MockitoTestSuite{ PortalRestResponse<String> expectedResponse = new PortalRestResponse<String>(); expectedResponse.setStatus(PortalRestStatusEnum.OK); expectedResponse.setMessage("success"); - expectedResponse.setResponse("\"ush_ticket_url\":\"http://todo_enter_ush_ticket_url\",\"portal_info_url\":\"https://todo_enter_portal_info_url\",\"feedback_email_address\":\"portal@lists.openecomp.org\""); + expectedResponse.setResponse("\"ush_ticket_url\":\"http://todo_enter_ush_ticket_url\",\"portal_info_url\":\"https://todo_enter_portal_info_url\",\"feedback_email_address\":\"portal@lists.onap.org\""); PowerMockito.mockStatic(SystemProperties.class); PowerMockito.mockStatic(EPCommonSystemProperties.class); Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.USH_TICKET_URL)).thenReturn("http://todo_enter_ush_ticket_url"); Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.PORTAL_INFO_URL)).thenReturn("https://todo_enter_portal_info_url"); - Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.FEEDBACK_EMAIL_ADDRESS)).thenReturn("portal@lists.openecomp.org"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.FEEDBACK_EMAIL_ADDRESS)).thenReturn("portal@lists.onap.org"); actualResponse = appContactUsController.getPortalDetails(mockedRequest); assertTrue(actualResponse.getStatus().compareTo(PortalRestStatusEnum.OK) == 0); @@ -330,7 +330,7 @@ public class AppContactUsControllerTest extends MockitoTestSuite{ Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.USH_TICKET_URL)).thenThrow(nullPointerException); Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.PORTAL_INFO_URL)).thenReturn("https://todo_enter_portal_info_url"); - Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.FEEDBACK_EMAIL_ADDRESS)).thenReturn("portal@lists.openecomp.org"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.FEEDBACK_EMAIL_ADDRESS)).thenReturn("portal@lists.onap.org"); actualResponse = appContactUsController.getPortalDetails(mockedRequest); assertEquals(actualResponse, expectedResponse); diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/DashboardControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/DashboardControllerTest.java index 37f7f687..54671ad3 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/DashboardControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/DashboardControllerTest.java @@ -242,7 +242,7 @@ public class DashboardControllerTest { expectedData.setStatus(PortalRestStatusEnum.ERROR); expectedData.setMessage("ERROR"); expectedData.setResponse("Category cannot be null or empty"); - + Mockito.when(adminRolesService.isSuperAdmin(Matchers.anyObject())).thenReturn(true); PortalRestResponse<String> actualResponse = dashboardController.saveWidgetData(commonWidget, mockedRequest, mockedResponse); assertEquals(expectedData,actualResponse); @@ -258,7 +258,7 @@ public class DashboardControllerTest { expectedData.setMessage("Invalid category: test"); expectedData.setResponse(null); Mockito.when(adminRolesService.isSuperAdmin(Matchers.anyObject())).thenReturn(true); - PortalRestResponse<String> actualResponse = dashboardController.saveWidgetData(commonWidget, mockedRequest, mockedResponse); + PortalRestResponse<String> actualResponse = dashboardController.saveWidgetData(commonWidget,mockedRequest, mockedResponse); assertEquals(expectedData,actualResponse); } diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/ExternalAccessRolesControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/ExternalAccessRolesControllerTest.java index 859cc4c2..47a1394e 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/ExternalAccessRolesControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/ExternalAccessRolesControllerTest.java @@ -76,6 +76,7 @@ import org.onap.portalsdk.core.domain.Role; import org.onap.portalsdk.core.restful.domain.EcompUser; import org.springframework.beans.BeanUtils; import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.web.client.HttpClientErrorException; import com.fasterxml.jackson.core.JsonProcessingException; @@ -624,7 +625,17 @@ public class ExternalAccessRolesControllerTest { EcompUser user = new EcompUser(); user.setOrgUserId("guestT"); users.add(user); + StringWriter sw = new StringWriter(); + PrintWriter writer = new PrintWriter(sw); + Mockito.when(mockedResponse.getWriter()).thenReturn(writer); + List<EPApp> applicationList = new ArrayList<EPApp>(); + EPApp app = mockApp(); + app.setCentralAuth(true); + applicationList.add(app); + Mockito.when(externalAccessRolesService.getApp(mockedRequest.getHeader(uebKey))).thenReturn(applicationList); Mockito.when(externalAccessRolesService.getAllAppUsers(mockedRequest.getHeader(uebKey))).thenReturn(users); + ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(app)).thenReturn(response); List<EcompUser> expectedUsers = externalAccessRolesController.getUsersOfApplication(mockedRequest, mockedResponse); assertEquals(expectedUsers, users); } diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/HealthCheckControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/HealthCheckControllerTest.java new file mode 100644 index 00000000..92c0b21e --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/HealthCheckControllerTest.java @@ -0,0 +1,76 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.portal.controller; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.framework.MockitoTestSuite; +import org.onap.portalapp.portal.utils.EcompPortalUtils; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(EcompPortalUtils.class) +public class HealthCheckControllerTest { + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @InjectMocks + HealthCheckController healthCheckController = new HealthCheckController(); + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + + @Test + public void healthCheckFailTest() { + PowerMockito.mockStatic(EcompPortalUtils.class); + healthCheckController.healthCheck(mockedRequest, mockedResponse); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/MicroserviceProxyControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/MicroserviceProxyControllerTest.java index 446c11c4..6f9ce496 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/MicroserviceProxyControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/MicroserviceProxyControllerTest.java @@ -37,6 +37,7 @@ */ package org.onap.portalapp.portal.controller; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import javax.servlet.http.HttpServletRequest; @@ -106,7 +107,7 @@ public class MicroserviceProxyControllerTest extends MockitoTestSuite { Mockito.when(microserviceProxyService.proxyToDestination(1, user, mockedRequest)) .thenThrow(httpClientErrorException); String acutualString = microserviceProxyController.getMicroserviceProxy(mockedRequest, getMockedResponse(), 1); - assertTrue(acutualString.equals("{\"error\":\"\"}")); + assertEquals("", acutualString); } @Test @@ -138,6 +139,6 @@ public class MicroserviceProxyControllerTest extends MockitoTestSuite { .thenThrow(httpClientErrorException); String acutualString = microserviceProxyController.getMicroserviceProxyByWidgetId(mockedRequest, getMockedResponse(), 1); - assertTrue(acutualString.equals("{\"error\":\"\"}")); - } + assertEquals("", acutualString); + } } diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/RoleManageControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/RoleManageControllerTest.java index e63ea438..d7f64c1d 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/RoleManageControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/RoleManageControllerTest.java @@ -38,9 +38,15 @@ package org.onap.portalapp.portal.controller; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.IOException; import java.io.PrintWriter; +import java.io.StringReader; import java.io.StringWriter; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -51,8 +57,10 @@ import java.util.TreeSet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.json.simple.JSONObject; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Matchers; import org.mockito.Mock; @@ -63,6 +71,7 @@ import org.onap.portalapp.controller.core.RoleFunctionListController; import org.onap.portalapp.controller.core.RoleListController; import org.onap.portalapp.portal.core.MockEPUser; import org.onap.portalapp.portal.domain.CentralV2RoleFunction; +import org.onap.portalapp.portal.domain.CentralizedApp; import org.onap.portalapp.portal.domain.EPApp; import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.ecomp.model.PortalRestResponse; @@ -73,44 +82,54 @@ import org.onap.portalapp.portal.service.EPAppService; import org.onap.portalapp.portal.service.ExternalAccessRolesService; import org.onap.portalapp.portal.transport.CentralV2Role; import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator; +import org.onap.portalapp.portal.utils.EcompPortalUtils; import org.onap.portalapp.util.EPUserUtils; +import org.onap.portalsdk.core.domain.Role; import org.onap.portalsdk.core.service.AuditService; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.mock.web.DelegatingServletInputStream; import org.springframework.web.servlet.ModelAndView; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ EPUserUtils.class, EcompPortalUtils.class }) public class RoleManageControllerTest { @Mock - RoleController roleController; + RoleController roleController; @Mock - RoleListController roleListController; + RoleListController roleListController; @Mock - RoleFunctionListController roleFunctionListController; - + RoleFunctionListController roleFunctionListController; @Mock ExternalAccessRolesService externalAccessRolesService; @Mock EPUserUtils ePUserUtils = new EPUserUtils(); - + @Mock ExternalAccessRolesService externalAccessRolesService1 = null; - + @InjectMocks - RoleManageController roleManageController = new RoleManageController(); - + RoleManageController roleManageController = new RoleManageController(); + @Mock EPAppService appService; @Mock AuditService auditService; - + @Mock AdminRolesService adminRolesService; - + @Before public void setup() { MockitoAnnotations.initMocks(this); @@ -122,41 +141,46 @@ public class RoleManageControllerTest { HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); NullPointerException nullPointerException = new NullPointerException(); MockEPUser mockUser = new MockEPUser(); - - + @Test - public void removeRoleRoleFunctionTest() throws Exception - { - + public void removeRoleRoleFunctionTest() throws Exception { + ModelAndView modelandView = new ModelAndView("login.htm"); Mockito.when(roleController.removeRoleFunction(mockedRequest, mockedResponse)).thenReturn(modelandView); - ModelAndView expectedModelandView = roleManageController.removeRoleRoleFunction(mockedRequest, mockedResponse); + ModelAndView expectedModelandView = roleManageController.removeRoleRoleFunction(mockedRequest, mockedResponse); assertEquals(expectedModelandView, modelandView); } - + @Test - public void addRoleRoRoleFunctionTest() throws Exception - { + public void addRoleRoRoleFunctionTest() throws Exception { ModelAndView modelandView = new ModelAndView("login.htm"); Mockito.when(roleController.addRoleFunction(mockedRequest, mockedResponse)).thenReturn(modelandView); - ModelAndView expectedModelandView = roleManageController.addRoleRoRoleFunction(mockedRequest, mockedResponse); + ModelAndView expectedModelandView = roleManageController.addRoleRoRoleFunction(mockedRequest, mockedResponse); assertEquals(expectedModelandView, modelandView); } - + @Test - public void removeChildRoleTest() throws Exception - { + public void removeChildRoleTest() throws Exception { ModelAndView modelandView = new ModelAndView("login.htm"); Mockito.when(roleController.removeChildRole(mockedRequest, mockedResponse)).thenReturn(modelandView); - ModelAndView expectedModelandView = roleManageController.removeChildRole(mockedRequest, mockedResponse); + ModelAndView expectedModelandView = roleManageController.removeChildRole(mockedRequest, mockedResponse); assertEquals(expectedModelandView, modelandView); } - - + @Test - public void getRoleIfRoleIdNullTest() throws Exception - { + public void getRoleIfRoleIdNullTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); + Mockito.when(adminRolesService.isAccountAdminOfApplication(user, CentralApp())).thenReturn(true); + List<EPApp> apps = new ArrayList<>(); + apps.add(CentralApp()); + Mockito.when(externalAccessRolesService.getApp(CentralApp().getUebKey())).thenReturn(apps); + ResponseEntity<String> result = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(apps.get(0))).thenReturn(result); CentralV2Role answer = new CentralV2Role(); Mockito.when(externalAccessRolesService.getRoleInfo((long) 1, "test")).thenReturn(answer); List<CentralV2RoleFunction> finalRoleFunctionList = new ArrayList<>(); @@ -164,29 +188,27 @@ public class RoleManageControllerTest { Mockito.when(externalAccessRolesService.getRolesForApp("test")).thenReturn(null); StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); - Mockito.when(mockedResponse.getWriter()).thenReturn(writer); + Mockito.when(mockedResponse.getWriter()).thenReturn(writer); List<EPApp> appList = new ArrayList<>(); appList.add(CentralApp()); ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); - Mockito.when( externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); - roleManageController.getRole(mockedRequest, mockedResponse, (long)1,null); - -} - + roleManageController.getRole(mockedRequest, mockedResponse, (long) 1, null); + } + @Test(expected = Exception.class) - public void getRoleExceptionTest() throws Exception - { + public void getRoleExceptionTest() throws Exception { Mockito.when(appService.getApp((long) 1)).thenReturn(mockApp()); CentralV2Role answer = new CentralV2Role(); Mockito.when(externalAccessRolesService.getRoleInfo((long) 1, "test")).thenReturn(answer); Mockito.when(externalAccessRolesService.getRoleFuncList("test")).thenThrow(nullPointerException); - roleManageController.getRole(mockedRequest, mockedResponse, (long)1,null); - -} + roleManageController.getRole(mockedRequest, mockedResponse, (long) 1, null); + + } + @Test - public void getRoleIfRoleIdNotNullTest() throws Exception - { + public void getRoleIfRoleIdNotNullTest() throws Exception { Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); CentralV2Role answer = new CentralV2Role(); Mockito.when(externalAccessRolesService.getRoleInfo((long) 1, "test")).thenReturn(answer); @@ -194,11 +216,11 @@ public class RoleManageControllerTest { Mockito.when(externalAccessRolesService.getRoleFuncList("test")).thenReturn(finalRoleFunctionList); StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); - Mockito.when(mockedResponse.getWriter()).thenReturn(writer); + Mockito.when(mockedResponse.getWriter()).thenReturn(writer); CentralV2Role currentRole = new CentralV2Role(); - SortedSet<CentralV2Role> parentRoles = new TreeSet<>(); + SortedSet<CentralV2Role> parentRoles = new TreeSet<>(); CentralV2Role centralV2Role = new CentralV2Role(); - centralV2Role.setName("test"); + centralV2Role.setName("test"); parentRoles.add(centralV2Role); currentRole.setParentRoles(parentRoles); Mockito.when(externalAccessRolesService.getRoleInfo((long) 1, "test")).thenReturn(currentRole); @@ -208,13 +230,12 @@ public class RoleManageControllerTest { List<EPApp> appList = new ArrayList<>(); appList.add(CentralApp()); ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); - Mockito.when( externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); - roleManageController.getRole(mockedRequest, mockedResponse, (long)1,(long)1); -} - - public EPApp mockApp() - { + roleManageController.getRole(mockedRequest, mockedResponse, (long) 1, (long) 1); + } + + public EPApp mockApp() { EPApp app = new EPApp(); app.setName("Test"); @@ -237,12 +258,20 @@ public class RoleManageControllerTest { app.setUebTopicName("test"); app.setAppType(1); return app; - + } + @Test public void getRolesTest() throws Exception { EPApp app = mockApp(); app.setCentralAuth(true); + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + Mockito.when(appService.getApp((long) 1)).thenReturn(app); + Mockito.when(adminRolesService.isAccountAdminOfApplication(user, app)).thenReturn(true); List<CentralV2Role> answer = new ArrayList<>(); Mockito.when(appService.getApp((long) 1)).thenReturn(app); Mockito.when(externalAccessRolesService.getRolesForApp("test")).thenReturn(answer); @@ -252,7 +281,7 @@ public class RoleManageControllerTest { List<EPApp> appList = new ArrayList<>(); appList.add(CentralApp()); ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); - Mockito.when( externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); roleManageController.getRoles(mockedRequest, mockedResponse, (long) 1); } @@ -268,6 +297,12 @@ public class RoleManageControllerTest { @Test public void getRoleFunctionListTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + Mockito.when(adminRolesService.isAccountAdminOfApplication(user, CentralApp())).thenReturn(true); Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); List<CentralV2RoleFunction> answer = new ArrayList<>(); Mockito.when(externalAccessRolesService.getRoleFuncList("test")).thenReturn(answer); @@ -277,7 +312,7 @@ public class RoleManageControllerTest { List<EPApp> appList = new ArrayList<>(); appList.add(CentralApp()); ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); - Mockito.when( externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); roleManageController.getRoleFunctionList(mockedRequest, mockedResponse, (long) 1); } @@ -290,16 +325,27 @@ public class RoleManageControllerTest { @Test public void saveRoleFunctionTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + Mockito.when(adminRolesService.isAccountAdminOfApplication(user, CentralApp())).thenReturn(true); Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); Mockito.doNothing().when(roleFunctionListController).saveRoleFunction(mockedRequest, mockedResponse, "test"); CentralV2RoleFunction addNewFunc = new CentralV2RoleFunction(); addNewFunc.setCode("Test"); + addNewFunc.setType("Test"); + addNewFunc.setAction("Test"); addNewFunc.setName("Test"); CentralV2RoleFunction roleFunction = mockCentralRoleFunction(); - Mockito.when(externalAccessRolesService.getRoleFunction("Test", "test")).thenReturn(roleFunction); + roleFunction.setCode("Test|Test|Test"); + Mockito.when(externalAccessRolesService.getRoleFunction("Test|Test|Test", "test")).thenReturn(roleFunction); Mockito.when(externalAccessRolesService.saveCentralRoleFunction(Matchers.anyObject(), Matchers.anyObject())) .thenReturn(true); - EPUser user = mockUser.mockEPUser(); + Mockito.when(EcompPortalUtils.getFunctionCode(roleFunction.getCode())).thenReturn("Test"); + Mockito.when(EcompPortalUtils.getFunctionType(roleFunction.getCode())).thenReturn("Test"); + Mockito.when(EcompPortalUtils.getFunctionAction(roleFunction.getCode())).thenReturn("Test"); Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); List<EPUser> userList = new ArrayList<>(); userList.add(user); @@ -310,9 +356,13 @@ public class RoleManageControllerTest { PrintWriter writer = new PrintWriter(sw); Mockito.when(mockedResponse.getWriter()).thenReturn(writer); ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); - Mockito.when( externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); - roleManageController.saveRoleFunction(mockedRequest, mockedResponse, addNewFunc, (long) 1); + PortalRestResponse<String> actual = roleManageController.saveRoleFunction(mockedRequest, mockedResponse, + addNewFunc, (long) 1); + PortalRestResponse<String> expected = new PortalRestResponse<String>(PortalRestStatusEnum.OK, + "Saved Successfully!", "Success"); + assertEquals(expected, actual); } @Test @@ -332,18 +382,22 @@ public class RoleManageControllerTest { addNewFunc.setCode("Test"); addNewFunc.setName("Test"); Mockito.when(appService.getApp((long) 1)).thenReturn(NonCentralApp()); - String roleFun = "{\"name\":\"Test\",\"code\":\"Test\"}"; roleManageController.saveRoleFunction(mockedRequest, mockedResponse, addNewFunc, (long) 1); } @Test public void removeRoleFunctionTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); EPUser user = mockUser.mockEPUser(); Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + Mockito.when(adminRolesService.isAccountAdminOfApplication(user, CentralApp())).thenReturn(true); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); - String roleFun = "{\"name\":\"Test\",\"code\":\"Test\"}"; + String roleFun = "{\"name\":\"Test\",\"type\":\"Test\",\"action\":\"Test\", \"code\":\"Test\"}"; CentralV2RoleFunction roleFunction = mockCentralRoleFunction(); - Mockito.when(externalAccessRolesService.getRoleFunction("Test", "test")).thenReturn(roleFunction); + Mockito.when(externalAccessRolesService.getRoleFunction("Test|Test|Test", "test")).thenReturn(roleFunction); StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); Mockito.when(mockedResponse.getWriter()).thenReturn(writer); @@ -352,9 +406,13 @@ public class RoleManageControllerTest { List<EPApp> appList = new ArrayList<>(); appList.add(CentralApp()); ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); - Mockito.when( externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); - roleManageController.removeRoleFunction(mockedRequest, mockedResponse, roleFun, (long) 1); + PortalRestResponse<String> actual = roleManageController.removeRoleFunction(mockedRequest, mockedResponse, + roleFun, (long) 1); + PortalRestResponse<String> expected = new PortalRestResponse<String>(PortalRestStatusEnum.OK, + "Deleted Successfully!", "Success"); + assertEquals(expected, actual); } @Test @@ -373,7 +431,7 @@ public class RoleManageControllerTest { List<EPApp> appList = new ArrayList<>(); appList.add(CentralApp()); ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); - Mockito.when( externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); roleManageController.removeRoleFunction(mockedRequest, mockedResponse, roleFun, (long) 1); } @@ -389,9 +447,12 @@ public class RoleManageControllerTest { @Test public void syncRolesTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + EPUser user = mockUser.mockEPUser(); EPApp app = mockApp(); app.setId((long) 1); - EPUser user = mockUser.mockEPUser(); Mockito.when(appService.getApp(1l)).thenReturn(app); Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); Mockito.when(adminRolesService.isSuperAdmin(Matchers.anyObject())).thenReturn(true); @@ -399,7 +460,7 @@ public class RoleManageControllerTest { List<EPApp> appList = new ArrayList<>(); appList.add(CentralApp()); ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); - Mockito.when( externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); PortalRestResponse<String> actual = roleManageController.syncRoles(mockedRequest, mockedResponse, 1l); PortalRestResponse<String> portalRestResponse = new PortalRestResponse<>(); @@ -419,9 +480,12 @@ public class RoleManageControllerTest { portalRestResponse.setStatus(PortalRestStatusEnum.ERROR); assertEquals(portalRestResponse, actual); } - + @Test public void syncRolesFunctionsTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); EPApp app = mockApp(); app.setId((long) 1); EPUser user = mockUser.mockEPUser(); @@ -432,7 +496,7 @@ public class RoleManageControllerTest { List<EPApp> appList = new ArrayList<>(); appList.add(CentralApp()); ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); - Mockito.when( externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); PortalRestResponse<String> actual = roleManageController.syncFunctions(mockedRequest, mockedResponse, 1l); PortalRestResponse<String> portalRestResponse = new PortalRestResponse<>(); @@ -452,18 +516,20 @@ public class RoleManageControllerTest { portalRestResponse.setStatus(PortalRestStatusEnum.ERROR); assertEquals(portalRestResponse, actual); } - + @Test - public void addeChildRoleTest() throws Exception - { + public void addChildRoleTest() throws Exception { ModelAndView modelandView = new ModelAndView("login.htm"); Mockito.when(roleController.addChildRole(mockedRequest, mockedResponse)).thenReturn(modelandView); - ModelAndView expectedModelandView = roleManageController.addChildRole(mockedRequest, mockedResponse); + ModelAndView expectedModelandView = roleManageController.addChildRole(mockedRequest, mockedResponse); assertEquals(expectedModelandView, modelandView); } - + @Test public void removeRoleTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); List<EPUser> epuserList = new ArrayList<>(); List<EPApp> appList = new ArrayList<>(); appList.add(CentralApp()); @@ -471,6 +537,7 @@ public class RoleManageControllerTest { epuserList.add(user); Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); + Mockito.when(adminRolesService.isSuperAdmin(Matchers.anyObject())).thenReturn(true); StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); Mockito.when(mockedResponse.getWriter()).thenReturn(writer); @@ -480,14 +547,16 @@ public class RoleManageControllerTest { Mockito.when(externalAccessRolesService.getUser(Matchers.anyString())).thenReturn(epuserList); Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); - Mockito.when( externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); Map<String, Object> expedtedResponse = new HashMap<String, Object>(); expedtedResponse.put("restCallStatus", " Unauthorized user"); - Map<String, Object> actualResponse = roleManageController.removeRole(mockedRequest, mockedResponse, (long) 1, (long) 1); + expedtedResponse.put("availableRoles", new ArrayList<>()); + Map<String, Object> actualResponse = roleManageController.removeRole(mockedRequest, mockedResponse, (long) 1, + (long) 1); assertEquals(actualResponse.size(), expedtedResponse.size()); } - + @Test(expected = Exception.class) public void removeRoleExceptionTest() throws Exception { EPUser user = mockUser.mockEPUser(); @@ -498,28 +567,344 @@ public class RoleManageControllerTest { Mockito.when(mockedResponse.getWriter()).thenReturn(writer); roleManageController.removeRole(mockedRequest, mockedResponse, (long) 1, (long) 1); } + + @SuppressWarnings("unchecked") + @Test + public void saveRoleNewTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + List<EPUser> epuserList = new ArrayList<>(); + List<EPApp> appList = new ArrayList<>(); + appList.add(CentralApp()); + EPUser user = mockUser.mockEPUser(); + epuserList.add(user); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); + Mockito.when(adminRolesService.isSuperAdmin(Matchers.anyObject())).thenReturn(true); + Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); + ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + JSONObject roleJson = new JSONObject(); + roleJson.put("name", "test"); + JSONObject roleJson2 = new JSONObject(); + List<JSONObject> childRolesJson = new ArrayList<>(); + List<JSONObject> roleFunctions = new ArrayList<>(); + roleJson2.put("role", roleJson); + roleJson2.put("childRoles", childRolesJson); + roleJson2.put("roleFunctions", roleFunctions); + ObjectMapper mapper = new ObjectMapper(); + JsonNode actualObj = mapper.readTree(roleJson2.toString()); + Mockito.when(mockedRequest.getInputStream()).thenReturn(new DelegatingServletInputStream( + new ByteArrayInputStream(actualObj.toString().getBytes(StandardCharsets.UTF_8)))); + Mockito.when(mockedRequest.getReader()).thenReturn(new BufferedReader(new StringReader(actualObj.toString()))); + Mockito.when(mockedRequest.getContentType()).thenReturn("application/json"); + Mockito.when(mockedRequest.getCharacterEncoding()).thenReturn("UTF-8"); + Mockito.when(externalAccessRolesService.ConvertCentralRoleToRole(Matchers.anyString())).thenReturn(new Role()); + ExternalRequestFieldsValidator externalRequestFieldsValidator = new ExternalRequestFieldsValidator(true, ""); + Mockito.when(externalAccessRolesService.saveRoleForApplication(Matchers.any(), Matchers.any())) + .thenReturn(externalRequestFieldsValidator); + Map<String, Object> actual = roleManageController.saveRole(mockedRequest, mockedResponse, CentralApp().getId()); + final Map<String, Object> expected = new HashMap<>(); + expected.put("role", new CentralV2Role(null, "test")); + expected.put("status", "Success"); + assertEquals(expected, actual); + } + + @SuppressWarnings("unchecked") + @Test + public void saveRoleUpdateTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + List<EPUser> epuserList = new ArrayList<>(); + List<EPApp> appList = new ArrayList<>(); + appList.add(CentralApp()); + EPUser user = mockUser.mockEPUser(); + epuserList.add(user); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); + Mockito.when(adminRolesService.isSuperAdmin(Matchers.anyObject())).thenReturn(true); + Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); + ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + JSONObject roleJson = new JSONObject(); + roleJson.put("id", 1); + roleJson.put("name", "test"); + roleJson.put("active", true); + JSONObject roleJson2 = new JSONObject(); + List<JSONObject> childRolesJson = new ArrayList<>(); + List<JSONObject> roleFunctions = new ArrayList<>(); + JSONObject roleFunction = new JSONObject(); + roleFunction.put("code", "test"); + roleFunction.put("name", "test"); + roleFunction.put("type", "test"); + roleFunction.put("action", "test"); + roleFunctions.add(roleFunction); + roleJson.put("roleFunctions", roleFunctions); + roleJson2.put("role", roleJson); + roleJson2.put("childRoles", childRolesJson); + roleJson2.put("roleFunctions", roleFunctions); + ObjectMapper mapper = new ObjectMapper(); + JsonNode actualObj = mapper.readTree(roleJson2.toString()); + Mockito.when(mockedRequest.getInputStream()).thenReturn(new DelegatingServletInputStream( + new ByteArrayInputStream(actualObj.toString().getBytes(StandardCharsets.UTF_8)))); + Mockito.when(mockedRequest.getReader()).thenReturn(new BufferedReader(new StringReader(actualObj.toString()))); + Mockito.when(mockedRequest.getContentType()).thenReturn("application/json"); + Mockito.when(mockedRequest.getCharacterEncoding()).thenReturn("UTF-8"); + Mockito.when(externalAccessRolesService.ConvertCentralRoleToRole(Matchers.anyString())).thenReturn(new Role()); + ExternalRequestFieldsValidator externalRequestFieldsValidator = new ExternalRequestFieldsValidator(true, ""); + Mockito.when(externalAccessRolesService.saveRoleForApplication(Matchers.any(), Matchers.any())) + .thenReturn(externalRequestFieldsValidator); + CentralV2Role cenV2Role = new CentralV2Role(1l, "test1"); + cenV2Role.setActive(true); + Mockito.when(externalAccessRolesService.getRoleInfo(Matchers.anyLong(), Matchers.any())).thenReturn(cenV2Role); + Map<String, Object> actual = roleManageController.saveRole(mockedRequest, mockedResponse, CentralApp().getId()); + final Map<String, Object> expected = new HashMap<>(); + expected.put("status", "Success"); + assertEquals(expected.get("status"), actual.get("status")); + } - public CentralV2RoleFunction mockCentralRoleFunction() - { + @SuppressWarnings("unchecked") + @Test + public void saveRoleInvalidRoleExceptionTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + List<EPUser> epuserList = new ArrayList<>(); + List<EPApp> appList = new ArrayList<>(); + appList.add(CentralApp()); + EPUser user = mockUser.mockEPUser(); + epuserList.add(user); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); + Mockito.when(adminRolesService.isSuperAdmin(Matchers.anyObject())).thenReturn(true); + Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); + ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + JSONObject roleJson = new JSONObject(); + roleJson.put("id", 1); + roleJson.put("name", "test%%"); + roleJson.put("active", true); + JSONObject roleJson2 = new JSONObject(); + List<JSONObject> childRolesJson = new ArrayList<>(); + List<JSONObject> roleFunctions = new ArrayList<>(); + JSONObject roleFunction = new JSONObject(); + roleFunction.put("code", "test"); + roleFunction.put("name", "test"); + roleFunction.put("type", "test"); + roleFunction.put("action", "test"); + roleFunctions.add(roleFunction); + roleJson.put("roleFunctions", roleFunctions); + roleJson2.put("role", roleJson); + roleJson2.put("childRoles", childRolesJson); + roleJson2.put("roleFunctions", roleFunctions); + ObjectMapper mapper = new ObjectMapper(); + JsonNode actualObj = mapper.readTree(roleJson2.toString()); + Mockito.when(mockedRequest.getInputStream()).thenReturn(new DelegatingServletInputStream( + new ByteArrayInputStream(actualObj.toString().getBytes(StandardCharsets.UTF_8)))); + Mockito.when(mockedRequest.getReader()).thenReturn(new BufferedReader(new StringReader(actualObj.toString()))); + Mockito.when(mockedRequest.getContentType()).thenReturn("application/json"); + Mockito.when(mockedRequest.getCharacterEncoding()).thenReturn("UTF-8"); + Map<String, Object> actual = roleManageController.saveRole(mockedRequest, mockedResponse, CentralApp().getId()); + final Map<String, Object> expected = new HashMap<>(); + expected.put("error", "Invalid role name found for 'test%%'. Any one of the following characters '%,(),=,:,comma, and double quotes' are not allowed"); + assertEquals(expected.get("error"), actual.get("error")); + } + + @Test + public void saveRoleUnauthorizedUserExceptionTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + List<EPUser> epuserList = new ArrayList<>(); + List<EPApp> appList = new ArrayList<>(); + appList.add(CentralApp()); + EPUser user = mockUser.mockEPUser(); + epuserList.add(user); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); + Mockito.when(adminRolesService.isSuperAdmin(Matchers.anyObject())).thenReturn(false); + Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); + ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + Map<String, Object> actual = roleManageController.saveRole(mockedRequest, mockedResponse, CentralApp().getId()); + final Map<String, Object> expected = new HashMap<>(); + expected.put("error", " Unauthorized user"); + assertEquals(expected.get("error"), actual.get("error")); + } + + @Test + public void toggleRoleTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + List<EPUser> epuserList = new ArrayList<>(); + List<EPApp> appList = new ArrayList<>(); + appList.add(CentralApp()); + EPUser user = mockUser.mockEPUser(); + epuserList.add(user); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); + Mockito.when(adminRolesService.isSuperAdmin(Matchers.anyObject())).thenReturn(true); + Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); + ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + CentralV2Role role = new CentralV2Role(1l, "test"); + role.setActive(true); + Role currentRole = new Role(); + currentRole.setName("test"); + Mockito.when(externalAccessRolesService.getRoleInfo(Matchers.anyLong(), Matchers.any())).thenReturn(role); + Mockito.when(externalAccessRolesService.ConvertCentralRoleToRole(Matchers.anyString())).thenReturn(currentRole); + ExternalRequestFieldsValidator externalRequestFieldsValidator = new ExternalRequestFieldsValidator(true, ""); + Mockito.when(externalAccessRolesService.saveRoleForApplication(Matchers.any(),Matchers.any())).thenReturn(externalRequestFieldsValidator); + Map<String, Object> actual = roleManageController.toggleRole(mockedRequest, mockedResponse, CentralApp().getId(), 1l); + final Map<String, Object> expected = new HashMap<>(); + expected.put("restcallStatus", "Success"); + assertEquals(expected.get("restcallStatus"), actual.get("restcallStatus")); + } + + @Test + public void toggleRoleUnauthorizedUserExceptionTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + List<EPUser> epuserList = new ArrayList<>(); + List<EPApp> appList = new ArrayList<>(); + appList.add(CentralApp()); + EPUser user = mockUser.mockEPUser(); + epuserList.add(user); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); + Mockito.when(adminRolesService.isSuperAdmin(Matchers.anyObject())).thenReturn(false); + Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); + ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + Map<String, Object> actual = roleManageController.toggleRole(mockedRequest, mockedResponse, CentralApp().getId(), 1l); + final Map<String, Object> expected = new HashMap<>(); + expected.put("restcallStatus", " Unauthorized user"); + assertEquals(expected.get("restcallStatus"), actual.get("restcallStatus")); + } + + @Test(expected = NullPointerException.class) + public void toggleRoleExceptionTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + List<EPUser> epuserList = new ArrayList<>(); + List<EPApp> appList = new ArrayList<>(); + appList.add(CentralApp()); + EPUser user = mockUser.mockEPUser(); + epuserList.add(user); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.doThrow(new NullPointerException()).when(appService).getApp((long) 1); + roleManageController.toggleRole(mockedRequest, mockedResponse, CentralApp().getId(), 1l); + } + + @Test + public void toggleRoleFailedTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + List<EPUser> epuserList = new ArrayList<>(); + List<EPApp> appList = new ArrayList<>(); + appList.add(CentralApp()); + EPUser user = mockUser.mockEPUser(); + epuserList.add(user); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); + Mockito.when(adminRolesService.isSuperAdmin(Matchers.anyObject())).thenReturn(true); + Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); + ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + CentralV2Role role = new CentralV2Role(1l, "test"); + role.setActive(true); + Role currentRole = new Role(); + currentRole.setName("test"); + Mockito.when(externalAccessRolesService.getRoleInfo(Matchers.anyLong(), Matchers.any())).thenReturn(role); + Mockito.when(externalAccessRolesService.ConvertCentralRoleToRole(Matchers.anyString())).thenReturn(currentRole); + ExternalRequestFieldsValidator externalRequestFieldsValidator = new ExternalRequestFieldsValidator(false, ""); + Mockito.when(externalAccessRolesService.saveRoleForApplication(Matchers.any(),Matchers.any())).thenReturn(externalRequestFieldsValidator); + Map<String, Object> actual = roleManageController.toggleRole(mockedRequest, mockedResponse, CentralApp().getId(), 1l); + final Map<String, Object> expected = new HashMap<>(); + expected.put("restcallStatus", "Toggle Role Failed"); + assertEquals(expected.get("restcallStatus"), actual.get("restcallStatus")); + } + + @Test + public void getAvailableChildRolesTest() throws Exception { + List<CentralV2Role> centralV2Roles = new ArrayList<>(); + CentralV2Role centralV2Role = new CentralV2Role(); + centralV2Role.setName("test"); + centralV2Role.setId(1l); + CentralV2Role centralV2Role2 = new CentralV2Role(); + centralV2Role2.setName("test"); + centralV2Role2.setId(1l); + centralV2Roles.add(centralV2Role); + centralV2Roles.add(centralV2Role2); + SortedSet<CentralV2RoleFunction> roleFuns = new TreeSet<>(); + CentralV2RoleFunction centralV2RoleFunction = new CentralV2RoleFunction("test", "test"); + roleFuns.add(centralV2RoleFunction); + CentralV2Role currentRole = new CentralV2Role(); + currentRole.setName("test"); + currentRole.setId(1l); + currentRole.setRoleFunctions(roleFuns); + Mockito.when(externalAccessRolesService.getRolesForApp(CentralApp().getUebKey())).thenReturn(centralV2Roles); + Mockito.when(externalAccessRolesService.getRoleInfo(1l, CentralApp().getUebKey())).thenReturn(currentRole); + List<CentralV2Role> actual = roleManageController.getAvailableChildRoles(CentralApp().getUebKey(), 1l); + assertEquals(new ArrayList<>().size(), actual.size()); + } + + @Test + public void getCentralizedAppRolesTest() throws IOException { + PowerMockito.mockStatic(EPUserUtils.class); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + List<CentralizedApp> cenApps = new ArrayList<>(); + CentralizedApp centralizedApp = new CentralizedApp(); + centralizedApp.setAppId(1); + centralizedApp.setAppName("Test"); + cenApps.add(centralizedApp); + Mockito.when(adminRolesService.isSuperAdmin(Matchers.anyObject())).thenReturn(true); + Mockito.when(externalAccessRolesService.getCentralizedAppsOfUser(Matchers.anyString())).thenReturn(cenApps); + List<CentralizedApp> actual = roleManageController.getCentralizedAppRoles(mockedRequest, mockedResponse, user.getOrgUserId()); + assertEquals(cenApps.size(), actual.size()); + } + + @Test + public void getCentralizedAppRolesExceptionTest() throws IOException { + PowerMockito.mockStatic(EPUserUtils.class); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + List<CentralizedApp> cenApps = new ArrayList<>(); + CentralizedApp centralizedApp = new CentralizedApp(); + centralizedApp.setAppId(1); + centralizedApp.setAppName("Test"); + cenApps.add(centralizedApp); + Mockito.when(adminRolesService.isAccountAdmin(Matchers.anyObject())).thenReturn(false); + List<CentralizedApp> actual = roleManageController.getCentralizedAppRoles(mockedRequest, mockedResponse, user.getOrgUserId()); + assertNull(actual); + } + + public CentralV2RoleFunction mockCentralRoleFunction() { CentralV2RoleFunction roleFunction = new CentralV2RoleFunction(); roleFunction.setCode("Test"); roleFunction.setName("Test"); roleFunction.setAppId((long) 1); return roleFunction; } - - public EPApp CentralApp() - { - EPApp app = mockApp(); + + public EPApp CentralApp() { + EPApp app = mockApp(); app.setCentralAuth(true); app.setNameSpace("com.test"); return app; } - - public EPApp NonCentralApp() - { - EPApp app = mockApp(); + + public EPApp NonCentralApp() { + EPApp app = mockApp(); app.setCentralAuth(false); return app; } + } diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/UserControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/UserControllerTest.java index 205b2355..84db1496 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/UserControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/UserControllerTest.java @@ -135,7 +135,7 @@ public class UserControllerTest extends MockitoTestSuite { @Test public void modifyLoggedinUserExceptionTest() { - EPUser epUser = null; + EPUser epUser =null; PortalRestResponse<String> expectedResponse = new PortalRestResponse<String>(); expectedResponse.setMessage("java.lang.NullPointerException"); expectedResponse.setResponse(null); diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/WidgetsCatalogControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/WidgetsCatalogControllerTest.java index 50291f07..d8aba5fc 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/WidgetsCatalogControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/WidgetsCatalogControllerTest.java @@ -37,6 +37,9 @@ */ package org.onap.portalapp.portal.controller; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + import java.util.ArrayList; import java.util.List; @@ -44,17 +47,23 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; +import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.onap.portalapp.portal.controller.WidgetsCatalogController; import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.domain.MicroserviceParameter; import org.onap.portalapp.portal.domain.WidgetCatalog; +import org.onap.portalapp.portal.domain.WidgetCatalogParameter; +import org.onap.portalapp.portal.domain.WidgetParameterResult; import org.onap.portalapp.portal.domain.WidgetServiceHeaders; +import org.onap.portalapp.portal.ecomp.model.PortalRestResponse; +import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum; import org.onap.portalapp.portal.framework.MockitoTestSuite; import org.onap.portalapp.portal.service.ConsulHealthService; import org.onap.portalapp.portal.service.ConsulHealthServiceImpl; @@ -65,29 +74,38 @@ import org.onap.portalapp.portal.service.WidgetParameterServiceImpl; import org.onap.portalapp.portal.utils.EPCommonSystemProperties; import org.onap.portalapp.portal.utils.EcompPortalUtils; import org.onap.portalapp.util.EPUserUtils; +import org.onap.portalsdk.core.onboarding.exception.CipherUtilException; +import org.onap.portalsdk.core.onboarding.util.CipherUtil; import org.onap.portalsdk.core.util.SystemProperties; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.mock.web.MockMultipartHttpServletRequest; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; - -@Ignore +@SuppressWarnings("rawtypes") @RunWith(PowerMockRunner.class) -@PrepareForTest({EPUserUtils.class, EcompPortalUtils.class, SystemProperties.class, EPCommonSystemProperties.class}) +@PrepareForTest({ EPUserUtils.class, CipherUtil.class, EcompPortalUtils.class, SystemProperties.class, + EPCommonSystemProperties.class, EPUserUtils.class }) public class WidgetsCatalogControllerTest { @Mock ConsulHealthService consulHealthService = new ConsulHealthServiceImpl(); - + @Mock MicroserviceService microserviceService = new MicroserviceServiceImpl(); - + @Mock WidgetParameterService widgetParameterService = new WidgetParameterServiceImpl(); - + @InjectMocks WidgetsCatalogController widgetsCatalogController = new WidgetsCatalogController(); @@ -95,10 +113,10 @@ public class WidgetsCatalogControllerTest { public void setup() { MockitoAnnotations.initMocks(this); } + @Mock - WidgetServiceHeaders widgetServiceHeaders ; - - + WidgetServiceHeaders widgetServiceHeaders; + @Mock RestTemplate template = new RestTemplate(); @@ -108,32 +126,380 @@ public class WidgetsCatalogControllerTest { HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); NullPointerException nullPointerException = new NullPointerException(); - + MockEPUser mockUser = new MockEPUser(); - - @Mock - HttpEntity mockHttpEntity; - + + @Test + public void getUserWidgetCatalogTest() throws RestClientException, Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(EcompPortalUtils.widgetMsProtocol()).thenReturn("test1"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WIDGET_MS_PROTOCOL)).thenReturn("https"); + Mockito.when(SystemProperties.getProperty("microservices.widget.local.port")).thenReturn("test"); + Mockito.when(EcompPortalUtils.getPropertyOrDefault("microservices.widget.username", "widget_user")) + .thenReturn("test"); + Mockito.when(CipherUtil + .decryptPKC(EcompPortalUtils.getPropertyOrDefault("microservices.widget.password", "widget_password"))) + .thenReturn("abc"); + List<WidgetCatalog> widgetsList = new ArrayList<>(); + WidgetCatalog widgetCatalog = new WidgetCatalog(); + widgetCatalog.setId(1l); + widgetCatalog.setName("test"); + widgetsList.add(widgetCatalog); + ResponseEntity<List> ans = new ResponseEntity<>(widgetsList, HttpStatus.OK); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), Matchers.<HttpEntity<?>>any(), + Matchers.eq(List.class))).thenReturn(ans); + List<WidgetCatalog> expectedWidgets = widgetsCatalogController.getUserWidgetCatalog("guestT"); + assertEquals(expectedWidgets, widgetsList); + } + + @Test + public void getUserWidgetCatalogExceptionTest() throws RestClientException, Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(EcompPortalUtils.widgetMsProtocol()).thenReturn("test1"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WIDGET_MS_PROTOCOL)).thenReturn("https"); + Mockito.when(SystemProperties.getProperty("microservices.widget.local.port")).thenReturn("test"); + Mockito.when(EcompPortalUtils.getPropertyOrDefault("microservices.widget.username", "widget_user")) + .thenReturn("test"); + Mockito.when(CipherUtil + .decryptPKC(EcompPortalUtils.getPropertyOrDefault("microservices.widget.password", "widget_password"))) + .thenReturn("abc"); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + Mockito.doThrow(new NullPointerException()).when(template).exchange(Matchers.anyString(), + Matchers.eq(HttpMethod.GET), Matchers.<HttpEntity<?>>any(), Matchers.eq(List.class)); + List<WidgetCatalog> expectedWidgets = widgetsCatalogController.getUserWidgetCatalog("guestT"); + assertNull(expectedWidgets); + } + + @Test + public void getWidgetCatalogTest() throws CipherUtilException { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(EcompPortalUtils.widgetMsProtocol()).thenReturn("test1"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WIDGET_MS_PROTOCOL)).thenReturn("https"); + Mockito.when(SystemProperties.getProperty("microservices.widget.local.port")).thenReturn("test"); + Mockito.when(EcompPortalUtils.getPropertyOrDefault("microservices.widget.username", "widget_user")) + .thenReturn("test"); + Mockito.when(CipherUtil + .decryptPKC(EcompPortalUtils.getPropertyOrDefault("microservices.widget.password", "widget_password"))) + .thenReturn("abc"); + List<WidgetCatalog> widgetsList = new ArrayList<>(); + WidgetCatalog widgetCatalog = new WidgetCatalog(); + widgetCatalog.setId(1l); + widgetCatalog.setName("test"); + widgetsList.add(widgetCatalog); + ResponseEntity<List> ans = new ResponseEntity<>(widgetsList, HttpStatus.OK); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), Matchers.<HttpEntity<?>>any(), + Matchers.eq(List.class))).thenReturn(ans); + List<WidgetCatalog> expectedWidgets = widgetsCatalogController.getWidgetCatalog(); + assertEquals(expectedWidgets, widgetsList); + } + + @Test + public void getWidgetCatalogExceptionTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(EcompPortalUtils.widgetMsProtocol()).thenReturn("test1"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WIDGET_MS_PROTOCOL)).thenReturn("https"); + Mockito.when(SystemProperties.getProperty("microservices.widget.local.port")).thenReturn("test"); + Mockito.when(EcompPortalUtils.getPropertyOrDefault("microservices.widget.username", "widget_user")) + .thenReturn("test"); + Mockito.when(CipherUtil + .decryptPKC(EcompPortalUtils.getPropertyOrDefault("microservices.widget.password", "widget_password"))) + .thenReturn("abc"); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + Mockito.doThrow(new NullPointerException()).when(template).exchange(Matchers.anyString(), + Matchers.eq(HttpMethod.GET), Matchers.<HttpEntity<?>>any(), Matchers.eq(List.class)); + List<WidgetCatalog> expectedWidgets = widgetsCatalogController.getUserWidgetCatalog("guestT"); + assertNull(expectedWidgets); + } + + @Test + public void updateWidgetCatalogTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(EcompPortalUtils.widgetMsProtocol()).thenReturn("test1"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WIDGET_MS_PROTOCOL)).thenReturn("https"); + Mockito.when(SystemProperties.getProperty("microservices.widget.local.port")).thenReturn("test"); + Mockito.when(EcompPortalUtils.getPropertyOrDefault("microservices.widget.username", "widget_user")) + .thenReturn("test"); + Mockito.when(CipherUtil + .decryptPKC(EcompPortalUtils.getPropertyOrDefault("microservices.widget.password", "widget_password"))) + .thenReturn("abc"); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + ResponseEntity<List> ans = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.PUT), Matchers.<HttpEntity<?>>any(), + Matchers.eq(List.class))).thenReturn(ans); + WidgetCatalog widget = new WidgetCatalog(); + widget.setId(1l); + widgetsCatalogController.updateWidgetCatalog(widget, 1); + } + + @Test + public void deleteOnboardingWidgetTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(EcompPortalUtils.widgetMsProtocol()).thenReturn("test1"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WIDGET_MS_PROTOCOL)).thenReturn("https"); + Mockito.when(SystemProperties.getProperty("microservices.widget.local.port")).thenReturn("test"); + Mockito.when(EcompPortalUtils.getPropertyOrDefault("microservices.widget.username", "widget_user")) + .thenReturn("test"); + Mockito.when(CipherUtil + .decryptPKC(EcompPortalUtils.getPropertyOrDefault("microservices.widget.password", "widget_password"))) + .thenReturn("abc"); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + ResponseEntity<List> ans = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<?>>any(), Matchers.eq(List.class))).thenReturn(ans); + widgetsCatalogController.deleteOnboardingWidget(1l); + } + + @SuppressWarnings("unchecked") + @Test + public void updateWidgetCatalogWithFilesTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(EcompPortalUtils.widgetMsProtocol()).thenReturn("test1"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WIDGET_MS_PROTOCOL)).thenReturn("https"); + Mockito.when(SystemProperties.getProperty("microservices.widget.local.port")).thenReturn("test"); + Mockito.when(EcompPortalUtils.getPropertyOrDefault("microservices.widget.username", "widget_user")) + .thenReturn("test"); + Mockito.when(CipherUtil + .decryptPKC(EcompPortalUtils.getPropertyOrDefault("microservices.widget.password", "widget_password"))) + .thenReturn("abc"); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + String ans = "success"; + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + Mockito.when(template.postForObject(Mockito.any(String.class), Mockito.any(HttpEntity.class), + Mockito.any(Class.class))).thenReturn(ans); + MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest(); + byte[] mockData = "test".getBytes(); + String originalFilename = "Test_File.zip"; + MockMultipartFile mockMultipartFile = new MockMultipartFile("file", originalFilename, "application/zip", + mockData); + request.addFile(mockMultipartFile); + String actual = widgetsCatalogController.updateWidgetCatalogWithFiles(request, 1l); + assertEquals(ans, actual); + } + + @SuppressWarnings("unchecked") + @Test + public void createWidgetCatalogTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(EcompPortalUtils.widgetMsProtocol()).thenReturn("test1"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WIDGET_MS_PROTOCOL)).thenReturn("https"); + Mockito.when(SystemProperties.getProperty("microservices.widget.local.port")).thenReturn("test"); + Mockito.when(EcompPortalUtils.getPropertyOrDefault("microservices.widget.username", "widget_user")) + .thenReturn("test"); + Mockito.when(CipherUtil + .decryptPKC(EcompPortalUtils.getPropertyOrDefault("microservices.widget.password", "widget_password"))) + .thenReturn("abc"); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + String ans = "success"; + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + Mockito.when(template.postForObject(Mockito.any(String.class), Mockito.any(HttpEntity.class), + Mockito.any(Class.class))).thenReturn(ans); + MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest(); + byte[] mockData = "test".getBytes(); + String originalFilename = "Test_File.zip"; + MockMultipartFile mockMultipartFile = new MockMultipartFile("file", originalFilename, "application/zip", + mockData); + request.addFile(mockMultipartFile); + String actual = widgetsCatalogController.createWidgetCatalog(request); + assertEquals(ans, actual); + } + + @SuppressWarnings("unchecked") + @Test + public void getWidgetFrameworkTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(EcompPortalUtils.widgetMsProtocol()).thenReturn("test1"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WIDGET_MS_PROTOCOL)).thenReturn("https"); + Mockito.when(SystemProperties.getProperty("microservices.widget.local.port")).thenReturn("test"); + Mockito.when(EcompPortalUtils.getPropertyOrDefault("microservices.widget.username", "widget_user")) + .thenReturn("test"); + Mockito.when(CipherUtil + .decryptPKC(EcompPortalUtils.getPropertyOrDefault("microservices.widget.password", "widget_password"))) + .thenReturn("abc"); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + Mockito.when(template.getForObject(Mockito.anyString(), Mockito.any(Class.class), Mockito.any(String.class))) + .thenReturn("test123"); + String result = widgetsCatalogController.getWidgetFramework(1l); + assertNull(result); + } + + @SuppressWarnings("unchecked") + @Test + public void getWidgetControllerTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(EcompPortalUtils.widgetMsProtocol()).thenReturn("test1"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WIDGET_MS_PROTOCOL)).thenReturn("https"); + Mockito.when(SystemProperties.getProperty("microservices.widget.local.port")).thenReturn("test"); + Mockito.when(EcompPortalUtils.getPropertyOrDefault("microservices.widget.username", "widget_user")) + .thenReturn("test"); + Mockito.when(CipherUtil + .decryptPKC(EcompPortalUtils.getPropertyOrDefault("microservices.widget.password", "widget_password"))) + .thenReturn("abc"); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + Mockito.when(template.getForObject(Mockito.anyString(), Mockito.any(Class.class), Mockito.any(String.class))) + .thenReturn("test123"); + String result = widgetsCatalogController.getWidgetController(1); + assertNull(result); + } + + @SuppressWarnings("unchecked") + @Test + public void getWidgetCSSTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(EcompPortalUtils.widgetMsProtocol()).thenReturn("test1"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WIDGET_MS_PROTOCOL)).thenReturn("https"); + Mockito.when(SystemProperties.getProperty("microservices.widget.local.port")).thenReturn("test"); + Mockito.when(EcompPortalUtils.getPropertyOrDefault("microservices.widget.username", "widget_user")) + .thenReturn("test"); + Mockito.when(CipherUtil + .decryptPKC(EcompPortalUtils.getPropertyOrDefault("microservices.widget.password", "widget_password"))) + .thenReturn("abc"); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + Mockito.when(template.getForObject(Mockito.anyString(), Mockito.any(Class.class), Mockito.any(String.class))) + .thenReturn("test123"); + String result = widgetsCatalogController.getWidgetCSS(1); + assertNull(result); + } + + @Test + public void getWidgetParameterResultTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + PowerMockito.mockStatic(EPUserUtils.class); + EPUser user = mockUser.mockEPUser(); + MockHttpServletRequest request = new MockHttpServletRequest(); + Mockito.when(EPUserUtils.getUserSession(request)).thenReturn(user); + Mockito.when(EcompPortalUtils.widgetMsProtocol()).thenReturn("test1"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WIDGET_MS_PROTOCOL)).thenReturn("https"); + Mockito.when(SystemProperties.getProperty("microservices.widget.local.port")).thenReturn("test"); + Mockito.when(EcompPortalUtils.getPropertyOrDefault("microservices.widget.username", "widget_user")) + .thenReturn("test"); + Mockito.when(CipherUtil + .decryptPKC(EcompPortalUtils.getPropertyOrDefault("microservices.widget.password", "widget_password"))) + .thenReturn("abc"); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + ResponseEntity<Long> ans = new ResponseEntity<>(1l, HttpStatus.OK); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), Matchers.<HttpEntity<?>>any(), + Matchers.eq(Long.class))).thenReturn(ans); + List<MicroserviceParameter> defaultParam = new ArrayList<>(); + MicroserviceParameter microserviceParameter = new MicroserviceParameter(); + microserviceParameter.setId(1l); + microserviceParameter.setPara_key("test"); + MicroserviceParameter microserviceParameter2 = new MicroserviceParameter(); + microserviceParameter2.setId(2l); + microserviceParameter2.setPara_key("test2"); + defaultParam.add(microserviceParameter); + defaultParam.add(microserviceParameter2); + Mockito.when(microserviceService.getParametersById(1)).thenReturn(defaultParam); + Mockito.when(widgetParameterService.getUserParamById(1l, user.getId(), 1l)).thenReturn(null); + WidgetCatalogParameter userValue = new WidgetCatalogParameter(); + userValue.setUser_value("test123"); + Mockito.when(widgetParameterService.getUserParamById(1l, user.getId(), 2l)).thenReturn(userValue); + PortalRestResponse<List<WidgetParameterResult>> actual = widgetsCatalogController + .getWidgetParameterResult(request, 1); + PortalRestResponse<List<WidgetParameterResult>> expected = new PortalRestResponse<List<WidgetParameterResult>>( + PortalRestStatusEnum.OK, "SUCCESS", new ArrayList<>()); + assertEquals(expected.getStatus(), actual.getStatus()); + } + @SuppressWarnings("unchecked") @Test - public void getUserWidgetCatalogTest() throws RestClientException, Exception{ - - String resourceType = null; - List<WidgetCatalog> widgets = new ArrayList<>(); - PowerMockito.mockStatic(EcompPortalUtils.class); - PowerMockito.mockStatic(SystemProperties.class); - PowerMockito.mockStatic(EPCommonSystemProperties.class); - Mockito.when(EcompPortalUtils.widgetMsProtocol()).thenReturn("test1"); - Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WIDGET_MS_PROTOCOL)).thenReturn("https"); -// Mockito.when(WidgetServiceHeaders.getInstance()).thenReturn(HttpHeaders.ACCEPT); - Mockito.when(SystemProperties.getProperty("microservices.widget.local.port")).thenReturn("test"); - Mockito.when(consulHealthService.getServiceLocation("widgets-service", - "test")).thenReturn("test.com"); - Mockito.when(new HttpEntity(WidgetServiceHeaders.getInstance())).thenReturn(mockHttpEntity); -// HttpEntity<String> entity = new HttpEntity<String>("helloWorld"); -// ResponseEntity<ArrayList> ans = new ResponseEntity<>(statusCode); -// Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), -// Matchers.<HttpEntity<?>>any(), Matchers.eq(ArrayList.class))).thenReturn(ans); -// List<WidgetCatalog> expectedWidgets = widgetsCatalogController.getUserWidgetCatalog(mockedRequest, mockedResponse, "guestT"); + public void doDownloadTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(EcompPortalUtils.widgetMsProtocol()).thenReturn("test1"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WIDGET_MS_PROTOCOL)).thenReturn("https"); + Mockito.when(SystemProperties.getProperty("microservices.widget.local.port")).thenReturn("test"); + Mockito.when(EcompPortalUtils.getPropertyOrDefault("microservices.widget.username", "widget_user")) + .thenReturn("test"); + Mockito.when(CipherUtil + .decryptPKC(EcompPortalUtils.getPropertyOrDefault("microservices.widget.password", "widget_password"))) + .thenReturn("abc"); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + MockHttpServletRequest request = new MockHttpServletRequest(); + MockHttpServletResponse response = new MockHttpServletResponse(); + ResponseEntity<byte[]> mockData = new ResponseEntity("testfile.zip".getBytes(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), Matchers.<HttpEntity<?>>any(), + Matchers.eq(byte[].class))).thenReturn(mockData); + widgetsCatalogController.doDownload(request, response, 1l); + } + + @Test + public void saveWidgetParameterTest() { + PowerMockito.mockStatic(EPUserUtils.class); + EPUser user = mockUser.mockEPUser(); + WidgetCatalogParameter widgetCatalogParameter = new WidgetCatalogParameter(); + widgetCatalogParameter.setId(1l); + widgetCatalogParameter.setParamId(1l); + widgetCatalogParameter.setUserId(user.getId()); + widgetCatalogParameter.setUser_value("test123"); + MockHttpServletRequest request = new MockHttpServletRequest(); + Mockito.when(EPUserUtils.getUserSession(request)).thenReturn(user); + Mockito.when(widgetParameterService.getUserParamById(widgetCatalogParameter.getWidgetId(), + widgetCatalogParameter.getUserId(), widgetCatalogParameter.getParamId())).thenReturn(widgetCatalogParameter); + PortalRestResponse<String> response = widgetsCatalogController.saveWidgetParameter(request, + widgetCatalogParameter); + PortalRestResponse<String> expected = new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", ""); + assertEquals(expected.getMessage(), response.getMessage()); + } + + @Test + public void saveWidgetParameterExceptionTest() { + PowerMockito.mockStatic(EPUserUtils.class); + EPUser user = mockUser.mockEPUser(); + WidgetCatalogParameter widgetCatalogParameter = new WidgetCatalogParameter(); + widgetCatalogParameter.setId(1l); + widgetCatalogParameter.setParamId(1l); + widgetCatalogParameter.setUserId(user.getId()); + widgetCatalogParameter.setUser_value("test123"); + MockHttpServletRequest request = new MockHttpServletRequest(); + Mockito.when(EPUserUtils.getUserSession(request)).thenReturn(user); + Mockito.doThrow(new NullPointerException()).when(widgetParameterService).getUserParamById(widgetCatalogParameter.getWidgetId(), + widgetCatalogParameter.getUserId(), widgetCatalogParameter.getParamId()); + PortalRestResponse<String> response = widgetsCatalogController.saveWidgetParameter(request, + widgetCatalogParameter); + PortalRestResponse<String> expected = new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", ""); + assertEquals(expected.getMessage(), response.getMessage()); } } diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/core/PopulateSampleTestData.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/core/PopulateSampleTestData.java index e3eeaa54..3a7d4f39 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/core/PopulateSampleTestData.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/core/PopulateSampleTestData.java @@ -36,7 +36,7 @@ package org.onap.portalapp.portal.core; * * ECOMP is a trademark and service mark of AT&T Intellectual Property. */ -//package org.openecomp.portalapp.portal.core; +//package org.onap.portalapp.portal.core; // //import java.sql.Connection; //import java.sql.SQLException; @@ -45,7 +45,7 @@ package org.onap.portalapp.portal.core; // //import org.junit.Before; //import org.junit.Test; -//import org.openecomp.portalapp.framework.ApplicationCommonContextTestSuite; +//import org.onap.portalapp.framework.ApplicationCommonContextTestSuite; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.core.io.ClassPathResource; //import org.springframework.jdbc.datasource.DataSourceUtils; diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/core/RemoveSampleTestData.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/core/RemoveSampleTestData.java index 1fa6c7d1..2aedae69 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/core/RemoveSampleTestData.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/core/RemoveSampleTestData.java @@ -36,7 +36,7 @@ package org.onap.portalapp.portal.core; * * ECOMP is a trademark and service mark of AT&T Intellectual Property. */ -//package org.openecomp.portalapp.portal.core; +//package org.onap.portalapp.portal.core; // //import java.sql.Connection; //import java.sql.SQLException; @@ -45,7 +45,7 @@ package org.onap.portalapp.portal.core; // //import org.junit.After; //import org.junit.Test; -//import org.openecomp.portalapp.framework.ApplicationCommonContextTestSuite; +//import org.onap.portalapp.framework.ApplicationCommonContextTestSuite; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.core.io.ClassPathResource; //import org.springframework.jdbc.datasource.DataSourceUtils; diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/core/RestURLsTestSuite.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/core/RestURLsTestSuite.java index 8bb21812..9c93790a 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/core/RestURLsTestSuite.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/core/RestURLsTestSuite.java @@ -36,7 +36,7 @@ package org.onap.portalapp.portal.core; * * ECOMP is a trademark and service mark of AT&T Intellectual Property. */ -//package org.openecomp.portalapp.portal.core; +//package org.onap.portalapp.portal.core; // //import static org.junit.Assert.assertEquals; //import static org.junit.Assert.assertTrue; @@ -47,12 +47,12 @@ package org.onap.portalapp.portal.core; // //import org.junit.Assert; //import org.junit.Test; -//import org.openecomp.portalapp.framework.ApplicationCommonContextTestSuite; -//import org.openecomp.portalapp.portal.domain.EPUser; -//import org.openecomp.portalapp.portal.test.core.MockEPUser; -//import org.openecomp.portalapp.portal.transport.AppNameIdIsAdmin; -//import org.openecomp.portalapp.portal.transport.AppsListWithAdminRole; -//import org.openecomp.portalsdk.core.util.SystemProperties; +//import org.onap.portalapp.framework.ApplicationCommonContextTestSuite; +//import org.onap.portalapp.portal.domain.EPUser; +//import org.onap.portalapp.portal.test.core.MockEPUser; +//import org.onap.portalapp.portal.transport.AppNameIdIsAdmin; +//import org.onap.portalapp.portal.transport.AppsListWithAdminRole; +//import org.onap.portalsdk.core.util.SystemProperties; //import org.springframework.http.MediaType; //import org.springframework.test.web.servlet.ResultActions; //import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/domain/EPUserAppsManualSortPreferenceTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/domain/EPUserAppsManualSortPreferenceTest.java index 2923eb2b..0b6a7e13 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/domain/EPUserAppsManualSortPreferenceTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/domain/EPUserAppsManualSortPreferenceTest.java @@ -46,7 +46,7 @@ public class EPUserAppsManualSortPreferenceTest { public EPUserAppsManualSortPreference mockEPUserAppsManualSortPreference(){ EPUserAppsManualSortPreference epUserAppsManualSortPreference = new EPUserAppsManualSortPreference(); - epUserAppsManualSortPreference.setUserId(1); + epUserAppsManualSortPreference.setUserId(1l); epUserAppsManualSortPreference.setAppId((long)1); epUserAppsManualSortPreference.setAppManualSortOrder(1); @@ -58,7 +58,7 @@ public class EPUserAppsManualSortPreferenceTest { EPUserAppsManualSortPreference epUserAppsManualSortPreference = mockEPUserAppsManualSortPreference(); - assertEquals(epUserAppsManualSortPreference.getUserId(), 1); + assertEquals(epUserAppsManualSortPreference.getUserId(), new Long(1)); assertEquals(epUserAppsManualSortPreference.getAppId(), new Long(1)); assertEquals(epUserAppsManualSortPreference.getAppManualSortOrder(), 1); diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/domain/EPWidgetsManualSortPreferenceTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/domain/EPWidgetsManualSortPreferenceTest.java index b4b4780d..5dbca6eb 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/domain/EPWidgetsManualSortPreferenceTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/domain/EPWidgetsManualSortPreferenceTest.java @@ -47,7 +47,7 @@ public class EPWidgetsManualSortPreferenceTest { public EPWidgetsManualSortPreference mockEPWidgetsManualSortPreference(){ EPWidgetsManualSortPreference epWidgetsManualSortPreference = new EPWidgetsManualSortPreference(); - epWidgetsManualSortPreference.setUserId(1); + epWidgetsManualSortPreference.setUserId(1l); epWidgetsManualSortPreference.setWidgetId((long)1); epWidgetsManualSortPreference.setWidgetRow(1); epWidgetsManualSortPreference.setWidgetCol(1); @@ -62,7 +62,7 @@ public class EPWidgetsManualSortPreferenceTest { EPWidgetsManualSortPreference epWidgetsManualSortPreference = mockEPWidgetsManualSortPreference(); assertEquals(epWidgetsManualSortPreference.getWidgetId(), new Long(1)); - assertEquals(epWidgetsManualSortPreference.getUserId(), 1); + assertEquals(epWidgetsManualSortPreference.getUserId(), new Long(1)); assertEquals(epWidgetsManualSortPreference.getWidgetRow(), 1); assertEquals(epWidgetsManualSortPreference.getWidgetCol(), 1); assertEquals(epWidgetsManualSortPreference.getWidgetHeight(), 1); diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/framework/ApplicationCommonContextTestSuite.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/framework/ApplicationCommonContextTestSuite.java index 764cebab..96c41729 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/framework/ApplicationCommonContextTestSuite.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/framework/ApplicationCommonContextTestSuite.java @@ -36,20 +36,20 @@ package org.onap.portalapp.portal.framework; * * ECOMP is a trademark and service mark of AT&T Intellectual Property. */ -//package org.openecomp.portalapp.portal.framework; +//package org.onap.portalapp.portal.framework; // //import java.io.IOException; // //import org.junit.Before; //import org.junit.runner.RunWith; -//import org.openecomp.portalsdk.core.conf.AppConfig; -////import org.openecomp.portalapp.conf.ExternalAppConfig; -////import org.openecomp.portalapp.conf.HibernateMappingLocations; -//import org.openecomp.portalsdk.core.conf.HibernateConfiguration; -//import org.openecomp.portalsdk.core.conf.HibernateMappingLocatable; -//import org.openecomp.portalsdk.core.objectcache.AbstractCacheManager; -//import org.openecomp.portalsdk.core.util.CacheManager; -//import org.openecomp.portalsdk.core.util.SystemProperties; +//import org.onap.portalsdk.core.conf.AppConfig; +////import org.onap.portalapp.conf.ExternalAppConfig; +////import org.onap.portalapp.conf.HibernateMappingLocations; +//import org.onap.portalsdk.core.conf.HibernateConfiguration; +//import org.onap.portalsdk.core.conf.HibernateMappingLocatable; +//import org.onap.portalsdk.core.objectcache.AbstractCacheManager; +//import org.onap.portalsdk.core.util.CacheManager; +//import org.onap.portalsdk.core.util.SystemProperties; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.context.annotation.Bean; //import org.springframework.context.annotation.ComponentScan; @@ -118,14 +118,14 @@ package org.onap.portalapp.portal.framework; //} // //@Configuration -//@ComponentScan(basePackages = "org.openecomp", excludeFilters = { +//@ComponentScan(basePackages = "org.onap", excludeFilters = { // // the following source configurations should not be scanned; instead of // // using Exclusion filter, we can use the @Profile annotation to exclude // // them -// @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.openecomp.portalsdk.core.controller.LogoutController*"), -// @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.openecomp.portalsdk.core.controller.SDKLoginController*"), -// @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.openecomp.portalapp.conf.ExternalAppConfig*"), -// @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.openecomp.*.*InitUebHandler*") }) +// @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.onap.portalsdk.core.controller.LogoutController*"), +// @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.onap.portalsdk.core.controller.SDKLoginController*"), +// @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.onap.portalapp.conf.ExternalAppConfig*"), +// @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.onap.*.*InitUebHandler*") }) //@Profile("test") //class MockAppConfig extends AppConfig { // @@ -185,7 +185,7 @@ package org.onap.portalapp.portal.framework; // } // // public String[] getPackagesToScan() { -// return new String[] { "org.openecomp", "src" }; +// return new String[] { "org.onap", "src" }; // } // //} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/logging/aop/EPEELFLoggerAdviceTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/logging/aop/EPEELFLoggerAdviceTest.java new file mode 100644 index 00000000..5f8319cf --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/logging/aop/EPEELFLoggerAdviceTest.java @@ -0,0 +1,158 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.portal.logging.aop; + +import static org.junit.Assert.assertNotEquals; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.utils.EPCommonSystemProperties; +import org.onap.portalapp.portal.utils.EcompPortalUtils; +import org.onap.portalapp.util.EPUserUtils; +import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum; +import org.onap.portalsdk.core.web.support.AppUtils; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpSession; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ EcompPortalUtils.class, SystemProperties.class, + EPCommonSystemProperties.class }) +public class EPEELFLoggerAdviceTest { + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @Mock + SecurityEventTypeEnum securityEventTypeEnum; + + @InjectMocks + EPEELFLoggerAdvice epEELFLoggerAdvice = new EPEELFLoggerAdvice(); + + @Test + @SuppressWarnings("static-access") + public void getCurrentDateTimeUTCTest(){ + String actual = epEELFLoggerAdvice.getCurrentDateTimeUTC(); + assertNotEquals("", actual); + } + + MockEPUser mockUser = new MockEPUser(); + + @Test + public void loadServletRequestBasedDefaultsTest(){ + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(AppUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + EPUser user = mockUser.mockEPUser(); + MockHttpSession session = new MockHttpSession(); + session.setAttribute("user_attribute_name", user); + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setServletPath("http:test.com"); + request.setSession(session); + request.addHeader("user-agent", "Mozilla/5.0"); + Mockito.when(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)).thenReturn("user_attribute_name"); + epEELFLoggerAdvice.loadServletRequestBasedDefaults(request, securityEventTypeEnum); + } + + @Test + public void afterTest(){ + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(AppUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + EPUser user = mockUser.mockEPUser(); + MockHttpSession session = new MockHttpSession(); + session.setAttribute("user_attribute_name", user); + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setServletPath("http:test.com"); + request.setSession(session); + request.addHeader("user-agent", "Mozilla/5.0"); + Mockito.when(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)).thenReturn("user_attribute_name"); + List<Object> args = new ArrayList<>(); + args.add("testClassName"); + args.add("testMethodName"); + Object[] passOnArgs = args.toArray(new Object[args.size()]); + List<Object> args2 = new ArrayList<>(); + args2.add(request); + Object[] httpArgs = args2.toArray(new Object[args2.size()]); + epEELFLoggerAdvice.after(securityEventTypeEnum, "200", "200", httpArgs, null, passOnArgs); + } + + @Test + public void BeforeTest(){ + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(AppUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + EPUser user = mockUser.mockEPUser(); + MockHttpSession session = new MockHttpSession(); + session.setAttribute("user_attribute_name", user); + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setServletPath("http:test.com"); + request.setSession(session); + request.addHeader("user-agent", "Mozilla/5.0"); + Mockito.when(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)).thenReturn("user_attribute_name"); + List<Object> args = new ArrayList<>(); + args.add("testClassName"); + args.add("testMethodName"); + Object[] passOnArgs = args.toArray(new Object[args.size()]); + List<Object> args2 = new ArrayList<>(); + args2.add(request); + Object[] httpArgs = args2.toArray(new Object[args2.size()]); + epEELFLoggerAdvice.before(securityEventTypeEnum, httpArgs, passOnArgs); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/AdminRolesServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/AdminRolesServiceImplTest.java new file mode 100644 index 00000000..d9beb4d1 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/AdminRolesServiceImplTest.java @@ -0,0 +1,435 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.portal.service; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.SortedSet; + +import org.hibernate.SQLQuery; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.json.simple.JSONObject; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.EPApp; +import org.onap.portalapp.portal.domain.EPRole; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.domain.EPUserApp; +import org.onap.portalapp.portal.domain.UserRole; +import org.onap.portalapp.portal.transport.AppNameIdIsAdmin; +import org.onap.portalapp.portal.transport.AppsListWithAdminRole; +import org.onap.portalapp.portal.utils.EPCommonSystemProperties; +import org.onap.portalapp.portal.utils.EcompPortalUtils; +import org.onap.portalapp.portal.utils.PortalConstants; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.service.DataAccessServiceImpl; +import org.onap.portalsdk.core.util.SystemProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ EcompPortalUtils.class, PortalConstants.class, SystemProperties.class, + EPCommonSystemProperties.class }) +public class AdminRolesServiceImplTest { + + @Mock + DataAccessService dataAccessService = new DataAccessServiceImpl(); + + @Mock + EPAppCommonServiceImpl epAppCommonServiceImpl = new EPAppCommonServiceImpl(); + + @Mock + SearchServiceImpl searchServiceImpl = new SearchServiceImpl(); + + @Mock + SessionFactory sessionFactory; + + @Mock + Session session; + + @Mock + Transaction transaction; + + @Mock + RestTemplate template = new RestTemplate(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + Mockito.when(sessionFactory.openSession()).thenReturn(session); + Mockito.when(session.beginTransaction()).thenReturn(transaction); + } + + @After + public void after() { + session.close(); + } + + @InjectMocks + AdminRolesServiceImpl adminRolesServiceImpl = new AdminRolesServiceImpl(); + + private Long ACCOUNT_ADMIN_ROLE_ID = 999L; + + private Long ECOMP_APP_ID = 1L; + + public EPApp mockApp() { + EPApp app = new EPApp(); + app.setName("Test"); + app.setImageUrl("test"); + app.setNameSpace("com.test.app"); + app.setCentralAuth(true); + app.setDescription("test"); + app.setNotes("test"); + app.setUrl("test"); + app.setId((long) 1); + app.setAppRestEndpoint("test"); + app.setAlternateUrl("test"); + app.setName("test"); + app.setMlAppName("test"); + app.setMlAppAdminId("test"); + app.setUsername("test"); + app.setAppPassword("test"); + app.setOpen(false); + app.setEnabled(true); + app.setUebKey("test"); + app.setUebSecret("test"); + app.setUebTopicName("test"); + app.setAppType(1); + return app; + } + + MockEPUser mockUser = new MockEPUser(); + + @SuppressWarnings("deprecation") + @Test + public void getAppsWithAdminRoleStateForUserTest() { + EPUser user = mockUser.mockEPUser(); + EPApp app = mockApp(); + app.setId(1l); + List<EPUser> users = new ArrayList<>(); + users.add(user); + Map<String, String> userParams = new HashMap<>(); + userParams.put("org_user_id", user.getOrgUserId()); + Mockito.when(dataAccessService.executeNamedQuery("getEPUserByOrgUserId", userParams, null)).thenReturn(users); + List<EPUserApp> userAppList = new ArrayList<>(); + EPUserApp epUserApp = new EPUserApp(); + EPRole role = new EPRole(); + role.setActive(true); + role.setId(1l); + role.setName("test role"); + epUserApp.setApp(app); + epUserApp.setRole(role); + epUserApp.setUserId(1l); + userAppList.add(epUserApp); + Mockito.when(dataAccessService.getList(EPUserApp.class, + " where userId = " + user.getId() + " and role.id = " + 999, null, null)).thenReturn(userAppList); + List<EPApp> appsList = new ArrayList<>(); + appsList.add(app); + Mockito.when(dataAccessService.getList(EPApp.class, + " where ( enabled = 'Y' or id = " + ECOMP_APP_ID + ")", null, null)).thenReturn(appsList); + AppsListWithAdminRole actual = adminRolesServiceImpl.getAppsWithAdminRoleStateForUser(user.getOrgUserId()); + assertNotNull(actual); + } + + @SuppressWarnings({ "deprecation", "unchecked" }) + @Test + public void setAppsWithAdminRoleStateForUserTest() { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(PortalConstants.class); + PowerMockito.mockStatic(SystemProperties.class); + EPUser user = mockUser.mockEPUser(); + EPApp app = mockApp(); + app.setId(1l); + EPApp app2 = mockApp(); + app2.setName("app2"); + app2.setNameSpace("com.test.app2"); + app2.setId(2l); + EPApp app3 = mockApp(); + app3.setName("app3"); + app3.setNameSpace("com.test.app3"); + app3.setId(3l); + List<EPApp> apps = new ArrayList<>(); + apps.add(app); + apps.add(app2); + apps.add(app3); + Mockito.when(epAppCommonServiceImpl.getAppsFullList()).thenReturn(apps); + + List<EPUser> localUserList = new ArrayList<>(); + localUserList.add(user); + Mockito.when( + dataAccessService.getList(EPUser.class, " where org_user_id='" + user.getOrgUserId() + "'", null, null)) + .thenReturn(localUserList); + List<EPUserApp> oldAppsWhereUserIsAdmin = new ArrayList<EPUserApp>(); + EPUserApp epUserApp = new EPUserApp(); + EPRole role = new EPRole(); + role.setActive(true); + role.setId(999l); + role.setName("app5"); + epUserApp.setApp(app); + epUserApp.setRole(role); + epUserApp.setUserId(1l); + oldAppsWhereUserIsAdmin.add(epUserApp); + Mockito.when(dataAccessService.getList(EPUserApp.class, + " where userId = " + user.getId() + " and role.id = " + ACCOUNT_ADMIN_ROLE_ID, null, + null)).thenReturn(oldAppsWhereUserIsAdmin); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + EPApp app4 = mockApp(); + app4.setId(6l); + app4.setName("app7"); + app4.setNameSpace("com.test.app7"); + List<EPApp> apps2 = new ArrayList<>(); + apps2.add(app); + apps2.add(app2); + apps2.add(app3); + apps2.add(app4); + Mockito.when(dataAccessService.executeNamedQuery("getCentralizedApps", null, null)).thenReturn(apps2); + Mockito.when( + EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn(true); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn("@test.com"); + JSONObject getUserRoles = new JSONObject(); + ResponseEntity<String> getResponse = new ResponseEntity<>(getUserRoles.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + ResponseEntity<String> addResponse = new ResponseEntity<>(HttpStatus.CREATED); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(addResponse); + + AppsListWithAdminRole newAppsListWithAdminRoles = new AppsListWithAdminRole(); + ArrayList<AppNameIdIsAdmin> appsRoles = new ArrayList<>(); + AppNameIdIsAdmin appNameIdIsAdmin = new AppNameIdIsAdmin(); + appNameIdIsAdmin.setAppName("app1"); + appNameIdIsAdmin.setId(2l); + appNameIdIsAdmin.setIsAdmin(true); + appNameIdIsAdmin.setRestrictedApp(false); + AppNameIdIsAdmin appNameIdIsAdmin2 = new AppNameIdIsAdmin(); + appNameIdIsAdmin2.setAppName("app2"); + appNameIdIsAdmin2.setId(3l); + appNameIdIsAdmin2.setIsAdmin(true); + appNameIdIsAdmin2.setRestrictedApp(false); + appsRoles.add(appNameIdIsAdmin); + appsRoles.add(appNameIdIsAdmin2); + newAppsListWithAdminRoles.setOrgUserId(user.getOrgUserId()); + newAppsListWithAdminRoles.setAppsRoles(appsRoles); + Mockito.when((EPApp) session.get(EPApp.class, appNameIdIsAdmin.id)).thenReturn(app2); + Mockito.when((EPApp) session.get(EPApp.class, appNameIdIsAdmin2.id)).thenReturn(app3); + JSONObject getUserRoles2 = new JSONObject(); + JSONObject getUserRoles3 = new JSONObject(); + JSONObject getUserRoles4 = new JSONObject(); + JSONObject finalUserRoles = new JSONObject(); + getUserRoles2.put("role", "com.test.app3.Account_Administrator"); + getUserRoles3.put("role", "com.test.app3.admin"); + getUserRoles4.put("role", "com.test.app3.owner"); + List<JSONObject> userRoles = new ArrayList<>(); + userRoles.add(getUserRoles2); + userRoles.add(getUserRoles3); + userRoles.add(getUserRoles4); + finalUserRoles.put("userRole", userRoles); + ResponseEntity<String> getResponse2 = new ResponseEntity<>(finalUserRoles.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse2); + boolean actual = adminRolesServiceImpl.setAppsWithAdminRoleStateForUser(newAppsListWithAdminRoles); + assertTrue(actual); + } + + @Test + public void isSuperAdminTest() { + EPUser user = mockUser.mockEPUser(); + user.setId(1l); + SQLQuery SqlQuery = Mockito.mock(SQLQuery.class); + Mockito.when(session.createSQLQuery(Matchers.anyString())).thenReturn(SqlQuery); + List<UserRole> userRoleList = new ArrayList<>(); + UserRole userRole = new UserRole(); + userRole.setFirstName("Hello"); + userRole.setLastName("World"); + userRole.setRoleId(1l); + userRole.setRoleName("test"); + userRole.setUser_Id(1l); + userRoleList.add(userRole); + Mockito.when(dataAccessService.executeSQLQuery(Matchers.anyString(), Matchers.any(), Matchers.anyMap())) + .thenReturn(userRoleList); + boolean actual = adminRolesServiceImpl.isSuperAdmin(user); + assertTrue(actual); + } + + @Test + public void isSuperAdminExceptionTest() { + EPUser user = mockUser.mockEPUser(); + user.setId(1l); + SQLQuery SqlQuery = Mockito.mock(SQLQuery.class); + Mockito.when(session.createSQLQuery(Matchers.anyString())).thenReturn(SqlQuery); + Mockito.doThrow(new NullPointerException()).when(dataAccessService).executeSQLQuery(Matchers.anyString(), + Matchers.any(), Matchers.anyMap()); + boolean actual = adminRolesServiceImpl.isSuperAdmin(user); + assertFalse(actual); + } + + @Test + public void isAccountAdminTest() { + EPUser user = mockUser.mockEPUser(); + EPApp app = mockApp(); + app.setId(2l); + SortedSet<EPUserApp> userApps = user.getEPUserApps(); + EPUserApp epUserApp = new EPUserApp(); + EPRole role = new EPRole(); + role.setActive(true); + role.setId(999l); + role.setName("test role"); + epUserApp.setApp(app); + epUserApp.setRole(role); + epUserApp.setUserId(1l); + userApps.add(epUserApp); + user.setUserApps(userApps); + Mockito.when((EPUser) dataAccessService.getDomainObject(Matchers.any(), Matchers.anyLong(), Matchers.anyMap())) + .thenReturn(user); + boolean actual = adminRolesServiceImpl.isAccountAdmin(user); + assertTrue(actual); + } + + @Test + public void isAccountAdminExceptionTest() { + EPUser user = mockUser.mockEPUser(); + Mockito.doThrow(new NullPointerException()).when(dataAccessService).getDomainObject(Matchers.any(), + Matchers.anyLong(), Matchers.anyMap()); + boolean actual = adminRolesServiceImpl.isAccountAdmin(user); + assertFalse(actual); + } + + @Test + public void isUserTest() { + EPUser user = mockUser.mockEPUser(); + EPApp app = mockApp(); + app.setId(2l); + SortedSet<EPUserApp> userApps = user.getEPUserApps(); + EPUserApp epUserApp = new EPUserApp(); + EPRole role = new EPRole(); + role.setActive(true); + role.setId(2l); + role.setName("test role"); + epUserApp.setApp(app); + epUserApp.setRole(role); + epUserApp.setUserId(1l); + userApps.add(epUserApp); + user.setUserApps(userApps); + Mockito.when((EPUser) dataAccessService.getDomainObject(Matchers.any(), Matchers.anyLong(), Matchers.anyMap())) + .thenReturn(user); + boolean actual = adminRolesServiceImpl.isUser(user); + assertTrue(actual); + } + + @Test + public void isUserExceptionTest() { + EPUser user = mockUser.mockEPUser(); + Mockito.doThrow(new NullPointerException()).when(dataAccessService).getDomainObject(Matchers.any(), + Matchers.anyLong(), Matchers.anyMap()); + boolean actual = adminRolesServiceImpl.isUser(user); + assertFalse(actual); + } + + @Test + public void getRolesByAppTest() { + EPUser user = mockUser.mockEPUser(); + EPApp app = mockApp(); + List<EPRole> expected = new ArrayList<>(); + EPRole role = new EPRole(); + role.setActive(true); + role.setId(1l); + role.setName("test role"); + expected.add(role); + Mockito.when(dataAccessService.executeSQLQuery(Matchers.anyString(), Matchers.any(), Matchers.anyMap())) + .thenReturn(expected); + List<EPRole> actual = adminRolesServiceImpl.getRolesByApp(user, app.getId()); + assertEquals(expected, actual); + } + + @Test + public void isAccountAdminOfApplicationTest() { + EPUser user = mockUser.mockEPUser(); + EPApp app = mockApp(); + SortedSet<EPUserApp> userApps = user.getEPUserApps(); + EPUserApp epUserApp = new EPUserApp(); + EPRole role = new EPRole(); + role.setActive(true); + role.setId(999l); + role.setName("test role"); + epUserApp.setApp(app); + epUserApp.setRole(role); + epUserApp.setUserId(1l); + userApps.add(epUserApp); + user.setUserApps(userApps); + Mockito.when((EPUser) dataAccessService.getDomainObject(Matchers.any(), Matchers.anyLong(), Matchers.anyMap())) + .thenReturn(user); + boolean actual = adminRolesServiceImpl.isAccountAdminOfApplication(user, app); + assertTrue(actual); + } + + @Test + public void isAccountAdminOfApplicationExceptionTest() { + EPUser user = mockUser.mockEPUser(); + EPApp app = mockApp(); + Mockito.doThrow(new NullPointerException()).when(dataAccessService).getDomainObject(Matchers.any(), + Matchers.anyLong(), Matchers.anyMap()); + boolean actual = adminRolesServiceImpl.isAccountAdminOfApplication(user, app); + assertFalse(actual); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPAppCommonServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPAppCommonServiceImplTest.java new file mode 100644 index 00000000..3bfd7ec4 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPAppCommonServiceImplTest.java @@ -0,0 +1,815 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.portal.service; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletResponse; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.criterion.Criterion; +import org.hibernate.criterion.Restrictions; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.AppIdAndNameTransportModel; +import org.onap.portalapp.portal.domain.AppsResponse; +import org.onap.portalapp.portal.domain.EPApp; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.domain.EPUserAppsManualSortPreference; +import org.onap.portalapp.portal.domain.EPUserAppsSortPreference; +import org.onap.portalapp.portal.domain.EPWidgetsManualSortPreference; +import org.onap.portalapp.portal.domain.EcompApp; +import org.onap.portalapp.portal.domain.UserRole; +import org.onap.portalapp.portal.domain.UserRoles; +import org.onap.portalapp.portal.transport.EPAppsSortPreference; +import org.onap.portalapp.portal.transport.EPDeleteAppsManualSortPref; +import org.onap.portalapp.portal.transport.EPWidgetsSortPreference; +import org.onap.portalapp.portal.transport.FieldsValidator; +import org.onap.portalapp.portal.transport.FunctionalMenuItem; +import org.onap.portalapp.portal.transport.LocalRole; +import org.onap.portalapp.portal.transport.OnboardingApp; +import org.onap.portalapp.portal.ueb.EPUebHelper; +import org.onap.portalapp.portal.utils.EPCommonSystemProperties; +import org.onap.portalapp.portal.utils.EcompPortalUtils; +import org.onap.portalapp.portal.utils.PortalConstants; +import org.onap.portalsdk.core.onboarding.util.PortalApiConstants; +import org.onap.portalsdk.core.onboarding.util.PortalApiProperties; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.service.DataAccessServiceImpl; +import org.onap.portalsdk.core.util.SystemProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import com.att.nsa.apiClient.credentials.ApiCredential; +import com.att.nsa.cambria.client.CambriaClientBuilders; +import com.att.nsa.cambria.client.CambriaIdentityManager; + +@RunWith(PowerMockRunner.class) +@PowerMockIgnore({ "org.apache.http.conn.ssl.*", "javax.net.ssl.*", "javax.crypto.*" }) +@PrepareForTest({ EcompPortalUtils.class, PortalApiProperties.class, PortalApiConstants.class, SystemProperties.class, + PortalConstants.class, EPCommonSystemProperties.class }) +public class EPAppCommonServiceImplTest { + + @Mock + DataAccessService dataAccessService = new DataAccessServiceImpl(); + + @Mock + AdminRolesServiceImpl adminRolesServiceImpl = new AdminRolesServiceImpl(); + + @Mock + EPUebHelper epUebHelper; + + @Mock + SessionFactory sessionFactory; + + @Mock + Session session; + + @Mock + Transaction transaction; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + Mockito.when(sessionFactory.openSession()).thenReturn(session); + Mockito.when(session.beginTransaction()).thenReturn(transaction); + } + + MockEPUser mockUser = new MockEPUser(); + + String ECOMP_APP_ID = "1"; + String SUPER_ADMIN_ROLE_ID = "1"; + String ACCOUNT_ADMIN_ROLE_ID = "999"; + String RESTRICTED_APP_ROLE_ID = "900"; + + @InjectMocks + EPAppCommonServiceImpl epAppCommonServiceImpl = new EPAppCommonServiceImpl(); + + public EPApp mockApp() { + EPApp app = new EPApp(); + app.setName("Test"); + app.setImageUrl("test"); + app.setDescription("test"); + app.setNotes("test"); + app.setUrl("test"); + app.setId((long) 1); + app.setAppRestEndpoint("test"); + app.setAlternateUrl("test"); + app.setName("test"); + app.setMlAppName("test"); + app.setMlAppAdminId("test"); + app.setUsername("test"); + app.setAppPassword("test"); + app.setOpen(false); + app.setEnabled(false); + app.setCentralAuth(true); + app.setUebKey("test"); + app.setUebSecret("test"); + app.setUebTopicName("test"); + app.setAppType(1); + return app; + } + + @Test + public void getUserAsAdminAppsTest() { + EPApp mockApp = mockApp(); + EPApp mockApp2 = mockApp(); + mockApp2.setId(2l); + EPUser user = mockUser.mockEPUser(); + List<EPApp> expected = new ArrayList<>(); + expected.add(mockApp); + expected.add(mockApp2); + String sql = "SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID=FN_APP.APP_ID where " + + "FN_USER_ROLE.USER_ID=" + user.getId() + " AND FN_USER_ROLE.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID + + " AND FN_APP.ENABLED = 'Y'"; + Mockito.when(dataAccessService.executeSQLQuery(sql, EPApp.class, null)).thenReturn(expected); + Mockito.when(adminRolesServiceImpl.isAccountAdmin(user)).thenReturn(true); + List<EPApp> actual = epAppCommonServiceImpl.getUserAsAdminApps(user); + assertEquals(expected, actual); + } + + @Test + public void getUserAsAdminAppsTestException() { + EPUser user = mockUser.mockEPUser(); + String sql = "SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID=FN_APP.APP_ID where " + + "FN_USER_ROLE.USER_ID=" + user.getId() + " AND FN_USER_ROLE.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID + + " AND FN_APP.ENABLED = 'Y'"; + Mockito.doThrow(new NullPointerException()).when(dataAccessService).executeSQLQuery(sql, EPApp.class, null); + Mockito.when(adminRolesServiceImpl.isAccountAdmin(user)).thenReturn(true); + List<EPApp> actual = epAppCommonServiceImpl.getUserAsAdminApps(user); + assertNull(actual); + } + + @Test + public void getUserByOrgUserIdAsAdminAppsTest() { + EPApp mockApp = mockApp(); + EPApp mockApp2 = mockApp(); + mockApp2.setId(2l); + EPUser user = mockUser.mockEPUser(); + List<EPApp> expected = new ArrayList<>(); + expected.add(mockApp); + expected.add(mockApp2); + String format = "SELECT * FROM FN_APP app INNER JOIN FN_USER_ROLE userrole ON userrole.APP_ID=app.APP_ID " + + "INNER JOIN FN_USER user on user.USER_ID = userrole.USER_ID " + + "WHERE user.org_user_id = '%s' AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID + + " AND FN_APP.ENABLED = 'Y'"; + String sql = String.format(format, user.getOrgUserId()); + Mockito.when(dataAccessService.executeSQLQuery(sql, EPApp.class, null)).thenReturn(expected); + List<EPApp> actual = epAppCommonServiceImpl.getUserByOrgUserIdAsAdminApps(user.getOrgUserId()); + assertEquals(expected, actual); + } + + @Test + public void getUserByOrgUserIdAsAdminAppsTestException() { + EPUser user = mockUser.mockEPUser(); + String format = "SELECT * FROM FN_APP app INNER JOIN FN_USER_ROLE userrole ON userrole.APP_ID=app.APP_ID " + + "INNER JOIN FN_USER user on user.USER_ID = userrole.USER_ID " + + "WHERE user.org_user_id = '%s' AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID + + " AND FN_APP.ENABLED = 'Y'"; + String sql = String.format(format, user.getOrgUserId()); + Mockito.doThrow(new NullPointerException()).when(dataAccessService).executeSQLQuery(sql, EPApp.class, null); + List<EPApp> actual = epAppCommonServiceImpl.getUserByOrgUserIdAsAdminApps(user.getOrgUserId()); + assertNull(actual); + } + + @SuppressWarnings("deprecation") + @Test + public void getAppsFullListTest() { + EPApp mockApp = mockApp(); + EPApp mockApp2 = mockApp(); + mockApp2.setId(2l); + List<EPApp> expected = new ArrayList<>(); + expected.add(mockApp); + expected.add(mockApp2); + Mockito.when(dataAccessService.getList(EPApp.class, null)).thenReturn(expected); + List<EPApp> actual = epAppCommonServiceImpl.getAppsFullList(); + assertEquals(expected, actual); + + } + + @Test + public void getEcompAppAppsFullListTest() { + List<EcompApp> expected = new ArrayList<>(); + List<EcompApp> actual = epAppCommonServiceImpl.getEcompAppAppsFullList(); + assertEquals(expected, actual); + } + + @Test + public void transformAppsToEcompAppsTest() { + EPApp mockApp = mockApp(); + EPApp mockApp2 = mockApp(); + mockApp2.setId(2l); + List<EPApp> epAppsList = new ArrayList<>(); + epAppsList.add(mockApp); + epAppsList.add(mockApp2); + List<EcompApp> expected = new ArrayList<>(); + EcompApp ecompApp = new EcompApp(); + ecompApp.setName("test1"); + EcompApp ecompApp2 = new EcompApp(); + ecompApp2.setName("test2"); + expected.add(ecompApp); + expected.add(ecompApp2); + List<EcompApp> actual = epAppCommonServiceImpl.transformAppsToEcompApps(epAppsList); + assertEquals(expected.size(), actual.size()); + } + + @SuppressWarnings({ "unchecked", "deprecation" }) + @Test + public void getAllAppsForAllTest() { + EPApp mockApp = mockApp(); + EPApp mockApp2 = mockApp(); + mockApp2.setId(2l); + List<EPApp> appsList = new ArrayList<>(); + appsList.add(mockApp); + appsList.add(mockApp2); + List<AppsResponse> expected = new ArrayList<>(); + AppsResponse appResponse1 = new AppsResponse(mockApp.getId(), mockApp.getName(), mockApp.isRestrictedApp(), + mockApp.getEnabled()); + AppsResponse appResponse2 = new AppsResponse(mockApp2.getId(), mockApp2.getName(), mockApp2.isRestrictedApp(), + mockApp2.getEnabled()); + expected.add(appResponse1); + expected.add(appResponse2); + Mockito.when((List<EPApp>) dataAccessService.getList(EPApp.class, " where id != " + ECOMP_APP_ID, "name", null)) + .thenReturn(appsList); + List<AppsResponse> actual = epAppCommonServiceImpl.getAllApps(true); + assertEquals(expected.size(), actual.size()); + } + + @SuppressWarnings({ "unchecked", "deprecation" }) + @Test + public void getAllAppsIsNotAllTest() { + EPApp mockApp = mockApp(); + EPApp mockApp2 = mockApp(); + mockApp2.setId(2l); + List<EPApp> appsList = new ArrayList<>(); + appsList.add(mockApp); + appsList.add(mockApp2); + List<AppsResponse> expected = new ArrayList<>(); + AppsResponse appResponse1 = new AppsResponse(mockApp.getId(), mockApp.getName(), mockApp.isRestrictedApp(), + mockApp.getEnabled()); + AppsResponse appResponse2 = new AppsResponse(mockApp2.getId(), mockApp2.getName(), mockApp2.isRestrictedApp(), + mockApp2.getEnabled()); + expected.add(appResponse1); + expected.add(appResponse2); + Mockito.when((List<EPApp>) dataAccessService.getList(EPApp.class, + " where ( enabled = 'Y' or id = " + ECOMP_APP_ID + ")", "name", null)).thenReturn(appsList); + List<AppsResponse> actual = epAppCommonServiceImpl.getAllApps(false); + assertEquals(expected.size(), actual.size()); + } + + @Test + public void getAppTest() { + EPApp expected = mockApp(); + Mockito.when((EPApp) dataAccessService.getDomainObject(EPApp.class, expected.getId(), null)) + .thenReturn(expected); + EPApp actual = epAppCommonServiceImpl.getApp(expected.getId()); + assertEquals(expected, actual); + } + + @Test + public void getAppExceptionTest() { + EPApp expected = mockApp(); + Mockito.doThrow(new NullPointerException()).when(dataAccessService).getDomainObject(EPApp.class, + expected.getId(), null); + EPApp actual = epAppCommonServiceImpl.getApp(expected.getId()); + assertNull(actual); + } + + @SuppressWarnings("unchecked") + @Test + public void getAppDetailTest() { + EPApp expected = mockApp(); + List<EPApp> appList = new ArrayList<>(); + appList.add(expected); + final Map<String, String> params = new HashMap<String, String>(); + params.put("appName", expected.getName()); + Mockito.when((List<EPApp>) dataAccessService.executeNamedQuery("getMyloginAppDetails", params, null)) + .thenReturn(appList); + EPApp actual = epAppCommonServiceImpl.getAppDetail(expected.getName()); + assertEquals(expected, actual); + } + + @Test + public void getAppDetailExceptionTest() { + EPApp expected = mockApp(); + List<EPApp> appList = new ArrayList<>(); + appList.add(expected); + final Map<String, String> params = new HashMap<String, String>(); + params.put("appName", expected.getName()); + Mockito.doThrow(new NullPointerException()).when(dataAccessService).executeNamedQuery("getMyloginAppDetails", + params, null); + EPApp actual = epAppCommonServiceImpl.getAppDetail(expected.getName()); + assertNull(actual); + } + + @Test + public void getUserProfile() { + EPUser user = mockUser.mockEPUser(); + final Map<String, String> params = new HashMap<>(); + params.put("org_user_id", user.getOrgUserId()); + List<UserRole> userRoleList = new ArrayList<>(); + UserRole userRole = new UserRole(); + userRole.setFirstName("GuestT"); + userRole.setLastName("GuestT"); + userRole.setOrgUserId("guestT"); + userRole.setRoleId(1l); + userRole.setRoleName("Test"); + userRole.setUser_Id(-1l); + userRoleList.add(userRole); + UserRoles expected = new UserRoles(userRole); + Mockito.when(dataAccessService.executeNamedQuery("getUserRoles", params, null)).thenReturn(userRoleList); + UserRoles actual = epAppCommonServiceImpl.getUserProfile(user.getOrgUserId()); + assertEquals(expected.getOrgUserId(), actual.getOrgUserId()); + } + + @Test + public void getUserProfileNullTest() { + EPUser user = mockUser.mockEPUser(); + final Map<String, String> params = new HashMap<>(); + params.put("org_user_id", user.getOrgUserId()); + List<UserRole> userRoleList = new ArrayList<>(); + Mockito.when(dataAccessService.executeNamedQuery("getUserRoles", params, null)).thenReturn(userRoleList); + UserRoles actual = epAppCommonServiceImpl.getUserProfile(user.getOrgUserId()); + assertNull(actual); + } + + @Test + public void getUserProfileNormalizedTest() { + EPUser user = mockUser.mockEPUser(); + user.setGuest(true); + user.setLoginId("guestT"); + final Map<String, String> params = new HashMap<>(); + params.put("org_user_id", user.getOrgUserId()); + List<UserRole> userRoleList = new ArrayList<>(); + UserRole userRole = new UserRole(); + userRole.setFirstName("GuestT"); + userRole.setLastName("GuestT"); + userRole.setOrgUserId("guestT"); + userRole.setRoleId(1l); + userRole.setRoleName("Test"); + userRole.setUser_Id(-1l); + userRoleList.add(userRole); + UserRoles expected = new UserRoles(userRole); + Mockito.when(dataAccessService.executeNamedQuery("getUserRoles", params, null)).thenReturn(userRoleList); + UserRoles actual = epAppCommonServiceImpl.getUserProfileNormalized(user); + assertEquals(expected.getOrgUserId(), actual.getOrgUserId()); + } + + @Test + public void getRestrictedAppRolesTest() { + EPUser user = mockUser.mockEPUser(); + EPApp mockApp = mockApp(); + mockApp.setRestrictedApp(true); + user.setLoginId("guestT"); + List<LocalRole> expected = new ArrayList<>(); + LocalRole localRole = new LocalRole(); + localRole.setRoleId(1); + localRole.setRolename("test1"); + expected.add(localRole); + String sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND ROLE_ID = '" + + RESTRICTED_APP_ROLE_ID + "'"; + Mockito.when(dataAccessService.executeSQLQuery(sql, LocalRole.class, null)).thenReturn(expected); + Mockito.when((EPApp) dataAccessService.getDomainObject(EPApp.class, mockApp.getId(), null)).thenReturn(mockApp); + List<LocalRole> actual = epAppCommonServiceImpl.getAppRoles(mockApp.getId()); + assertEquals(expected, actual); + } + + @Test + public void getPoralAppRolesTest() { + EPUser user = mockUser.mockEPUser(); + EPApp mockApp = mockApp(); + mockApp.setRestrictedApp(false); + mockApp.setId(1l); + user.setLoginId("guestT"); + List<LocalRole> expected = new ArrayList<>(); + LocalRole localRole = new LocalRole(); + localRole.setRoleId(1); + localRole.setRolename("test1"); + expected.add(localRole); + String sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND APP_ID IS NULL"; + Mockito.when(dataAccessService.executeSQLQuery(sql, LocalRole.class, null)).thenReturn(expected); + Mockito.when((EPApp) dataAccessService.getDomainObject(EPApp.class, mockApp.getId(), null)).thenReturn(mockApp); + List<LocalRole> actual = epAppCommonServiceImpl.getAppRoles(mockApp.getId()); + assertEquals(expected, actual); + } + + @Test + public void getNonPortalAndNonRestrictedAppRolesTest() { + EPUser user = mockUser.mockEPUser(); + EPApp mockApp = mockApp(); + mockApp.setRestrictedApp(false); + mockApp.setId(2l); + user.setLoginId("guestT"); + List<LocalRole> expected = new ArrayList<>(); + LocalRole localRole = new LocalRole(); + localRole.setRoleId(1); + localRole.setRolename("test1"); + expected.add(localRole); + String sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND APP_ID = '" + + mockApp.getId() + "'"; + Mockito.when(dataAccessService.executeSQLQuery(sql, LocalRole.class, null)).thenReturn(expected); + Mockito.when((EPApp) dataAccessService.getDomainObject(EPApp.class, mockApp.getId(), null)).thenReturn(mockApp); + List<LocalRole> actual = epAppCommonServiceImpl.getAppRoles(mockApp.getId()); + assertEquals(expected, actual); + } + + @Test + public void getAdminAppsTest() { + EPUser user = mockUser.mockEPUser(); + user.setId(1l); + List<AppIdAndNameTransportModel> expected = new ArrayList<>(); + AppIdAndNameTransportModel appIdAndNameTransportModel = new AppIdAndNameTransportModel(); + appIdAndNameTransportModel.setId(1l); + appIdAndNameTransportModel.setName("test1"); + expected.add(appIdAndNameTransportModel); + Mockito.when(adminRolesServiceImpl.isAccountAdmin(user)).thenReturn(true); + String format = "SELECT app.APP_ID, app.APP_NAME, app.APP_TYPE FROM FN_APP app inner join FN_USER_ROLE userrole ON userrole.APP_ID=app.APP_ID " + + "where userrole.USER_ID = %d AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID + + " AND (app.ENABLED = 'Y' OR app.APP_ID=1)"; + String sql = String.format(format, user.getId()); + Mockito.when(dataAccessService.executeSQLQuery(sql, AppIdAndNameTransportModel.class, null)) + .thenReturn(expected); + List<AppIdAndNameTransportModel> actual = epAppCommonServiceImpl.getAdminApps(user); + assertEquals(expected, actual); + } + + @Test + public void getAdminAppsExceptionTest() { + EPUser user = mockUser.mockEPUser(); + user.setId(1l); + List<AppIdAndNameTransportModel> expected = new ArrayList<>(); + Mockito.when(adminRolesServiceImpl.isAccountAdmin(user)).thenReturn(true); + String format = "SELECT app.APP_ID, app.APP_NAME, app.APP_TYPE FROM FN_APP app inner join FN_USER_ROLE userrole ON userrole.APP_ID=app.APP_ID " + + "where userrole.USER_ID = %d AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID + + " AND (app.ENABLED = 'Y' OR app.APP_ID=1)"; + String sql = String.format(format, user.getId()); + Mockito.doThrow(new NullPointerException()).when(dataAccessService).executeSQLQuery(sql, + AppIdAndNameTransportModel.class, null); + List<AppIdAndNameTransportModel> actual = epAppCommonServiceImpl.getAdminApps(user); + assertEquals(expected, actual); + } + + @SuppressWarnings("unchecked") + @Test + public void addOnboardingAppUnKnownHostExceptionTest() throws Exception { + PowerMockito.mockStatic(PortalApiConstants.class); + PowerMockito.mockStatic(PortalApiProperties.class); + EPUser user = mockUser.mockEPUser(); + List<EPApp> mockAppList = new ArrayList<>(); + OnboardingApp onboardApp = new OnboardingApp(); + onboardApp.setRestrictedApp(false); + onboardApp.name = "test1"; + onboardApp.url = "http://test.com"; + onboardApp.isOpen = false; + onboardApp.isEnabled = true; + onboardApp.username = "test123"; + onboardApp.appPassword = "test123"; + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion urlCrit = Restrictions.eq("url", onboardApp.url); + Criterion nameCrit = Restrictions.eq("name", onboardApp.name); + Criterion orCrit = Restrictions.or(urlCrit, nameCrit); + restrictionsList.add(orCrit); + List<String> uebList = new ArrayList<>(); + uebList.add("localhost"); + com.att.nsa.apiClient.credentials.ApiCredential apiCredential = new ApiCredential(user.getEmail(), + "ECOMP Portal Owner"); + CambriaIdentityManager mockIm = Mockito + .spy(new CambriaClientBuilders.IdentityManagerBuilder().usingHosts(uebList).build()); + Mockito.doReturn(apiCredential).when(mockIm).createApiKey(user.getEmail(), "ECOMP Portal Owner"); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.UEB_URL_LIST)).thenReturn("localhost"); + Mockito.when((List<EPApp>) dataAccessService.getList(EPApp.class, null, restrictionsList, null)) + .thenReturn(mockAppList); + FieldsValidator expected = new FieldsValidator(); + expected.setHttpStatusCode(Long.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); + FieldsValidator actual = epAppCommonServiceImpl.addOnboardingApp(onboardApp, user); + assertEquals(expected, actual); + } + + @SuppressWarnings("unchecked") + @Test + public void modifyOnboardingAppTest() throws Exception { + EPUser user = mockUser.mockEPUser(); + EPApp mockApp = mockApp(); + mockApp.setName("test1"); + mockApp.setId(2l); + mockApp.setUrl("http://test.com"); + mockApp.setUsername("test123"); + mockApp.setAppPassword("test123"); + mockApp.setRestrictedApp(false); + mockApp.setEnabled(true); + mockApp.setOpen(false); + List<EPApp> mockAppList = new ArrayList<>(); + mockAppList.add(mockApp); + OnboardingApp onboardApp = new OnboardingApp(); + onboardApp.setRestrictedApp(false); + onboardApp.name = "test1"; + onboardApp.id = 2l; + onboardApp.url = "http://test.com"; + onboardApp.isOpen = false; + onboardApp.isEnabled = true; + onboardApp.thumbnail = "test123imgthumbnail"; + onboardApp.username = "test123"; + onboardApp.appPassword = "test123"; + List<Criterion> restrictionsList1 = new ArrayList<Criterion>(); + Criterion idCrit = Restrictions.eq("id", onboardApp.id); + Criterion urlCrit = Restrictions.eq("url", onboardApp.url); + Criterion nameCrit = Restrictions.eq("name", onboardApp.name); + Criterion orCrit = Restrictions.or(idCrit, urlCrit, nameCrit); + restrictionsList1.add(orCrit); + Mockito.when((List<EPApp>) dataAccessService.getList(EPApp.class, null, restrictionsList1, null)) + .thenReturn(mockAppList); + Mockito.when((EPApp) session.get(EPApp.class, onboardApp.id)).thenReturn(mockApp); + String sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn " + + "FROM fn_menu_functional m, fn_menu_functional_roles r " + "WHERE m.menu_id = r.menu_id " + + " AND r.app_id = '" + onboardApp.id + "' "; + List<Integer> roles = new ArrayList<>(); + roles.add(1); + roles.add(2); + List<FunctionalMenuItem> menuItems = new ArrayList<>(); + FunctionalMenuItem functionalMenuItem = new FunctionalMenuItem(); + functionalMenuItem.setRestrictedApp(false); + functionalMenuItem.setUrl("http://test1.com"); + functionalMenuItem.setRoles(roles); + menuItems.add(functionalMenuItem); + Mockito.when(dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null)).thenReturn(menuItems); + Mockito.when((FunctionalMenuItem) session.get(FunctionalMenuItem.class, functionalMenuItem.menuId)) + .thenReturn(functionalMenuItem); + Mockito.doNothing().when(epUebHelper).addPublisher(mockApp); + FieldsValidator expected = new FieldsValidator(); + expected.setHttpStatusCode(Long.valueOf(HttpServletResponse.SC_OK)); + FieldsValidator actual = epAppCommonServiceImpl.modifyOnboardingApp(onboardApp, user); + assertEquals(expected, actual); + } + + @Test + public void saveWidgetsSortManualTest() { + EPUser user = mockUser.mockEPUser(); + List<EPWidgetsManualSortPreference> mockEPManualWidgets = new ArrayList<>(); + EPWidgetsManualSortPreference epWidgetsManualSortPreference = new EPWidgetsManualSortPreference(); + epWidgetsManualSortPreference.setUserId(user.getId()); + epWidgetsManualSortPreference.setWidgetCol(1); + epWidgetsManualSortPreference.setWidgetHeight(1); + epWidgetsManualSortPreference.setWidgetId(1l); + epWidgetsManualSortPreference.setWidgetRow(1); + epWidgetsManualSortPreference.setWidgetWidth(1); + mockEPManualWidgets.add(epWidgetsManualSortPreference); + final Map<String, Long> params = new HashMap<>(); + params.put("userId", user.getId()); + Mockito.when(dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null)) + .thenReturn(mockEPManualWidgets); + FieldsValidator expected = new FieldsValidator(); + expected.setHttpStatusCode(Long.valueOf(HttpServletResponse.SC_OK)); + List<EPWidgetsSortPreference> epWidgetsSortPreferenceList = new ArrayList<>(); + EPWidgetsSortPreference mockEPWidgetsSortPreference = new EPWidgetsSortPreference(); + mockEPWidgetsSortPreference.setRow(2); + mockEPWidgetsSortPreference.setHeaderText("test"); + mockEPWidgetsSortPreference.setSizeX(2); + mockEPWidgetsSortPreference.setSizeY(2); + mockEPWidgetsSortPreference.setWidgetid(2l); + mockEPWidgetsSortPreference.setWidgetIdentifier("test"); + mockEPWidgetsSortPreference.setCol(2); + epWidgetsSortPreferenceList.add(mockEPWidgetsSortPreference); + FieldsValidator actual = epAppCommonServiceImpl.saveWidgetsSortManual(epWidgetsSortPreferenceList, user); + assertEquals(expected, actual); + } + + @Test + public void saveWidgetsSortManualExistingRecordTest() { + EPUser user = mockUser.mockEPUser(); + List<EPWidgetsManualSortPreference> mockEPManualWidgets = new ArrayList<>(); + EPWidgetsManualSortPreference epWidgetsManualSortPreference = new EPWidgetsManualSortPreference(); + epWidgetsManualSortPreference.setUserId(user.getId()); + epWidgetsManualSortPreference.setWidgetCol(1); + epWidgetsManualSortPreference.setWidgetHeight(1); + epWidgetsManualSortPreference.setWidgetId(2l); + epWidgetsManualSortPreference.setWidgetRow(1); + epWidgetsManualSortPreference.setWidgetWidth(1); + mockEPManualWidgets.add(epWidgetsManualSortPreference); + final Map<String, Long> params = new HashMap<>(); + params.put("userId", user.getId()); + Mockito.when(dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null)) + .thenReturn(mockEPManualWidgets); + FieldsValidator expected = new FieldsValidator(); + expected.setHttpStatusCode(Long.valueOf(HttpServletResponse.SC_OK)); + List<EPWidgetsSortPreference> epWidgetsSortPreferenceList = new ArrayList<>(); + EPWidgetsSortPreference mockEPWidgetsSortPreference = new EPWidgetsSortPreference(); + mockEPWidgetsSortPreference.setRow(2); + mockEPWidgetsSortPreference.setHeaderText("test"); + mockEPWidgetsSortPreference.setSizeX(2); + mockEPWidgetsSortPreference.setSizeY(2); + mockEPWidgetsSortPreference.setWidgetid(2l); + mockEPWidgetsSortPreference.setWidgetIdentifier("test"); + mockEPWidgetsSortPreference.setCol(2); + epWidgetsSortPreferenceList.add(mockEPWidgetsSortPreference); + FieldsValidator actual = epAppCommonServiceImpl.saveWidgetsSortManual(epWidgetsSortPreferenceList, user); + assertEquals(expected, actual); + } + + @Test + public void deleteUserWidgetSortPrefTest() { + EPUser user = mockUser.mockEPUser(); + List<EPWidgetsManualSortPreference> mockEPManualWidgets = new ArrayList<>(); + EPWidgetsManualSortPreference epWidgetsManualSortPreference = new EPWidgetsManualSortPreference(); + epWidgetsManualSortPreference.setUserId(user.getId()); + epWidgetsManualSortPreference.setWidgetCol(1); + epWidgetsManualSortPreference.setWidgetHeight(1); + epWidgetsManualSortPreference.setWidgetId(2l); + epWidgetsManualSortPreference.setWidgetRow(1); + epWidgetsManualSortPreference.setWidgetWidth(1); + mockEPManualWidgets.add(epWidgetsManualSortPreference); + final Map<String, Long> params = new HashMap<>(); + params.put("userId", user.getId()); + Mockito.when(dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null)) + .thenReturn(mockEPManualWidgets); + FieldsValidator expected = new FieldsValidator(); + expected.setHttpStatusCode(Long.valueOf(HttpServletResponse.SC_OK)); + List<EPWidgetsSortPreference> epWidgetsSortPreferenceList = new ArrayList<>(); + EPWidgetsSortPreference mockEPWidgetsSortPreference = new EPWidgetsSortPreference(); + mockEPWidgetsSortPreference.setRow(2); + mockEPWidgetsSortPreference.setHeaderText("test"); + mockEPWidgetsSortPreference.setSizeX(2); + mockEPWidgetsSortPreference.setSizeY(2); + mockEPWidgetsSortPreference.setWidgetid(2l); + mockEPWidgetsSortPreference.setWidgetIdentifier("test"); + mockEPWidgetsSortPreference.setCol(2); + epWidgetsSortPreferenceList.add(mockEPWidgetsSortPreference); + FieldsValidator actual = epAppCommonServiceImpl.deleteUserWidgetSortPref(epWidgetsSortPreferenceList, user); + assertEquals(expected, actual); + } + + @Test + public void saveAppsSortPreferenceForNewUserTest() { + EPUser user = mockUser.mockEPUser(); + List<EPUserAppsSortPreference> mockEPAppSortPrefList = new ArrayList<>(); + final Map<String, Long> params = new HashMap<>(); + params.put("userId", user.getId()); + Mockito.when(dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null)) + .thenReturn(mockEPAppSortPrefList); + FieldsValidator expected = new FieldsValidator(); + expected.setHttpStatusCode(Long.valueOf(HttpServletResponse.SC_OK)); + EPAppsSortPreference mockEPAppsSortPreference = new EPAppsSortPreference(); + mockEPAppsSortPreference.setIndex(1); + mockEPAppsSortPreference.setTitle("Last Used"); + mockEPAppsSortPreference.setValue("L"); + FieldsValidator actual = epAppCommonServiceImpl.saveAppsSortPreference(mockEPAppsSortPreference, user); + assertEquals(expected, actual); + } + + @Test + public void saveAppsSortPreferenceUpdateTest() { + EPUser user = mockUser.mockEPUser(); + List<EPUserAppsSortPreference> mockEPAppSortPrefList = new ArrayList<>(); + EPUserAppsSortPreference mockEPAppSortPref = new EPUserAppsSortPreference(); + mockEPAppSortPref.setSortPref("L"); + mockEPAppSortPref.setId(2l); + mockEPAppSortPref.setUserId((int) (long) user.getId()); + mockEPAppSortPrefList.add(mockEPAppSortPref); + final Map<String, Long> params = new HashMap<>(); + params.put("userId", user.getId()); + Mockito.when(dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null)) + .thenReturn(mockEPAppSortPrefList); + FieldsValidator expected = new FieldsValidator(); + expected.setHttpStatusCode(Long.valueOf(HttpServletResponse.SC_OK)); + EPAppsSortPreference mockEPAppsSortPreference = new EPAppsSortPreference(); + mockEPAppsSortPreference.setIndex(1); + mockEPAppsSortPreference.setTitle("Last Used"); + mockEPAppsSortPreference.setValue("L"); + FieldsValidator actual = epAppCommonServiceImpl.saveAppsSortPreference(mockEPAppsSortPreference, user); + assertEquals(expected, actual); + } + + @Test + public void getUserAppsSortTypePreferenceTest() { + EPUser user = mockUser.mockEPUser(); + final Map<String, Long> params = new HashMap<>(); + List<EPUserAppsSortPreference> mockEPAppSortPrefList = new ArrayList<>(); + EPUserAppsSortPreference mockEPAppSortPref = new EPUserAppsSortPreference(); + mockEPAppSortPref.setSortPref("L"); + mockEPAppSortPref.setId(2l); + mockEPAppSortPref.setUserId((int) (long) user.getId()); + mockEPAppSortPrefList.add(mockEPAppSortPref); + params.put("userId", user.getId()); + Mockito.when(dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null)) + .thenReturn(mockEPAppSortPrefList); + String actual = epAppCommonServiceImpl.getUserAppsSortTypePreference(user); + assertEquals(mockEPAppSortPref.getSortPref(), actual); + } + + @Test + public void getUserAppsSortTypePreferenceExceptionTest() { + EPUser user = mockUser.mockEPUser(); + final Map<String, Long> params = new HashMap<>(); + List<EPUserAppsSortPreference> mockEPAppSortPrefList = new ArrayList<>(); + EPUserAppsSortPreference mockEPAppSortPref = new EPUserAppsSortPreference(); + mockEPAppSortPref.setSortPref("L"); + mockEPAppSortPref.setId(2l); + mockEPAppSortPref.setUserId((int) (long) user.getId()); + mockEPAppSortPrefList.add(mockEPAppSortPref); + params.put("userId", user.getId()); + Mockito.doThrow(new NullPointerException()).when(dataAccessService) + .executeNamedQuery("userAppsSortPreferenceQuery", params, null); + String actual = epAppCommonServiceImpl.getUserAppsSortTypePreference(user); + assertNull(actual); + } + + @Test + public void deleteUserAppSortManualTest() { + EPUser user = mockUser.mockEPUser(); + EPApp mockApp = mockApp(); + mockApp.setId(1l); + final Map<String, Long> params = new HashMap<>(); + List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>(); + EPUserAppsManualSortPreference epManualApp = new EPUserAppsManualSortPreference(); + epManualApp.setAppId(mockApp.getId()); + epManualApp.setAppManualSortOrder(1); + epManualApp.setId(1l); + epManualApp.setUserId(user.getId()); + epManualApps.add(epManualApp); + params.put("userId", user.getId()); + Mockito.when(dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null)).thenReturn(epManualApps); + EPDeleteAppsManualSortPref delAppSortManual = new EPDeleteAppsManualSortPref(); + delAppSortManual.setAppId(mockApp.getId()); + delAppSortManual.setPending(false); + delAppSortManual.setSelect(false); + FieldsValidator actual = epAppCommonServiceImpl.deleteUserAppSortManual(delAppSortManual, user); + FieldsValidator expected = new FieldsValidator(); + expected.setHttpStatusCode(200l); + assertEquals(expected, actual); + } + + @Test + public void deleteUserAppSortManualExceptionTest() { + EPUser user = mockUser.mockEPUser(); + EPApp mockApp = mockApp(); + mockApp.setId(1l); + final Map<String, Long> params = new HashMap<>(); + List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>(); + EPUserAppsManualSortPreference epManualApp = new EPUserAppsManualSortPreference(); + epManualApp.setAppId(mockApp.getId()); + epManualApp.setAppManualSortOrder(1); + epManualApp.setId(1l); + epManualApp.setUserId(user.getId()); + epManualApps.add(epManualApp); + params.put("userId", user.getId()); + Mockito.doThrow(new NullPointerException()).when(dataAccessService).executeNamedQuery("userAppsManualSortPrfQuery", params, null); + EPDeleteAppsManualSortPref delAppSortManual = new EPDeleteAppsManualSortPref(); + delAppSortManual.setAppId(mockApp.getId()); + delAppSortManual.setPending(false); + delAppSortManual.setSelect(false); + FieldsValidator actual = epAppCommonServiceImpl.deleteUserAppSortManual(delAppSortManual, user); + FieldsValidator expected = new FieldsValidator(); + expected.setHttpStatusCode(500l); + assertEquals(expected, actual); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPLeftMenuServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPLeftMenuServiceImplTest.java new file mode 100644 index 00000000..3cc6762f --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPLeftMenuServiceImplTest.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.portal.service; + +import static org.junit.Assert.assertNotEquals; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; + +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.CentralizedApp; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalsdk.core.domain.MenuData; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.service.DataAccessServiceImpl; + +public class EPLeftMenuServiceImplTest { + + @Mock + DataAccessService dataAccessService = new DataAccessServiceImpl(); + + @Mock + ExternalAccessRolesServiceImpl externalAccessRolesServiceImpl = new ExternalAccessRolesServiceImpl(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @InjectMocks + EPLeftMenuServiceImpl epLeftMenuServiceImpl = new EPLeftMenuServiceImpl(); + + + MockEPUser mockUser = new MockEPUser(); + + @Test + public void getLeftMenuItemsTest() { + EPUser user = mockUser.mockEPUser(); + Set<MenuData> fullMenuSet = new TreeSet<>(); + MenuData menuData = new MenuData(); + menuData.setAction("test"); + menuData.setFunctionCd("test_1"); + menuData.setActive(true); + menuData.setExternalUrl("test"); + menuData.setId(1l); + menuData.setMenuSetCode("test"); + menuData.setSortOrder((short) 1); + menuData.setSeparator(true); + fullMenuSet.add(menuData); + Set<String> roleFunctionSet = new TreeSet<>(); + roleFunctionSet.add("test"); + roleFunctionSet.add("test2"); + Map<String, String> params = new HashMap<>(); + params.put("userId", user.getOrgUserId()); + List<CentralizedApp> applicationsList = new ArrayList<>(); + List<CentralizedApp> applicationsList2 = new ArrayList<>(); + CentralizedApp centralizedApp = new CentralizedApp(); + centralizedApp.setAppId(1); + centralizedApp.setAppName("test"); + applicationsList.add(centralizedApp); + applicationsList2.add(centralizedApp); + Mockito.when(dataAccessService.executeNamedQuery(Matchers.anyString(), Matchers.anyMap(), Matchers.anyMap())).thenReturn(applicationsList); + Mockito.when(externalAccessRolesServiceImpl.getCentralizedAppsOfUser(Matchers.anyString())).thenReturn(applicationsList2); + String actual = epLeftMenuServiceImpl.getLeftMenuItems(user, fullMenuSet, roleFunctionSet); + JSONObject notExpected = new JSONObject(); + assertNotEquals(notExpected.toString(), actual); + } + + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPLoginServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPLoginServiceImplTest.java new file mode 100644 index 00000000..5eaa40fd --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPLoginServiceImplTest.java @@ -0,0 +1,239 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.portal.service; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.command.EPLoginBean; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.EPApp; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.utils.EPCommonSystemProperties; +import org.onap.portalapp.portal.utils.EcompPortalUtils; +import org.onap.portalapp.util.EPUserUtils; +import org.onap.portalsdk.core.onboarding.util.CipherUtil; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.service.DataAccessServiceImpl; +import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.portalsdk.core.web.support.AppUtils; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.web.client.RestTemplate; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ EPUserUtils.class, CipherUtil.class, AppUtils.class, SystemProperties.class, + EPCommonSystemProperties.class }) +public class EPLoginServiceImplTest { + + @Mock + DataAccessService dataAccessService = new DataAccessServiceImpl(); + + @Mock + EPAppCommonServiceImpl epAppCommonServiceImpl = new EPAppCommonServiceImpl(); + + @Mock + SearchServiceImpl searchServiceImpl = new SearchServiceImpl(); + + @Mock + RestTemplate template = new RestTemplate(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @InjectMocks + EPLoginServiceImpl epLoginServiceImpl = new EPLoginServiceImpl(); + + public EPApp mockApp() { + EPApp app = new EPApp(); + app.setName("Test"); + app.setImageUrl("test"); + app.setNameSpace("com.test.app"); + app.setCentralAuth(true); + app.setDescription("test"); + app.setNotes("test"); + app.setUrl("test"); + app.setId((long) 1); + app.setAppRestEndpoint("test"); + app.setAlternateUrl("test"); + app.setName("test"); + app.setMlAppName("test"); + app.setMlAppAdminId("test"); + app.setUsername("test"); + app.setAppPassword("test"); + app.setOpen(false); + app.setEnabled(true); + app.setUebKey("test"); + app.setUebSecret("test"); + app.setUebTopicName("test"); + app.setAppType(1); + return app; + } + + MockEPUser mockUser = new MockEPUser(); + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test + public void findUserTest() throws Exception { + EPUser user = mockUser.mockEPUser(); + EPLoginBean expected = new EPLoginBean(); + expected.setOrgUserId("guestT"); + Map<String, String> params = new HashMap<>(); + params.put("org_user_id", expected.getOrgUserId()); + List list = new ArrayList<>(); + list.add(user); + Mockito.when(dataAccessService.executeNamedQuery("getEPUserByOrgUserId", params, new HashMap())).thenReturn(list); + EPLoginBean actual = epLoginServiceImpl.findUser(expected, "test", new HashMap<>()); + assertNotNull(actual); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test + public void findUserPasswordMatchTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(AppUtils.class); + PowerMockito.mockStatic(CipherUtil.class); + EPUser user = mockUser.mockEPUser(); + user.setLoginId("guestT"); + user.setLoginPwd("abc"); + EPLoginBean expected = new EPLoginBean(); + expected.setLoginId(user.getLoginId()); + expected.setLoginPwd("xyz"); + Map<String, String> params = new HashMap<>(); + params.put("org_user_id", user.getOrgUserId()); + List list = new ArrayList<>(); + list.add(user); + Mockito.when(dataAccessService.executeNamedQuery("getEPUserByOrgUserId", params, new HashMap())).thenReturn(list); + Map<String, String> params2 = new HashMap<>(); + params2.put("login_id", user.getOrgUserId()); + List list2 = new ArrayList<>(); + list2.add(user); + Mockito.when(dataAccessService.executeNamedQuery("getEPUserByLoginId", params2, new HashMap())).thenReturn(list2); + Mockito.when(CipherUtil.decryptPKC(user.getLoginPwd())).thenReturn("xyz"); + EPLoginBean actual = epLoginServiceImpl.findUser(expected, "test", new HashMap<>()); + assertNotNull(actual); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test + public void findUserExcpetionTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(AppUtils.class); + PowerMockito.mockStatic(CipherUtil.class); + EPUser user = mockUser.mockEPUser(); + user.setLoginId("guestT"); + user.setLoginPwd("abc"); + EPLoginBean expected = new EPLoginBean(); + expected.setLoginId(user.getLoginId()); + expected.setLoginPwd("xyz"); + Map<String, String> params = new HashMap<>(); + params.put("org_user_id", user.getOrgUserId()); + List list = new ArrayList<>(); + list.add(user); + Mockito.when(dataAccessService.executeNamedQuery("getEPUserByOrgUserId", params, new HashMap())).thenReturn(list); + Map<String, String> params2 = new HashMap<>(); + params2.put("login_id", user.getOrgUserId()); + List list2 = new ArrayList<>(); + list2.add(user); + Mockito.doThrow(new NullPointerException()).when(dataAccessService).executeNamedQuery("getEPUserByLoginId", params2, new HashMap()); + Mockito.when(CipherUtil.decryptPKC(user.getLoginPwd())).thenReturn("xyz"); + EPLoginBean actual = epLoginServiceImpl.findUser(expected, "test", new HashMap<>()); + assertEquals(expected,actual); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test + public void findUserAppUtilsExcpetionTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(AppUtils.class); + PowerMockito.mockStatic(CipherUtil.class); + EPUser user = mockUser.mockEPUser(); + user.setLoginId("guestT"); + user.setLoginPwd("abc"); + user.setActive(false); + EPLoginBean expected = new EPLoginBean(); + expected.setOrgUserId(user.getOrgUserId()); + Map<String, String> params = new HashMap<>(); + params.put("org_user_id", user.getOrgUserId()); + List list = new ArrayList<>(); + list.add(user); + Mockito.when(dataAccessService.executeNamedQuery("getEPUserByOrgUserId", params, new HashMap())).thenReturn(list); + Mockito.when(EPUserUtils.hasRole(user, SystemProperties.getProperty(SystemProperties.SYS_ADMIN_ROLE_ID))).thenReturn(false); + Mockito.when(AppUtils.isApplicationLocked()).thenReturn(true); + Mockito.when(EPUserUtils.hasRole(user, SystemProperties.getProperty(SystemProperties.SYS_ADMIN_ROLE_ID))).thenReturn(false); + Mockito.when(AppUtils.isApplicationLocked()).thenReturn(true); + EPLoginBean actual = epLoginServiceImpl.findUser(expected, "test", new HashMap<>()); + assertEquals(expected,actual); + } + + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test + public void findUserWithoutPwdTest() { + EPUser user = mockUser.mockEPUser(); + Map<String, String> params = new HashMap<>(); + params.put("login_id", user.getOrgUserId()); + List list = new ArrayList<>(); + list.add(user); + Mockito.when(dataAccessService.executeNamedQuery("getEPUserByLoginId", params, new HashMap())).thenReturn(list); + EPUser actual = epLoginServiceImpl.findUserWithoutPwd(user.getOrgUserId()); + assertEquals(user.getOrgUserId(), actual.getOrgUserId()); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPProfileServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPProfileServiceImplTest.java new file mode 100644 index 00000000..9aa60185 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPProfileServiceImplTest.java @@ -0,0 +1,86 @@ +/* +* ============LICENSE_START======================================================= +* ONAP PORTAL +* ================================================================================ +* Copyright 2018 TechMahindra +*================================================================================= +* Licensed 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 +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* ============LICENSE_END========================================================= +*/ +package org.onap.portalapp.portal.service; + +import static org.junit.Assert.*; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.service.EPProfileServiceImpl; +import org.onap.portalsdk.core.dao.ProfileDao; +import org.onap.portalsdk.core.domain.Profile; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.service.DataAccessServiceImpl; + +public class EPProfileServiceImplTest { + + @Mock + DataAccessService dataAccessService = new DataAccessServiceImpl(); + + @Mock + ProfileDao profileDao; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @InjectMocks + EPProfileServiceImpl epProfileServiceImpl = new EPProfileServiceImpl(); + + MockEPUser mockUser = new MockEPUser(); + + @Test + public void findAllTest() { + List<Profile> profileList = new ArrayList<>(); + Mockito.when(dataAccessService.getList(Profile.class, null)).thenReturn(profileList); + List<Profile> expectedRoleList = epProfileServiceImpl.findAll(); + assertEquals(expectedRoleList, profileList); + } + + @Test(expected = java.lang.NumberFormatException.class) + public void getUserTest() { + EPUser epUser = new EPUser(); + Mockito.when(dataAccessService.getDomainObject(EPUser.class, Long.parseLong("test"), null)).thenReturn(epUser); + epProfileServiceImpl.getUser("test"); + } + + @Test + public void saveUserTest() { + EPUser user = mockUser.mockEPUser(); + Mockito.doNothing().when(dataAccessService).saveDomainObject(user, null); + epProfileServiceImpl.saveUser(user); + } + + @Test + public void getProfileTest() { + epProfileServiceImpl.getProfile(1); + + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImplTest.java index 66cfdd31..172b9421 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImplTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImplTest.java @@ -39,16 +39,29 @@ package org.onap.portalapp.portal.service; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.hibernate.SQLQuery; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.criterion.Criterion; +import org.hibernate.criterion.Restrictions; +import org.json.JSONObject; +import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -59,16 +72,30 @@ import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.onap.portalapp.portal.core.MockEPUser; import org.onap.portalapp.portal.domain.CentralV2RoleFunction; +import org.onap.portalapp.portal.domain.CentralizedApp; import org.onap.portalapp.portal.domain.EPApp; import org.onap.portalapp.portal.domain.EPAppRoleFunction; import org.onap.portalapp.portal.domain.EPRole; import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.domain.EPUserApp; import org.onap.portalapp.portal.exceptions.InactiveApplicationException; +import org.onap.portalapp.portal.exceptions.InvalidUserException; import org.onap.portalapp.portal.framework.MockitoTestSuite; +import org.onap.portalapp.portal.transport.BulkUploadRoleFunction; +import org.onap.portalapp.portal.transport.BulkUploadUserRoles; +import org.onap.portalapp.portal.transport.CentralRole; +import org.onap.portalapp.portal.transport.CentralUser; +import org.onap.portalapp.portal.transport.CentralV2Role; import org.onap.portalapp.portal.transport.EcompUserRoles; +import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator; +import org.onap.portalapp.portal.transport.GlobalRoleWithApplicationRoleFunction; +import org.onap.portalapp.portal.transport.LocalRole; import org.onap.portalapp.portal.utils.EPCommonSystemProperties; import org.onap.portalapp.portal.utils.EcompPortalUtils; +import org.onap.portalapp.portal.utils.PortalConstants; +import org.onap.portalapp.util.EPUserUtils; import org.onap.portalsdk.core.domain.Role; +import org.onap.portalsdk.core.domain.RoleFunction; import org.onap.portalsdk.core.restful.domain.EcompUser; import org.onap.portalsdk.core.service.DataAccessService; import org.onap.portalsdk.core.service.DataAccessServiceImpl; @@ -84,11 +111,14 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; +import com.fasterxml.jackson.databind.ObjectMapper; + @RunWith(PowerMockRunner.class) -@PrepareForTest({ EcompPortalUtils.class, SystemProperties.class, EPCommonSystemProperties.class }) +@PrepareForTest({ EcompPortalUtils.class, Criterion.class, Restrictions.class, SystemProperties.class, + EPCommonSystemProperties.class }) public class ExternalAccessRolesServiceImplTest { @Mock - DataAccessService dataAccessService1 = new DataAccessServiceImpl(); + DataAccessService dataAccessService = new DataAccessServiceImpl(); @Mock RestTemplate template = new RestTemplate(); @@ -96,11 +126,44 @@ public class ExternalAccessRolesServiceImplTest { @InjectMocks ExternalAccessRolesServiceImpl externalAccessRolesServiceImpl = new ExternalAccessRolesServiceImpl(); + @Mock + EPAppCommonServiceImpl epAppCommonServiceImpl = new EPAppCommonServiceImpl(); + + @Mock + SessionFactory sessionFactory; + + @Mock + Session session; + + @Mock + Transaction transaction; + @Before public void setup() { MockitoAnnotations.initMocks(this); + Mockito.when(sessionFactory.openSession()).thenReturn(session); + Mockito.when(session.beginTransaction()).thenReturn(transaction); + } + + @After + public void after() { + session.close(); } + private static final String APP_ROLE_NAME_PARAM = "appRoleName"; + + private static final String GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM = "getRoletoUpdateInExternalAuthSystem"; + + private static final String GET_PORTAL_APP_ROLES_QUERY = "getPortalAppRoles"; + + private static final String GET_ROLE_FUNCTION_QUERY = "getRoleFunction"; + + private static final String FUNCTION_CODE_PARAMS = "functionCode"; + + private static final String FUNCTION_PIPE = "|"; + + private static final String APP_ID = "appId"; + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); @@ -113,6 +176,8 @@ public class ExternalAccessRolesServiceImplTest { EPApp app = new EPApp(); app.setName("Test"); app.setImageUrl("test"); + app.setNameSpace("com.test.app"); + app.setCentralAuth(true); app.setDescription("test"); app.setNotes("test"); app.setUrl("test"); @@ -125,7 +190,7 @@ public class ExternalAccessRolesServiceImplTest { app.setUsername("test"); app.setAppPassword("test"); app.setOpen(false); - app.setEnabled(false); + app.setEnabled(true); app.setUebKey("test"); app.setUebSecret("test"); app.setUebTopicName("test"); @@ -133,38 +198,29 @@ public class ExternalAccessRolesServiceImplTest { return app; } + @SuppressWarnings("deprecation") @Test public void getAppRolesIfAppIsPortalTest() throws Exception { List<EPRole> applicationRoles = new ArrayList<>(); - Mockito.when(dataAccessService1.getList(EPRole.class, "test", null, null)).thenReturn(applicationRoles); + Mockito.when(dataAccessService.getList(EPRole.class, "test", null, null)).thenReturn(applicationRoles); List<EPRole> expectedApplicationRoles = externalAccessRolesServiceImpl.getAppRoles((long) 1); assertEquals(expectedApplicationRoles, applicationRoles); } + @SuppressWarnings("deprecation") @Test public void getAppRolesTest() throws Exception { List<EPRole> applicationRoles = new ArrayList<>(); - Mockito.when(dataAccessService1.getList(EPRole.class, "test", null, null)).thenReturn(applicationRoles); + Mockito.when(dataAccessService.getList(EPRole.class, "test", null, null)).thenReturn(applicationRoles); List<EPRole> expectedApplicationRoles = externalAccessRolesServiceImpl.getAppRoles((long) 10); assertEquals(expectedApplicationRoles, applicationRoles); } - // @SuppressWarnings("null") - // @Test(expected = java.lang.Exception.class) - // public void getAppRolesExceptionTest() throws Exception{ - // List<EPRole> applicationRoles = new ArrayList<>(); - // DataAccessService dataAccessService = null ; - // Mockito.when(dataAccessService.getList(EPRole.class, "where app_id = 10", - // null, null)).thenThrow(nullPointerException); - // List<EPRole> expectedApplicationRoles = - // externalAccessRolesServiceImpl.getAppRoles((long) 10); - // assertEquals(expectedApplicationRoles,applicationRoles); - // } - + @SuppressWarnings("deprecation") @Test public void getAppExceptionTest() throws Exception { List<EPApp> app = new ArrayList<>(); - Mockito.when(dataAccessService1.getList(EPApp.class, " where ueb_key = '" + uebKey + "'", null, null)) + Mockito.when(dataAccessService.getList(EPApp.class, " where ueb_key = '" + uebKey + "'", null, null)) .thenReturn(app); List<EPApp> expectedapp = externalAccessRolesServiceImpl.getApp(uebKey); assertEquals(app, expectedapp); @@ -174,11 +230,12 @@ public class ExternalAccessRolesServiceImplTest { public void getAppErrorTest() throws Exception { List<EPApp> appList = new ArrayList<>(); EPApp app = mockApp(); + app.setEnabled(false); appList.add(app); final Map<String, String> appUebkeyParams = new HashMap<>(); appUebkeyParams.put("appKey", "test-ueb-key"); - Mockito.when(dataAccessService1.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) - .thenReturn(appList); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); externalAccessRolesServiceImpl.getApp(uebKey); } @@ -190,7 +247,7 @@ public class ExternalAccessRolesServiceImplTest { appList.add(app); final Map<String, String> appUebkeyParams = new HashMap<>(); appUebkeyParams.put("appKey", "test-ueb-key"); - Mockito.when(dataAccessService1.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) .thenReturn(appList); List<EPApp> expectedapp = externalAccessRolesServiceImpl.getApp(uebKey); assertEquals(appList, expectedapp); @@ -218,12 +275,13 @@ public class ExternalAccessRolesServiceImplTest { roleList.add(ePRole); final Map<String, String> appUebkeyParams = new HashMap<>(); appUebkeyParams.put("appKey", "test-ueb-key"); - Mockito.when(dataAccessService1.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) .thenReturn(appList); final Map<String, Long> getPartnerAppRoleParams = new HashMap<>(); getPartnerAppRoleParams.put("appRoleId", role.getId()); - getPartnerAppRoleParams.put("appId", app.getId()); - Mockito.when(dataAccessService1.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null)).thenReturn(roleList); + getPartnerAppRoleParams.put("appId", app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null)) + .thenReturn(roleList); Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)) .thenReturn("Testurl"); ResponseEntity<String> addResponse = new ResponseEntity<>(HttpStatus.CREATED); @@ -233,7 +291,6 @@ public class ExternalAccessRolesServiceImplTest { assertTrue(externalAccessRolesServiceImpl.addRole(role, uebKey)); } - @Test public void addRoleMethodNotAllowedTest() throws Exception { HttpHeaders headers = new HttpHeaders(); @@ -255,12 +312,13 @@ public class ExternalAccessRolesServiceImplTest { roleList.add(ePRole); final Map<String, String> appUebkeyParams = new HashMap<>(); appUebkeyParams.put("appKey", "test-ueb-key"); - Mockito.when(dataAccessService1.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) .thenReturn(appList); final Map<String, Long> getPartnerAppRoleParams = new HashMap<>(); getPartnerAppRoleParams.put("appRoleId", role.getId()); - getPartnerAppRoleParams.put("appId", app.getId()); - Mockito.when(dataAccessService1.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null)).thenReturn(roleList); + getPartnerAppRoleParams.put("appId", app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null)) + .thenReturn(roleList); Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)) .thenReturn("Testurl"); ResponseEntity<String> addResponse = new ResponseEntity<>(HttpStatus.METHOD_NOT_ALLOWED); @@ -295,6 +353,9 @@ public class ExternalAccessRolesServiceImplTest { @Test public void deleteCentralRoleFunctionTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); final Map<String, String> params = new HashMap<>(); EPApp app = mockApp(); params.put("functionCode", "menu_fun_code"); @@ -303,20 +364,110 @@ public class ExternalAccessRolesServiceImplTest { CentralV2RoleFunction domainCentralRoleFunction = new CentralV2RoleFunction(); domainCentralRoleFunction.setCode("menu_fun_code"); centralRoleFunctionList.add(domainCentralRoleFunction); - Mockito.when(dataAccessService1.executeNamedQuery("getRoleFunction", params, null)) + Mockito.when(dataAccessService.executeNamedQuery("getRoleFunction", params, null)) .thenReturn(centralRoleFunctionList); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); ResponseEntity<String> addResponse = new ResponseEntity<>(HttpStatus.OK); Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(addResponse); HttpHeaders headers = new HttpHeaders(); - PowerMockito.mockStatic(EcompPortalUtils.class); Mockito.when(EcompPortalUtils.base64encodeKeyForAAFBasicAuth()).thenReturn(headers); - - Mockito.doNothing().when(dataAccessService1).deleteDomainObjects(EPAppRoleFunction.class, + Mockito.doNothing().when(dataAccessService).deleteDomainObjects(EPAppRoleFunction.class, "app_id = " + app.getId() + " and function_cd = '" + "menu_fun_code" + "'", null); - assertTrue(externalAccessRolesServiceImpl.deleteCentralRoleFunction("menu_fun_code", app)); } + + @Test + public void deleteRoleForApplicationTest() throws Exception { + EPApp app = mockApp(); + app.setId(2l); + List<EPApp> appList = new ArrayList<>(); + appList.add(app); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + final Map<String, String> deleteRoleParams = new HashMap<>(); + deleteRoleParams.put(APP_ROLE_NAME_PARAM, "test_delete"); + deleteRoleParams.put(APP_ID, String.valueOf(app.getId())); + List<EPRole> epRoleList = new ArrayList<>(); + EPRole epRole = new EPRole(); + epRole.setName("test_delete"); + epRole.setId(1l); + epRole.setActive(true); + epRole.setAppRoleId(11l); + epRoleList.add(epRole); + Mockito.when( + dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, deleteRoleParams, null)) + .thenReturn(epRoleList); + final Map<String, Long> appRoleFuncsParams = new HashMap<>(); + appRoleFuncsParams.put("appId", app.getId()); + appRoleFuncsParams.put("roleId", epRole.getId()); + List<EPAppRoleFunction> appRoleFunctionList = new ArrayList<>(); + EPAppRoleFunction epAppRoleFunction = new EPAppRoleFunction(); + epAppRoleFunction.setCode("test_code"); + epAppRoleFunction.setAppId(app.getId()); + epAppRoleFunction.setRoleAppId(null); + appRoleFunctionList.add(epAppRoleFunction); + Mockito.when( + dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null)) + .thenReturn(appRoleFunctionList); + SQLQuery SqlQuery = Mockito.mock(SQLQuery.class); + Mockito.when(session.createSQLQuery(Matchers.anyString())).thenReturn(SqlQuery); + PowerMockito.mockStatic(EcompPortalUtils.class); + ResponseEntity<String> getResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + ResponseEntity<String> DelResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(DelResponse); + assertTrue(externalAccessRolesServiceImpl.deleteRoleForApplication(epRole.getName(), app.getUebKey())); + } + + @Test + public void deleteRoleForPortalApplicationTest() throws Exception { + EPApp app = mockApp(); + app.setId(1l); + List<EPApp> appList = new ArrayList<>(); + appList.add(app); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + final Map<String, String> deleteRoleParams2 = new HashMap<>(); + deleteRoleParams2.put(APP_ROLE_NAME_PARAM, "test_delete"); + List<EPRole> epRoleList2 = new ArrayList<>(); + EPRole epRole = new EPRole(); + epRole.setName("test_delete"); + epRole.setId(1l); + epRole.setActive(true); + epRoleList2.add(epRole); + Mockito.when(dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, deleteRoleParams2, null)) + .thenReturn(epRoleList2); + final Map<String, Long> appRoleFuncsParams = new HashMap<>(); + appRoleFuncsParams.put("appId", app.getId()); + appRoleFuncsParams.put("roleId", epRole.getId()); + List<EPAppRoleFunction> appRoleFunctionList = new ArrayList<>(); + EPAppRoleFunction epAppRoleFunction = new EPAppRoleFunction(); + epAppRoleFunction.setCode("test_code"); + epAppRoleFunction.setAppId(app.getId()); + epAppRoleFunction.setRoleAppId(null); + appRoleFunctionList.add(epAppRoleFunction); + Mockito.when( + dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null)) + .thenReturn(appRoleFunctionList); + SQLQuery SqlQuery = Mockito.mock(SQLQuery.class); + Mockito.when(session.createSQLQuery(Matchers.anyString())).thenReturn(SqlQuery); + PowerMockito.mockStatic(EcompPortalUtils.class); + ResponseEntity<String> getResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + ResponseEntity<String> DelResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(DelResponse); + assertTrue(externalAccessRolesServiceImpl.deleteRoleForApplication(epRole.getName(), app.getUebKey())); + } + @Test public void deleteCentralRoleFunctionFailTest() throws Exception { final Map<String, String> params = new HashMap<>(); @@ -328,16 +479,14 @@ public class ExternalAccessRolesServiceImplTest { domainCentralRoleFunction.setCode("menu_fun_code"); centralRoleFunctionList.add(domainCentralRoleFunction); HttpClientErrorException httpClientErrorException = new HttpClientErrorException(HttpStatus.NOT_FOUND); - Mockito.when(dataAccessService1.executeNamedQuery("getRoleFunction", params, null)) + Mockito.when(dataAccessService.executeNamedQuery("getRoleFunction", params, null)) .thenReturn(centralRoleFunctionList); - ResponseEntity<String> addResponse = new ResponseEntity<>(HttpStatus.NOT_FOUND); Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenThrow(httpClientErrorException); HttpHeaders headers = new HttpHeaders(); PowerMockito.mockStatic(EcompPortalUtils.class); Mockito.when(EcompPortalUtils.base64encodeKeyForAAFBasicAuth()).thenReturn(headers); - - Mockito.doNothing().when(dataAccessService1).deleteDomainObjects(EPAppRoleFunction.class, + Mockito.doNothing().when(dataAccessService).deleteDomainObjects(EPAppRoleFunction.class, "app_id = " + app.getId() + " and function_cd = '" + "menu_fun_code" + "'", null); boolean returnedValue = externalAccessRolesServiceImpl.deleteCentralRoleFunction("menu_fun_code", app); @@ -354,71 +503,233 @@ public class ExternalAccessRolesServiceImplTest { CentralV2RoleFunction domainCentralRoleFunction = new CentralV2RoleFunction(); domainCentralRoleFunction.setCode("menu_fun_code"); centralRoleFunctionList.add(domainCentralRoleFunction); - Mockito.when(dataAccessService1.executeNamedQuery("getAppFunctionDetails", params, null)) + Mockito.when(dataAccessService.executeNamedQuery("getAppFunctionDetails", params, null)) .thenThrow(nullPointerException); assertTrue(externalAccessRolesServiceImpl.deleteCentralRoleFunction("menu_fun_code", app)); } @Test - public void getUserTest() { + public void getRoleFunctionTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(SystemProperties.class); + EPApp app = mockApp(); + List<EPApp> appList = new ArrayList<>(); + appList.add(app); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + Mockito.when(EcompPortalUtils.getFunctionCode("test_type|type_code|*")).thenReturn("type_code"); + Mockito.when(EcompPortalUtils.getFunctionType("test_type|type_code|*")).thenReturn("test_type"); + Mockito.when(EcompPortalUtils.getFunctionAction("test_type|type_code|*")).thenReturn("*"); + List<CentralV2RoleFunction> getRoleFuncList = new ArrayList<>(); + CentralV2RoleFunction getCenRole = new CentralV2RoleFunction("test_type|type_code|*", "test_name"); + getRoleFuncList.add(getCenRole); + final Map<String, String> params = new HashMap<>(); + params.put(FUNCTION_CODE_PARAMS, "test_type|type_code|*"); + params.put(APP_ID, String.valueOf(app.getId())); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null)) + .thenReturn(getRoleFuncList); + CentralV2RoleFunction actual = externalAccessRolesServiceImpl.getRoleFunction("test_type|type_code|*", + app.getUebKey()); + assertEquals(getCenRole.getCode(), actual.getCode()); + } + + @Test + public void getRoleFunctionMutilpleFilterTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(SystemProperties.class); + EPApp app = mockApp(); + List<EPApp> appList = new ArrayList<>(); + appList.add(app); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + CentralV2RoleFunction expected = new CentralV2RoleFunction(null, "type_code", "test_name", null, "test_type", + "*", null); + Mockito.when(EcompPortalUtils.getFunctionCode("test_type|type_code|*")).thenReturn("type_code"); + Mockito.when(EcompPortalUtils.getFunctionCode("test_type_1|type_code_1|*")).thenReturn("type_code_1"); + Mockito.when(EcompPortalUtils.getFunctionType("test_type|type_code|*")).thenReturn("test_type"); + Mockito.when(EcompPortalUtils.getFunctionAction("test_type|type_code|*")).thenReturn("*"); + List<CentralV2RoleFunction> getRoleFuncList = new ArrayList<>(); + CentralV2RoleFunction getCenRole = new CentralV2RoleFunction("test_type|type_code|*", "test_name"); + CentralV2RoleFunction getCenRole2 = new CentralV2RoleFunction("test_type_1|type_code_1|*", "test_name_1"); + getRoleFuncList.add(getCenRole); + getRoleFuncList.add(getCenRole2); + final Map<String, String> params = new HashMap<>(); + params.put(FUNCTION_CODE_PARAMS, "test_type|type_code|*"); + params.put(APP_ID, String.valueOf(app.getId())); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null)) + .thenReturn(getRoleFuncList); + CentralV2RoleFunction actual = externalAccessRolesServiceImpl.getRoleFunction("test_type|type_code|*", + app.getUebKey()); + assertEquals(expected.getCode(), actual.getCode()); + } + + @Test + public void getUserTest() throws InvalidUserException { List<EPUser> userList = new ArrayList<>(); EPUser user = mockUser.mockEPUser(); userList.add(user); final Map<String, String> userParams = new HashMap<>(); userParams.put("org_user_id", "guestT"); - Mockito.when(dataAccessService1.executeNamedQuery("getEPUserByOrgUserId", userParams, null)) + Mockito.when(dataAccessService.executeNamedQuery("getEPUserByOrgUserId", userParams, null)) .thenReturn(userList); List<EPUser> expectedUserList = externalAccessRolesServiceImpl.getUser("guestT"); assertEquals(expectedUserList, userList); } - - - public void saveCentralRoleFunctionTest() throws Exception { + + @Test + public void getV2UserWithRolesTest() throws Exception { + EPApp app = mockApp(); + app.setId(2l); + EPUser user = mockUser.mockEPUser(); + List<EPApp> appList = new ArrayList<>(); + appList.add(app); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + final Map<String, String> userParams = new HashMap<>(); + userParams.put("org_user_id", user.getOrgUserId()); + List<EPUser> userList = new ArrayList<>(); + Set<EPUserApp> userAppSet = user.getEPUserApps(); + EPUserApp epUserApp = new EPUserApp(); + EPRole epRole = new EPRole(); + epRole.setName("test"); + epRole.setId(1l); + epRole.setActive(true); + epRole.setAppRoleId(11l); + epUserApp.setApp(app); + epUserApp.setUserId(user.getId()); + epUserApp.setRole(epRole); + userAppSet.add(epUserApp); + user.setUserApps(userAppSet); + userList.add(user); + Mockito.when(dataAccessService.executeNamedQuery("getEPUserByOrgUserId", userParams, null)) + .thenReturn(userList); + final Map<String, Long> params = new HashMap<>(); + List<CentralV2RoleFunction> appRoleFunctionList = new ArrayList<>(); CentralV2RoleFunction centralV2RoleFunction = new CentralV2RoleFunction(); - centralV2RoleFunction.setCode("menu_test"); + centralV2RoleFunction.setCode("test_type|test_code|*"); + centralV2RoleFunction.setName("test name"); + centralV2RoleFunction.setAppId(app.getId()); + appRoleFunctionList.add(centralV2RoleFunction); + params.put("roleId", epUserApp.getRole().getId()); + params.put(APP_ID, epUserApp.getApp().getId()); + Mockito.when(dataAccessService.executeNamedQuery("getAppRoleFunctionList", params, null)) + .thenReturn(appRoleFunctionList); + String actual = externalAccessRolesServiceImpl.getV2UserWithRoles(user.getOrgUserId(), app.getUebKey()); + String notExpected = ""; + assertNotEquals(actual, notExpected); + } + + @Test + public void saveCentralRoleFunctionNewTestForV2() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); EPApp app = mockApp(); app.setId((long) 1); + CentralV2RoleFunction centralV2RoleFunction = new CentralV2RoleFunction(); + centralV2RoleFunction.setCode("test_code"); + centralV2RoleFunction.setName("test name"); + centralV2RoleFunction.setAppId(app.getId()); + centralV2RoleFunction.setAction("*"); + centralV2RoleFunction.setType("test_type"); final Map<String, String> params = new HashMap<>(); - params.put("functionCd", "menu_test"); params.put("appId", String.valueOf(1)); + + List<CentralV2RoleFunction> appRoleFunc = new ArrayList<>(); + appRoleFunc.add(centralV2RoleFunction); + params.put(FUNCTION_CODE_PARAMS, centralV2RoleFunction.getType() + FUNCTION_PIPE + + centralV2RoleFunction.getCode() + FUNCTION_PIPE + centralV2RoleFunction.getAction()); + Mockito.when(dataAccessService.executeNamedQuery("getRoleFunction", params, null)).thenReturn(appRoleFunc); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + HttpHeaders headers = new HttpHeaders(); + Mockito.when(EcompPortalUtils.base64encodeKeyForAAFBasicAuth()).thenReturn(headers); + JSONObject mockJsonObjectPerm = new JSONObject(); + JSONObject mockJsonObjectFinalPerm = new JSONObject(); + mockJsonObjectPerm.put("type", "com.test.app.test_type"); + mockJsonObjectPerm.put("instance", "com.test.app.test_code"); + mockJsonObjectPerm.put("action", "*"); + mockJsonObjectPerm.put("description", "test name"); + List<JSONObject> mockJson = new ArrayList<>(); + mockJson.add(mockJsonObjectPerm); + mockJsonObjectFinalPerm.put("perm", mockJson); + ResponseEntity<String> getResponse = new ResponseEntity<>(mockJsonObjectFinalPerm.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + ResponseEntity<String> updateResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(updateResponse); + Boolean actual = externalAccessRolesServiceImpl.saveCentralRoleFunction(centralV2RoleFunction, app); + assertEquals(true, actual); + } + + @Test + public void saveCentralRoleFunctionUpdateForV2Test() throws Exception { PowerMockito.mockStatic(EcompPortalUtils.class); + EPApp app = mockApp(); + app.setId((long) 1); + CentralV2RoleFunction centralV2RoleFunction = new CentralV2RoleFunction(); + centralV2RoleFunction.setCode("test_code"); + centralV2RoleFunction.setName("test name2"); + centralV2RoleFunction.setAppId(app.getId()); + centralV2RoleFunction.setAction("*"); + centralV2RoleFunction.setType("test_type"); + CentralV2RoleFunction centralV2RoleFunctionExisting = new CentralV2RoleFunction(); + centralV2RoleFunctionExisting.setCode("test_code"); + centralV2RoleFunctionExisting.setName("test name"); + centralV2RoleFunctionExisting.setAppId(app.getId()); + centralV2RoleFunctionExisting.setAction("*"); + centralV2RoleFunctionExisting.setType("test_type"); + final Map<String, String> params = new HashMap<>(); + params.put("appId", String.valueOf(1)); + List<CentralV2RoleFunction> appRoleFunc = new ArrayList<>(); + appRoleFunc.add(centralV2RoleFunctionExisting); + params.put(FUNCTION_CODE_PARAMS, centralV2RoleFunction.getType() + FUNCTION_PIPE + + centralV2RoleFunction.getCode() + FUNCTION_PIPE + centralV2RoleFunction.getAction()); + Mockito.when(dataAccessService.executeNamedQuery("getRoleFunction", params, null)).thenReturn(appRoleFunc); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); HttpHeaders headers = new HttpHeaders(); Mockito.when(EcompPortalUtils.base64encodeKeyForAAFBasicAuth()).thenReturn(headers); - List<CentralV2RoleFunction> appRoleFunc = new ArrayList<>(); - appRoleFunc.add(centralV2RoleFunction); - Mockito.when(dataAccessService1.executeNamedQuery("getAppFunctionDetails", params, - null)).thenReturn(appRoleFunc); - ResponseEntity<String> addResponse = new ResponseEntity<>(HttpStatus.OK); + JSONObject mockJsonObjectPerm = new JSONObject(); + JSONObject mockJsonObjectFinalPerm = new JSONObject(); + mockJsonObjectPerm.put("type", "com.test.app.test_type"); + mockJsonObjectPerm.put("instance", "test_code"); + mockJsonObjectPerm.put("action", "*"); + mockJsonObjectPerm.put("description", "test name"); + List<JSONObject> mockJson = new ArrayList<>(); + mockJson.add(mockJsonObjectPerm); + mockJsonObjectFinalPerm.put("perm", mockJson); + ResponseEntity<String> getResponse = new ResponseEntity<>(mockJsonObjectFinalPerm.toString(), HttpStatus.OK); Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(addResponse); + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + ResponseEntity<String> updateResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.PUT), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(updateResponse); + Boolean actual = externalAccessRolesServiceImpl.saveCentralRoleFunction(centralV2RoleFunction, app); + assertEquals(true, actual); } - -// @Test -// public void getAllAppUsersIfAppIsPortalTest() throws Exception -// { -// List<EPApp> expectedapps = new ArrayList<>(); -// EPApp app = new EPApp(); -// app.setEnabled(true); -// app.setId((long) 1); -// expectedapps.add(app); -// List<EPRole> applicationRoles = new ArrayList<>(); -// Mockito.when(dataAccessService1.getList(EPRole.class, "test", null, null)).thenReturn(applicationRoles); -// Mockito.when(dataAccessService1.getList(EPApp.class, " where ueb_key = '" + uebKey + "'", null, null)).thenReturn(expectedapps); -// externalAccessRolesServiceImpl.getAllAppUsers(uebKey); -// } - - - @Test(expected = IndexOutOfBoundsException.class) - public void getAllAppUsersTest() throws Exception - { - List<EPApp> expectedapps = new ArrayList<>(); + + @SuppressWarnings("deprecation") + @Test + public void getAllAppUsersTest() throws Exception { EPApp app = new EPApp(); app.setEnabled(true); app.setId((long) 10); - expectedapps.add(app); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); List<EPRole> applicationRoles = new ArrayList<>(); - Mockito.when(dataAccessService1.getList(EPRole.class, "test", null, null)).thenReturn(applicationRoles); - Mockito.when(dataAccessService1.getList(EPApp.class, " where ueb_key = '" + uebKey + "'", null, null)).thenReturn(expectedapps); + Mockito.when(dataAccessService.getList(EPRole.class, "test", null, null)).thenReturn(applicationRoles); + Mockito.when(dataAccessService.getList(EPApp.class, " where ueb_key = '" + uebKey + "'", null, null)) + .thenReturn(appList); final Map<String, Long> appParams = new HashMap<>(); appParams.put("appId", app.getId()); List<EcompUserRoles> userList = new ArrayList<>(); @@ -426,31 +737,1648 @@ public class ExternalAccessRolesServiceImplTest { ecompUserRoles.setOrgUserId("guestT"); ecompUserRoles.setRoleId((long) 1); ecompUserRoles.setRoleName("test"); - EcompUserRoles ecompUserRoles2 = new EcompUserRoles(); ecompUserRoles2.setOrgUserId("guestT"); ecompUserRoles2.setRoleId((long) 2); ecompUserRoles2.setRoleName("test new"); userList.add(ecompUserRoles); userList.add(ecompUserRoles2); - - Mockito.when(dataAccessService1.executeNamedQuery("ApplicationUserRoles", appParams, null)).thenReturn(userList); - List<EcompUser> usersfinalList = externalAccessRolesServiceImpl.getAllAppUsers(uebKey); + Mockito.when(dataAccessService.executeNamedQuery("ApplicationUserRoles", appParams, null)).thenReturn(userList); + List<EcompUser> usersfinalList = externalAccessRolesServiceImpl.getAllAppUsers(app.getUebKey()); assertEquals(usersfinalList.get(0).getRoles().size(), 2); } - + @Test - public void getGlobalRolesOfPortalTest() - { - Mockito.when(dataAccessService1.executeNamedQuery("getGlobalRolesOfPortal", null, null)).thenReturn(null); + public void getGlobalRolesOfPortalTest() { + Mockito.when(dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null)).thenReturn(null); assertEquals(externalAccessRolesServiceImpl.getGlobalRolesOfPortal(), null); } - + @Test - public void getGlobalRolesOfPortalExceptionTest() - { + public void getGlobalRolesOfPortalExceptionTest() { List<EPRole> globalRoles = new ArrayList<>(); - Mockito.when(dataAccessService1.executeNamedQuery("getGlobalRolesOfPortal", null, null)).thenThrow(nullPointerException); + Mockito.when(dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null)) + .thenThrow(nullPointerException); assertEquals(externalAccessRolesServiceImpl.getGlobalRolesOfPortal(), globalRoles); } + + @Test + public void getRolesForAppTest() throws Exception { + EPApp app = mockApp(); + app.setId(2l); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<EPRole> applicationRoles = new ArrayList<>(); + EPRole appRole = new EPRole(); + appRole.setActive(true); + appRole.setAppId(app.getId()); + appRole.setAppRoleId(100l); + appRole.setId(10l); + appRole.setName("test"); + applicationRoles.add(appRole); + final Map<String, Long> appParams = new HashMap<>(); + appParams.put("appId", app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null)) + .thenReturn(applicationRoles); + List<CentralV2RoleFunction> cenRoleFuncList = new ArrayList<>(); + CentralV2RoleFunction v2RoleFunction = new CentralV2RoleFunction(); + v2RoleFunction.setAppId(app.getId()); + v2RoleFunction.setCode("test_type|test_code|*"); + v2RoleFunction.setName("test name"); + cenRoleFuncList.add(v2RoleFunction); + final Map<String, Long> params = new HashMap<>(); + params.put("roleId", appRole.getId()); + params.put(APP_ID, appList.get(0).getId()); + Mockito.when(dataAccessService.executeNamedQuery("getAppRoleFunctionList", params, null)) + .thenReturn(cenRoleFuncList); + List<GlobalRoleWithApplicationRoleFunction> mockGlobalRoles = new ArrayList<>(); + GlobalRoleWithApplicationRoleFunction mockGlobalRole = new GlobalRoleWithApplicationRoleFunction(); + mockGlobalRole.setActive(true); + mockGlobalRole.setAppId(app.getId()); + mockGlobalRole.setRoleId(1111l); + mockGlobalRole.setRoleName("global_test"); + mockGlobalRole.setFunctionCd("test_type|test_code|*"); + mockGlobalRole.setFunctionName("test name"); + mockGlobalRoles.add(mockGlobalRole); + Map<String, Long> params2 = new HashMap<>(); + params2.put("appId", app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getGlobalRoleWithApplicationRoleFunctions", params2, null)) + .thenReturn(mockGlobalRoles); + List<EPRole> globalRoles = new ArrayList<>(); + EPRole globalRole = new EPRole(); + globalRole.setName("global_test"); + globalRole.setId(1111l); + globalRole.setActive(true); + globalRoles.add(globalRole); + Mockito.when(dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null)).thenReturn(globalRoles); + List<CentralV2Role> expected = new ArrayList<>(); + CentralV2Role cenV2Role = new CentralV2Role(); + CentralV2Role cenV2Role2 = new CentralV2Role(); + expected.add(cenV2Role); + expected.add(cenV2Role2); + List<CentralV2Role> actual = externalAccessRolesServiceImpl.getRolesForApp(app.getUebKey()); + assertEquals(expected.size(), actual.size()); + } + + @Test + public void getRoleFuncListTest() throws Exception { + EPApp app = mockApp(); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + final Map<String, Long> params = new HashMap<>(); + params.put(APP_ID, app.getId()); + List<CentralV2RoleFunction> expected = new ArrayList<>(); + CentralV2RoleFunction centralV2RoleFunction = new CentralV2RoleFunction("test_type|type_code|*", "test_name"); + expected.add(centralV2RoleFunction); + Mockito.when(dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null)).thenReturn(expected); + List<CentralV2RoleFunction> actual = externalAccessRolesServiceImpl.getRoleFuncList(app.getUebKey()); + assertEquals(expected, actual); + } + + @Test + public void getRoleInfoTest() throws Exception { + EPApp app = mockApp(); + app.setId(2l); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<EPRole> globalRoles = new ArrayList<>(); + EPRole globalRole = new EPRole(); + globalRole.setName("global_test"); + globalRole.setId(2l); + globalRole.setActive(true); + globalRoles.add(globalRole); + Mockito.when(dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null)).thenReturn(globalRoles); + List<GlobalRoleWithApplicationRoleFunction> mockGlobalRoles = new ArrayList<>(); + GlobalRoleWithApplicationRoleFunction mockGlobalRole = new GlobalRoleWithApplicationRoleFunction(); + mockGlobalRole.setActive(true); + mockGlobalRole.setAppId(app.getId()); + mockGlobalRole.setRoleId(2l); + mockGlobalRole.setRoleName("global_test"); + mockGlobalRole.setFunctionCd("test_type|test_code|*"); + mockGlobalRole.setFunctionName("test name"); + mockGlobalRoles.add(mockGlobalRole); + Map<String, Long> params = new HashMap<>(); + params.put("roleId", 2l); + params.put("requestedAppId", 2l); + Mockito.when(dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp", params, null)) + .thenReturn(mockGlobalRoles); + CentralV2Role actual = externalAccessRolesServiceImpl.getRoleInfo(2l, app.getUebKey()); + assertNotEquals(null, actual); + } + + @Test + public void getPartnerRoleInfoTest() throws Exception { + EPApp app = mockApp(); + app.setId(2l); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<EPRole> applicationRoles = new ArrayList<>(); + EPRole appRole = new EPRole(); + appRole.setActive(true); + appRole.setAppId(app.getId()); + appRole.setAppRoleId(100l); + appRole.setId(10l); + appRole.setName("test"); + applicationRoles.add(appRole); + final Map<String, Long> getPartnerAppRoleParams = new HashMap<>(); + getPartnerAppRoleParams.put("appRoleId", 10l); + getPartnerAppRoleParams.put("appId", app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null)) + .thenReturn(applicationRoles); + final Map<String, Long> params = new HashMap<>(); + params.put("roleId", appRole.getId()); + params.put(APP_ID, app.getId()); + List<CentralV2RoleFunction> cenRoleFuncList = new ArrayList<>(); + CentralV2RoleFunction centralV2RoleFunction = new CentralV2RoleFunction("test_type|type_code|*", "test_name"); + cenRoleFuncList.add(centralV2RoleFunction); + Mockito.when(dataAccessService.executeNamedQuery("getAppRoleFunctionList", params, null)) + .thenReturn(cenRoleFuncList); + CentralV2Role actual = externalAccessRolesServiceImpl.getRoleInfo(10l, app.getUebKey()); + assertNotEquals(null, actual); + } + + @Test + public void saveRoleForPortalApplicationNewTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + EPApp app = mockApp(); + app.setId(1l); + Role addRoleTest = new Role(); + addRoleTest.setActive(true); + addRoleTest.setName("Test"); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + HttpHeaders headers = new HttpHeaders(); + JSONObject mockJsonObjectRole = new JSONObject(); + Mockito.when(EcompPortalUtils.base64encodeKeyForAAFBasicAuth()).thenReturn(headers); + ResponseEntity<String> getResponse = new ResponseEntity<>(mockJsonObjectRole.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + final Map<String, String> epAppPortalRoleParams = new HashMap<>(); + epAppPortalRoleParams.put(APP_ROLE_NAME_PARAM, addRoleTest.getName()); + List<EPRole> getRoleCreated = new ArrayList<>(); + EPRole roleCreate = new EPRole(); + roleCreate.setActive(true); + roleCreate.setId(10l); + roleCreate.setName("test"); + getRoleCreated.add(roleCreate); + Mockito.when(dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, epAppPortalRoleParams, null)) + .thenReturn(getRoleCreated); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + ResponseEntity<String> addResponse = new ResponseEntity<>(HttpStatus.CREATED); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(addResponse); + ExternalRequestFieldsValidator actual = externalAccessRolesServiceImpl.saveRoleForApplication(addRoleTest, + app.getUebKey()); + ExternalRequestFieldsValidator expected = new ExternalRequestFieldsValidator(true, ""); + assertEquals(expected, actual); + } + + @Test + public void saveRoleForPortalApplicationUpdateTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + EPApp app = mockApp(); + app.setId(1l); + Role addRoleTest = new Role(); + SortedSet<RoleFunction> roleFuncSet = new TreeSet<>(); + RoleFunction roleFunc = new RoleFunction(); + roleFunc.setName("Test Name"); + roleFunc.setCode("test_type|test_instance|*"); + RoleFunction roleFunc2 = new RoleFunction(); + roleFunc2.setName("Test Name3"); + roleFunc2.setCode("test_type3|test_instance3|*"); + roleFuncSet.add(roleFunc); + roleFuncSet.add(roleFunc2); + addRoleTest.setActive(true); + addRoleTest.setName("Test2"); + addRoleTest.setId(2l); + addRoleTest.setRoleFunctions(roleFuncSet); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<EPRole> globalRoles = new ArrayList<>(); + EPRole globalRole = new EPRole(); + globalRole.setName("global_test"); + globalRole.setId(1111l); + globalRole.setActive(true); + globalRoles.add(globalRole); + Mockito.when(dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null)).thenReturn(globalRoles); + List<EPRole> epRoleList = new ArrayList<>(); + EPRole getEPRole = new EPRole(); + getEPRole.setName("Test"); + getEPRole.setId(2l); + getEPRole.setActive(true); + epRoleList.add(getEPRole); + final Map<String, Long> getPortalAppRoleParams = new HashMap<>(); + getPortalAppRoleParams.put("roleId", addRoleTest.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPortalAppRoleByRoleId", getPortalAppRoleParams, null)) + .thenReturn(epRoleList); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + HttpHeaders headers = new HttpHeaders(); + Mockito.when(EcompPortalUtils.base64encodeKeyForAAFBasicAuth()).thenReturn(headers); + JSONObject mockJsonObjectRole = new JSONObject(); + JSONObject mockJsonObjectFinalRole = new JSONObject(); + JSONObject mockJsonObjectPerm1 = new JSONObject(); + JSONObject mockJsonObjectPerm2 = new JSONObject(); + mockJsonObjectPerm1.put("type", "com.test.app.test_type"); + mockJsonObjectPerm1.put("instance", "test_instance"); + mockJsonObjectPerm1.put("action", "*"); + mockJsonObjectPerm2.put("type", "com.test.app.test_type2"); + mockJsonObjectPerm2.put("instance", "test_instance2"); + mockJsonObjectPerm2.put("action", "*"); + List<JSONObject> permsList = new ArrayList<>(); + permsList.add(mockJsonObjectPerm1); + permsList.add(mockJsonObjectPerm2); + mockJsonObjectRole.put("name", "com.test.app.Test"); + mockJsonObjectRole.put("perms", permsList); + mockJsonObjectRole.put("description", + "{\"id\":\"2\",\"name\":\"Test\",\"active\":\"true\",\"priority\":\"null\",\"appId\":\"null\",\"appRoleId\":\"null\"}"); + List<JSONObject> roleList = new ArrayList<>(); + roleList.add(mockJsonObjectRole); + mockJsonObjectFinalRole.put("role", roleList); + ResponseEntity<String> getResponse = new ResponseEntity<>(mockJsonObjectFinalRole.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + ResponseEntity<String> delResponse = new ResponseEntity<>(roleList.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(delResponse); + ResponseEntity<String> addRoleResponse = new ResponseEntity<>(HttpStatus.CREATED); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(addRoleResponse); + final Map<String, String> params = new HashMap<>(); + params.put("uebKey", app.getUebKey()); + params.put("roleId", String.valueOf(getEPRole.getId())); + List<BulkUploadUserRoles> userRolesList = new ArrayList<>(); + BulkUploadUserRoles bulkUploadUserRoles = new BulkUploadUserRoles(); + bulkUploadUserRoles.setAppNameSpace("com.test.app"); + bulkUploadUserRoles.setOrgUserId("guestT"); + bulkUploadUserRoles.setRoleName("Test2"); + userRolesList.add(bulkUploadUserRoles); + Mockito.when(dataAccessService.executeNamedQuery("getBulkUsersForSingleRole", params, null)) + .thenReturn(userRolesList); + Mockito.when( + EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn(true); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn("@test.com"); + ResponseEntity<String> mockBulkUsersUpload = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(mockBulkUsersUpload); + List<EPAppRoleFunction> appRoleFunctionList = new ArrayList<>(); + final Map<String, Long> appRoleFuncsParams = new HashMap<>(); + appRoleFuncsParams.put("appId", app.getId()); + appRoleFuncsParams.put("roleId", getEPRole.getId()); + Mockito.when( + dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null)) + .thenReturn(appRoleFunctionList); + Mockito.when(EcompPortalUtils.getFunctionCode(roleFunc.getCode())).thenReturn("test_instance"); + Mockito.when(EcompPortalUtils.getFunctionCode(roleFunc2.getCode())).thenReturn("test_instance3"); + final Map<String, String> getAppFunctionParams = new HashMap<>(); + getAppFunctionParams.put("appId", String.valueOf(app.getId())); + getAppFunctionParams.put(FUNCTION_CODE_PARAMS, roleFunc.getCode()); + List<CentralV2RoleFunction> v2RoleFunction = new ArrayList<>(); + CentralV2RoleFunction v2RoleFunction1 = new CentralV2RoleFunction("test_type|test_instance|*", "Test Name"); + v2RoleFunction.add(v2RoleFunction1); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null)) + .thenReturn(v2RoleFunction); + final Map<String, String> getAppFunctionParams2 = new HashMap<>(); + getAppFunctionParams2.put("appId", String.valueOf(app.getId())); + getAppFunctionParams2.put(FUNCTION_CODE_PARAMS, roleFunc2.getCode()); + List<CentralV2RoleFunction> v2RoleFunction2 = new ArrayList<>(); + CentralV2RoleFunction v2RoleFunction3 = new CentralV2RoleFunction("test_type3|test_instance3|*", "Test Name3"); + v2RoleFunction2.add(v2RoleFunction3); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams2, null)) + .thenReturn(v2RoleFunction2); + ExternalRequestFieldsValidator actual = externalAccessRolesServiceImpl.saveRoleForApplication(addRoleTest, + app.getUebKey()); + ExternalRequestFieldsValidator expected = new ExternalRequestFieldsValidator(true, ""); + assertEquals(expected, actual); + } + + @Test + public void saveRoleExitsInDbButNotInExtAuthSystemTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + EPApp app = mockApp(); + app.setId(1l); + Role addRoleTest = new Role(); + SortedSet<RoleFunction> roleFuncSet = new TreeSet<>(); + RoleFunction roleFunc = new RoleFunction(); + roleFunc.setName("Test Name"); + roleFunc.setCode("test_type|test_instance|*"); + RoleFunction roleFunc2 = new RoleFunction(); + roleFunc2.setName("Test Name3"); + roleFunc2.setCode("test_type3|test_instance3|*"); + roleFuncSet.add(roleFunc); + roleFuncSet.add(roleFunc2); + addRoleTest.setActive(true); + addRoleTest.setName("Test2"); + addRoleTest.setId(2l); + addRoleTest.setRoleFunctions(roleFuncSet); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<EPRole> globalRoles = new ArrayList<>(); + EPRole globalRole = new EPRole(); + globalRole.setName("global_test"); + globalRole.setId(1111l); + globalRole.setActive(true); + globalRoles.add(globalRole); + Mockito.when(dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null)).thenReturn(globalRoles); + List<EPRole> epRoleList = new ArrayList<>(); + EPRole getEPRole = new EPRole(); + getEPRole.setName("Test"); + getEPRole.setId(2l); + getEPRole.setActive(true); + epRoleList.add(getEPRole); + final Map<String, Long> getPortalAppRoleParams = new HashMap<>(); + getPortalAppRoleParams.put("roleId", addRoleTest.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPortalAppRoleByRoleId", getPortalAppRoleParams, null)) + .thenReturn(epRoleList); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + HttpHeaders headers = new HttpHeaders(); + Mockito.when(EcompPortalUtils.base64encodeKeyForAAFBasicAuth()).thenReturn(headers); + JSONObject mockJsonObjectFinalRole = new JSONObject(); + ResponseEntity<String> getResponse = new ResponseEntity<>(mockJsonObjectFinalRole.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + ResponseEntity<String> addRoleResponse = new ResponseEntity<>(HttpStatus.CREATED); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(addRoleResponse); + final Map<String, String> params = new HashMap<>(); + params.put("uebKey", app.getUebKey()); + params.put("roleId", String.valueOf(getEPRole.getId())); + List<BulkUploadUserRoles> userRolesList = new ArrayList<>(); + BulkUploadUserRoles bulkUploadUserRoles = new BulkUploadUserRoles(); + bulkUploadUserRoles.setAppNameSpace("com.test.app"); + bulkUploadUserRoles.setOrgUserId("guestT"); + bulkUploadUserRoles.setRoleName("Test2"); + userRolesList.add(bulkUploadUserRoles); + Mockito.when(dataAccessService.executeNamedQuery("getBulkUsersForSingleRole", params, null)) + .thenReturn(userRolesList); + Mockito.when( + EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn(true); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn("@test.com"); + List<EPAppRoleFunction> appRoleFunctionList = new ArrayList<>(); + final Map<String, Long> appRoleFuncsParams = new HashMap<>(); + appRoleFuncsParams.put("appId", app.getId()); + appRoleFuncsParams.put("roleId", getEPRole.getId()); + Mockito.when( + dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null)) + .thenReturn(appRoleFunctionList); + Mockito.when(EcompPortalUtils.getFunctionCode(roleFunc.getCode())).thenReturn("test_instance"); + Mockito.when(EcompPortalUtils.getFunctionCode(roleFunc2.getCode())).thenReturn("test_instance3"); + final Map<String, String> getAppFunctionParams = new HashMap<>(); + getAppFunctionParams.put("appId", String.valueOf(app.getId())); + getAppFunctionParams.put(FUNCTION_CODE_PARAMS, roleFunc.getCode()); + List<CentralV2RoleFunction> v2RoleFunction = new ArrayList<>(); + CentralV2RoleFunction v2RoleFunction1 = new CentralV2RoleFunction("test_type|test_instance|*", "Test Name"); + v2RoleFunction.add(v2RoleFunction1); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null)) + .thenReturn(v2RoleFunction); + final Map<String, String> getAppFunctionParams2 = new HashMap<>(); + getAppFunctionParams2.put("appId", String.valueOf(app.getId())); + getAppFunctionParams2.put(FUNCTION_CODE_PARAMS, roleFunc2.getCode()); + List<CentralV2RoleFunction> v2RoleFunction2 = new ArrayList<>(); + CentralV2RoleFunction v2RoleFunction3 = new CentralV2RoleFunction("test_type3|test_instance3|*", "Test Name3"); + v2RoleFunction2.add(v2RoleFunction3); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams2, null)) + .thenReturn(v2RoleFunction2); + ExternalRequestFieldsValidator actual = externalAccessRolesServiceImpl.saveRoleForApplication(addRoleTest, + app.getUebKey()); + ExternalRequestFieldsValidator expected = new ExternalRequestFieldsValidator(true, ""); + assertEquals(expected, actual); + } + + @Test + public void saveGlobalRoleForPortalApplicationUpdateTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + EPApp app = mockApp(); + app.setId(1l); + Role addRoleTest = new Role(); + SortedSet<RoleFunction> roleFuncSet = new TreeSet<>(); + RoleFunction roleFunc = new RoleFunction(); + roleFunc.setName("Test Name"); + roleFunc.setCode("test_type|test_instance|*"); + RoleFunction roleFunc2 = new RoleFunction(); + roleFunc2.setName("Test Name3"); + roleFunc2.setCode("test_type3|test_instance3|*"); + roleFuncSet.add(roleFunc); + roleFuncSet.add(roleFunc2); + addRoleTest.setActive(true); + addRoleTest.setName("global_test2"); + addRoleTest.setId(1111l); + addRoleTest.setRoleFunctions(roleFuncSet); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<EPRole> globalRoles = new ArrayList<>(); + EPRole globalRole = new EPRole(); + globalRole.setName("global_test"); + globalRole.setId(1111l); + globalRole.setActive(true); + globalRoles.add(globalRole); + Mockito.when(dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null)).thenReturn(globalRoles); + List<EPRole> epRoleList = new ArrayList<>(); + EPRole getEPRole = new EPRole(); + getEPRole.setName("global_test"); + getEPRole.setId(1111l); + getEPRole.setActive(true); + epRoleList.add(getEPRole); + final Map<String, Long> getPortalAppRoleParams = new HashMap<>(); + getPortalAppRoleParams.put("roleId", addRoleTest.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPortalAppRoleByRoleId", getPortalAppRoleParams, null)) + .thenReturn(epRoleList); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + HttpHeaders headers = new HttpHeaders(); + Mockito.when(EcompPortalUtils.base64encodeKeyForAAFBasicAuth()).thenReturn(headers); + JSONObject mockJsonObjectRole = new JSONObject(); + JSONObject mockJsonObjectFinalRole = new JSONObject(); + JSONObject mockJsonObjectPerm1 = new JSONObject(); + JSONObject mockJsonObjectPerm2 = new JSONObject(); + mockJsonObjectPerm1.put("type", "com.test.app.test_type"); + mockJsonObjectPerm1.put("instance", "test_instance"); + mockJsonObjectPerm1.put("action", "*"); + mockJsonObjectPerm2.put("type", "com.test.app.test_type2"); + mockJsonObjectPerm2.put("instance", "test_instance2"); + mockJsonObjectPerm2.put("action", "*"); + List<JSONObject> permsList = new ArrayList<>(); + permsList.add(mockJsonObjectPerm1); + permsList.add(mockJsonObjectPerm2); + mockJsonObjectRole.put("name", "com.test.app.global_test"); + mockJsonObjectRole.put("perms", permsList); + mockJsonObjectRole.put("description", + "{\"id\":\"1111\",\"name\":\"global_test\",\"active\":\"true\",\"priority\":\"null\",\"appId\":\"null\",\"appRoleId\":\"null\"}"); + List<JSONObject> roleList = new ArrayList<>(); + roleList.add(mockJsonObjectRole); + mockJsonObjectFinalRole.put("role", roleList); + ResponseEntity<String> getResponse = new ResponseEntity<>(mockJsonObjectFinalRole.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + ResponseEntity<String> delResponse = new ResponseEntity<>(roleList.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(delResponse); + ResponseEntity<String> addRoleResponse = new ResponseEntity<>(HttpStatus.CREATED); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(addRoleResponse); + final Map<String, String> params = new HashMap<>(); + params.put("uebKey", app.getUebKey()); + params.put("roleId", String.valueOf(getEPRole.getId())); + List<BulkUploadUserRoles> userRolesList = new ArrayList<>(); + BulkUploadUserRoles bulkUploadUserRoles = new BulkUploadUserRoles(); + bulkUploadUserRoles.setAppNameSpace("com.test.app"); + bulkUploadUserRoles.setOrgUserId("guestT"); + bulkUploadUserRoles.setRoleName("Test2"); + userRolesList.add(bulkUploadUserRoles); + Mockito.when(dataAccessService.executeNamedQuery("getBulkUsersForSingleRole", params, null)) + .thenReturn(userRolesList); + Mockito.when( + EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn(true); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn("@test.com"); + ResponseEntity<String> mockBulkUsersUpload = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(mockBulkUsersUpload); + List<EPAppRoleFunction> appRoleFunctionList = new ArrayList<>(); + final Map<String, Long> appRoleFuncsParams = new HashMap<>(); + appRoleFuncsParams.put("appId", app.getId()); + appRoleFuncsParams.put("roleId", getEPRole.getId()); + Mockito.when( + dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null)) + .thenReturn(appRoleFunctionList); + Mockito.when(EcompPortalUtils.getFunctionCode(roleFunc.getCode())).thenReturn("test_instance"); + Mockito.when(EcompPortalUtils.getFunctionCode(roleFunc2.getCode())).thenReturn("test_instance3"); + final Map<String, String> getAppFunctionParams = new HashMap<>(); + getAppFunctionParams.put("appId", String.valueOf(app.getId())); + getAppFunctionParams.put(FUNCTION_CODE_PARAMS, roleFunc.getCode()); + List<CentralV2RoleFunction> v2RoleFunction = new ArrayList<>(); + CentralV2RoleFunction v2RoleFunction1 = new CentralV2RoleFunction("test_type|test_instance|*", "Test Name"); + v2RoleFunction.add(v2RoleFunction1); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null)) + .thenReturn(v2RoleFunction); + final Map<String, String> getAppFunctionParams2 = new HashMap<>(); + getAppFunctionParams2.put("appId", String.valueOf(app.getId())); + getAppFunctionParams2.put(FUNCTION_CODE_PARAMS, roleFunc2.getCode()); + List<CentralV2RoleFunction> v2RoleFunction2 = new ArrayList<>(); + CentralV2RoleFunction v2RoleFunction3 = new CentralV2RoleFunction("test_type3|test_instance3|*", "Test Name3"); + v2RoleFunction2.add(v2RoleFunction3); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams2, null)) + .thenReturn(v2RoleFunction2); + ExternalRequestFieldsValidator actual = externalAccessRolesServiceImpl.saveRoleForApplication(addRoleTest, + app.getUebKey()); + ExternalRequestFieldsValidator expected = new ExternalRequestFieldsValidator(true, ""); + assertEquals(expected, actual); + } + + @Test + public void saveRoleForPartnerApplicationUpdateTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + EPApp app = mockApp(); + app.setId(2l); + Role addRoleTest = new Role(); + SortedSet<RoleFunction> roleFuncSet = new TreeSet<>(); + RoleFunction roleFunc = new RoleFunction(); + roleFunc.setName("Test Name"); + roleFunc.setCode("test_type|test_instance|*"); + RoleFunction roleFunc2 = new RoleFunction(); + roleFunc2.setName("Test Name3"); + roleFunc2.setCode("test_type3|test_instance3|*"); + roleFuncSet.add(roleFunc); + roleFuncSet.add(roleFunc2); + addRoleTest.setActive(false); + addRoleTest.setName("Test2"); + addRoleTest.setId(22l); + addRoleTest.setRoleFunctions(roleFuncSet); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<EPRole> globalRoles = new ArrayList<>(); + EPRole globalRole = new EPRole(); + globalRole.setName("global_test"); + globalRole.setId(1111l); + globalRole.setActive(true); + globalRoles.add(globalRole); + Mockito.when(dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null)).thenReturn(globalRoles); + List<EPRole> epRoleList = new ArrayList<>(); + EPRole getEPRole = new EPRole(); + getEPRole.setName("Test2"); + getEPRole.setId(2l); + getEPRole.setActive(true); + getEPRole.setAppRoleId(22l); + epRoleList.add(getEPRole); + final Map<String, Long> getPortalAppRoleParams = new HashMap<>(); + getPortalAppRoleParams.put("appRoleId", addRoleTest.getId()); + getPortalAppRoleParams.put("appId", app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPortalAppRoleParams, null)) + .thenReturn(epRoleList); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + HttpHeaders headers = new HttpHeaders(); + Mockito.when(EcompPortalUtils.base64encodeKeyForAAFBasicAuth()).thenReturn(headers); + JSONObject mockJsonObjectRole = new JSONObject(); + JSONObject mockJsonObjectFinalRole = new JSONObject(); + JSONObject mockJsonObjectPerm1 = new JSONObject(); + JSONObject mockJsonObjectPerm2 = new JSONObject(); + mockJsonObjectPerm1.put("type", "com.test.app.test_type"); + mockJsonObjectPerm1.put("instance", "test_instance"); + mockJsonObjectPerm1.put("action", "*"); + mockJsonObjectPerm2.put("type", "com.test.app.test_type2"); + mockJsonObjectPerm2.put("instance", "test_instance2"); + mockJsonObjectPerm2.put("action", "*"); + List<JSONObject> permsList = new ArrayList<>(); + permsList.add(mockJsonObjectPerm1); + permsList.add(mockJsonObjectPerm2); + mockJsonObjectRole.put("name", "com.test.app.Test"); + mockJsonObjectRole.put("perms", permsList); + mockJsonObjectRole.put("description", + "{\"id\":\"2\",\"name\":\"Test2\",\"active\":\"true\",\"priority\":\"null\",\"appId\":\"2\",\"appRoleId\":\"22\"}"); + List<JSONObject> roleList = new ArrayList<>(); + roleList.add(mockJsonObjectRole); + mockJsonObjectFinalRole.put("role", roleList); + ResponseEntity<String> getResponse = new ResponseEntity<>(mockJsonObjectFinalRole.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + ResponseEntity<String> delResponse = new ResponseEntity<>(roleList.toString(), HttpStatus.OK); + final Map<String, String> getPartnerAppRoleParams = new HashMap<>(); + getPartnerAppRoleParams.put(APP_ROLE_NAME_PARAM, addRoleTest.getName()); + getPartnerAppRoleParams.put("appId", String.valueOf(app.getId())); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, + getPartnerAppRoleParams, null)).thenReturn(epRoleList); + ResponseEntity<String> updateRoleResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.PUT), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(updateRoleResponse); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(delResponse); + ResponseEntity<String> addRoleResponse = new ResponseEntity<>(HttpStatus.CREATED); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(addRoleResponse); + final Map<String, String> params = new HashMap<>(); + params.put("uebKey", app.getUebKey()); + params.put("roleId", String.valueOf(getEPRole.getId())); + List<BulkUploadUserRoles> userRolesList = new ArrayList<>(); + BulkUploadUserRoles bulkUploadUserRoles = new BulkUploadUserRoles(); + bulkUploadUserRoles.setAppNameSpace("com.test.app"); + bulkUploadUserRoles.setOrgUserId("guestT"); + bulkUploadUserRoles.setRoleName("Test2"); + userRolesList.add(bulkUploadUserRoles); + Mockito.when(dataAccessService.executeNamedQuery("getBulkUsersForSingleRole", params, null)) + .thenReturn(userRolesList); + Mockito.when( + EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn(true); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn("@test.com"); + ResponseEntity<String> mockBulkUsersUpload = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(mockBulkUsersUpload); + List<EPAppRoleFunction> appRoleFunctionList = new ArrayList<>(); + final Map<String, Long> appRoleFuncsParams = new HashMap<>(); + appRoleFuncsParams.put("appId", app.getId()); + appRoleFuncsParams.put("roleId", getEPRole.getId()); + Mockito.when( + dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null)) + .thenReturn(appRoleFunctionList); + Mockito.when(EcompPortalUtils.getFunctionCode(roleFunc.getCode())).thenReturn("test_instance"); + Mockito.when(EcompPortalUtils.getFunctionCode(roleFunc2.getCode())).thenReturn("test_instance3"); + final Map<String, String> getAppFunctionParams = new HashMap<>(); + getAppFunctionParams.put("appId", String.valueOf(app.getId())); + getAppFunctionParams.put(FUNCTION_CODE_PARAMS, roleFunc.getCode()); + List<CentralV2RoleFunction> v2RoleFunction = new ArrayList<>(); + CentralV2RoleFunction v2RoleFunction1 = new CentralV2RoleFunction("test_type|test_instance|*", "Test Name"); + v2RoleFunction.add(v2RoleFunction1); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null)) + .thenReturn(v2RoleFunction); + final Map<String, String> getAppFunctionParams2 = new HashMap<>(); + getAppFunctionParams2.put("appId", String.valueOf(app.getId())); + getAppFunctionParams2.put(FUNCTION_CODE_PARAMS, roleFunc2.getCode()); + List<CentralV2RoleFunction> v2RoleFunction2 = new ArrayList<>(); + CentralV2RoleFunction v2RoleFunction3 = new CentralV2RoleFunction("test_type3|test_instance3|*", "Test Name3"); + v2RoleFunction2.add(v2RoleFunction3); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams2, null)) + .thenReturn(v2RoleFunction2); + ExternalRequestFieldsValidator actual = externalAccessRolesServiceImpl.saveRoleForApplication(addRoleTest, + app.getUebKey()); + ExternalRequestFieldsValidator expected = new ExternalRequestFieldsValidator(true, ""); + assertEquals(expected, actual); + } + + @Test + public void saveGlobalRoleFunctionsForPartnerApplicationUpdateTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + EPApp app = mockApp(); + app.setId(2l); + Role addRoleTest = new Role(); + SortedSet<RoleFunction> roleFuncSet = new TreeSet<>(); + RoleFunction roleFunc = new RoleFunction(); + roleFunc.setName("Test Name"); + roleFunc.setCode("test_type|test_instance|*"); + RoleFunction roleFunc2 = new RoleFunction(); + roleFunc2.setName("Test Name3"); + roleFunc2.setCode("test_type3|test_instance3|*"); + roleFuncSet.add(roleFunc); + roleFuncSet.add(roleFunc2); + addRoleTest.setActive(true); + addRoleTest.setName("global_test"); + addRoleTest.setId(1111l); + addRoleTest.setRoleFunctions(roleFuncSet); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<EPRole> globalRoles = new ArrayList<>(); + EPRole globalRole = new EPRole(); + globalRole.setName("global_test"); + globalRole.setId(1111l); + globalRole.setActive(true); + EPRole globalRole2 = new EPRole(); + globalRole2.setName("global_test2"); + globalRole2.setId(2222l); + globalRole2.setActive(true); + globalRoles.add(globalRole); + globalRoles.add(globalRole2); + Mockito.when(dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null)).thenReturn(globalRoles); + List<EPRole> getGlobalRoles = new ArrayList<>(); + EPRole getEPGlobalRole = new EPRole(); + getEPGlobalRole.setName("global_test"); + getEPGlobalRole.setId(1111l); + getEPGlobalRole.setActive(true); + getGlobalRoles.add(getEPGlobalRole); + final Map<String, Long> getPortalAppRoleParams = new HashMap<>(); + getPortalAppRoleParams.put("roleId", globalRole.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPortalAppRoleByRoleId", getPortalAppRoleParams, null)) + .thenReturn(getGlobalRoles); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + Mockito.when(epAppCommonServiceImpl.getApp(PortalConstants.PORTAL_APP_ID)).thenReturn(app); + JSONObject mockJsonObjectPerm = new JSONObject(); + JSONObject mockJsonObjectPerm2 = new JSONObject(); + JSONObject mockJsonObjectPerm3 = new JSONObject(); + JSONObject mockJsonObjectPerm4 = new JSONObject(); + JSONObject mockJsonObjectFinalPerm = new JSONObject(); + mockJsonObjectPerm.put("type", "com.test.app.test_type"); + mockJsonObjectPerm.put("instance", "test_instance"); + mockJsonObjectPerm.put("action", "*"); + mockJsonObjectPerm.put("description", "Test Name"); + mockJsonObjectPerm2.put("type", "com.test.app.access"); + mockJsonObjectPerm2.put("instance", "test_instance2"); + mockJsonObjectPerm2.put("action", "*"); + mockJsonObjectPerm2.put("description", "Test Name2"); + mockJsonObjectPerm3.put("type", "com.test.app.test_type3"); + mockJsonObjectPerm3.put("instance", "test_instance3"); + mockJsonObjectPerm3.put("action", "*"); + mockJsonObjectPerm3.put("description", "Test Name3"); + mockJsonObjectPerm4.put("type", "com.test.app.test_type4"); + mockJsonObjectPerm4.put("instance", "test_instance4"); + mockJsonObjectPerm4.put("action", "*"); + mockJsonObjectPerm4.put("description", "Test Name4"); + List<JSONObject> mockJson = new ArrayList<>(); + mockJson.add(mockJsonObjectPerm); + mockJson.add(mockJsonObjectPerm2); + mockJson.add(mockJsonObjectPerm3); + mockJson.add(mockJsonObjectPerm4); + mockJsonObjectFinalPerm.put("perm", mockJson); + ResponseEntity<String> getResponse = new ResponseEntity<>(mockJsonObjectFinalPerm.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + Mockito.when(EcompPortalUtils.getFunctionCode(roleFunc.getCode())).thenReturn("test_instance"); + ResponseEntity<String> postResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(postResponse); + Mockito.when(EcompPortalUtils.getFunctionCode(roleFunc.getCode())).thenReturn("test_instance"); + final Map<String, Long> epAppRoleFuncParams = new HashMap<>(); + epAppRoleFuncParams.put("requestedAppId", app.getId()); + epAppRoleFuncParams.put("roleId", globalRole.getId()); + List<GlobalRoleWithApplicationRoleFunction> mockGlobalRoles = new ArrayList<>(); + GlobalRoleWithApplicationRoleFunction mockGlobalRole = new GlobalRoleWithApplicationRoleFunction(); + mockGlobalRole.setActive(true); + mockGlobalRole.setAppId(app.getId()); + mockGlobalRole.setRoleId(1111l); + mockGlobalRole.setRoleName("global_test"); + mockGlobalRole.setFunctionCd("test_type4|test_instance4|*"); + mockGlobalRole.setFunctionName("test name"); + mockGlobalRoles.add(mockGlobalRole); + Mockito.when(dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp", epAppRoleFuncParams, null)) + .thenReturn(mockGlobalRoles); + ResponseEntity<String> delResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(delResponse); + final Map<String, Long> appRoleFuncsParams = new HashMap<>(); + appRoleFuncsParams.put("appId", app.getId()); + appRoleFuncsParams.put("roleId", globalRole.getId()); + List<EPAppRoleFunction> appRoleFunctionList = new ArrayList<>(); + EPAppRoleFunction epAppRoleFunction = new EPAppRoleFunction(); + epAppRoleFunction.setAppId(app.getId()); + epAppRoleFunction.setRoleAppId("1"); + epAppRoleFunction.setCode("test"); + epAppRoleFunction.setRoleId(1111l); + appRoleFunctionList.add(epAppRoleFunction); + Mockito.when( + dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null)) + .thenReturn(appRoleFunctionList); + final Map<String, String> getAppFunctionParams = new HashMap<>(); + Mockito.when(EcompPortalUtils.getFunctionCode(roleFunc.getCode())).thenReturn("test_instance"); + Mockito.when(EcompPortalUtils.getFunctionCode(roleFunc2.getCode())).thenReturn("test_instance3"); + Mockito.when(EcompPortalUtils.getFunctionCode("test_type4|test_instance4|*")).thenReturn("test_instance4"); + getAppFunctionParams.put("appId", String.valueOf(app.getId())); + getAppFunctionParams.put(FUNCTION_CODE_PARAMS, roleFunc.getCode()); + List<CentralV2RoleFunction> roleFunction = new ArrayList<>(); + CentralV2RoleFunction centralV2RoleFunction = new CentralV2RoleFunction(null, roleFunc.getCode(), + roleFunc.getName(), app.getId(), null); + roleFunction.add(centralV2RoleFunction); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null)) + .thenReturn(roleFunction); + final Map<String, String> getAppFunctionParams2 = new HashMap<>(); + getAppFunctionParams2.put("appId", String.valueOf(app.getId())); + getAppFunctionParams2.put(FUNCTION_CODE_PARAMS, roleFunc2.getCode()); + List<CentralV2RoleFunction> roleFunction2 = new ArrayList<>(); + CentralV2RoleFunction centralV2RoleFunction2 = new CentralV2RoleFunction(null, roleFunc2.getCode(), + roleFunc2.getName(), app.getId(), null); + roleFunction2.add(centralV2RoleFunction2); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams2, null)) + .thenReturn(roleFunction2); + ExternalRequestFieldsValidator actual = externalAccessRolesServiceImpl.saveRoleForApplication(addRoleTest, + app.getUebKey()); + ExternalRequestFieldsValidator expected = new ExternalRequestFieldsValidator(true, ""); + assertEquals(expected, actual); + } + + @Test + public void syncRoleFunctionFromExternalAccessSystemTest() { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + EPApp app = mockApp(); + app.setId(2l); + JSONObject mockJsonObjectFinalPerm = new JSONObject(); + JSONObject mockJsonObjectPerm = new JSONObject(); + JSONObject mockJsonObjectPerm2 = new JSONObject(); + JSONObject mockJsonObjectPerm3 = new JSONObject(); + mockJsonObjectPerm.put("type", "com.test.app.test_type"); + mockJsonObjectPerm.put("instance", "test_instance"); + mockJsonObjectPerm.put("action", "*"); + mockJsonObjectPerm.put("description", "test_name"); + List<String> rolePermList = new ArrayList<>(); + rolePermList.add("com.test.app|test1"); + mockJsonObjectPerm.put("roles", rolePermList); + mockJsonObjectPerm2.put("type", "com.test.app.test_type2"); + mockJsonObjectPerm2.put("instance", "test_instance2"); + List<String> rolePermList2 = new ArrayList<>(); + rolePermList2.add("com.test.app|test1"); + rolePermList2.add("com.test.app|test2"); + rolePermList2.add("com.test.app|test6"); + rolePermList2.add("com.test.app.new|global_test"); + mockJsonObjectPerm2.put("action", "*"); + mockJsonObjectPerm2.put("roles", rolePermList2); + mockJsonObjectPerm2.put("description", "test_name2"); + mockJsonObjectPerm3.put("type", "com.test.app.access"); + mockJsonObjectPerm3.put("instance", "test_instance3"); + mockJsonObjectPerm3.put("action", "*"); + mockJsonObjectPerm3.put("description", "test_name3"); + List<JSONObject> permsList = new ArrayList<>(); + permsList.add(mockJsonObjectPerm); + permsList.add(mockJsonObjectPerm2); + permsList.add(mockJsonObjectPerm3); + mockJsonObjectFinalPerm.put("perm", permsList); + ResponseEntity<String> getResponse = new ResponseEntity<>(mockJsonObjectFinalPerm.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + final Map<String, Long> params = new HashMap<>(); + params.put(APP_ID, app.getId()); + List<CentralV2RoleFunction> appFunctions = new ArrayList<>(); + CentralV2RoleFunction centralV2RoleFunction = new CentralV2RoleFunction(null, "test_type|test_instance|*", + "test_name", app.getId(), null); + CentralV2RoleFunction centralV2RoleFunction2 = new CentralV2RoleFunction(null, "test_instance2", "test_name2", + app.getId(), null); + CentralV2RoleFunction centralV2RoleFunction3 = new CentralV2RoleFunction(null, "test_instance5", "test_name5", + app.getId(), null); + appFunctions.add(centralV2RoleFunction); + appFunctions.add(centralV2RoleFunction2); + appFunctions.add(centralV2RoleFunction3); + Mockito.when(dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null)).thenReturn(appFunctions); + List<EPRole> globalRoles = new ArrayList<>(); + EPRole globalRole = new EPRole(); + globalRole.setName("global_test"); + globalRole.setId(1111l); + globalRole.setActive(true); + globalRoles.add(globalRole); + Mockito.when(dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null)).thenReturn(globalRoles); + List<EPRole> getCurrentRoleList = new ArrayList<>(); + EPRole getEPRole = new EPRole(); + getEPRole.setName("test1"); + getEPRole.setId(2l); + getEPRole.setActive(true); + EPRole getEPRole2 = new EPRole(); + getEPRole2.setName("global_test"); + getEPRole2.setId(1111l); + getEPRole2.setActive(true); + EPRole getEPRole3 = new EPRole(); + getEPRole3.setName("test2"); + getEPRole3.setId(4l); + getEPRole3.setActive(true); + getCurrentRoleList.add(getEPRole); + getCurrentRoleList.add(getEPRole2); + getCurrentRoleList.add(getEPRole3); + final Map<String, Long> appParams = new HashMap<>(); + appParams.put("appId", app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null)) + .thenReturn(getCurrentRoleList); + final Map<String, String> appSyncFuncsParams = new HashMap<>(); + appSyncFuncsParams.put("appId", String.valueOf(app.getId())); + appSyncFuncsParams.put("functionCd", ""); + List<CentralV2RoleFunction> roleFunctionList = new ArrayList<>(); + Mockito.when(dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams, null)) + .thenReturn(roleFunctionList); + String code = centralV2RoleFunction.getCode(); + appSyncFuncsParams.put("functionCd", code); + CentralV2RoleFunction getCentralV2RoleFunction = new CentralV2RoleFunction(null, "test_type|test_instance|*", + "test_name", app.getId(), null); + roleFunctionList.add(getCentralV2RoleFunction); + Mockito.when(dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams, null)) + .thenReturn(roleFunctionList); + List<LocalRole> localRoles = new ArrayList<>(); + LocalRole localRole = new LocalRole(); + localRole.setRoleId(2); + localRole.setRolename("test1"); + LocalRole localRole2 = new LocalRole(); + localRole2.setRoleId(3); + localRole2.setRolename("test3"); + localRoles.add(localRole); + localRoles.add(localRole2); + final Map<String, String> appRoleFuncParams = new HashMap<>(); + appRoleFuncParams.put("functionCd", "test_type2|test_instance2|*"); + appRoleFuncParams.put("appId", String.valueOf(app.getId())); + Mockito.when(dataAccessService.executeNamedQuery("getCurrentAppRoleFunctions", appRoleFuncParams, null)) + .thenReturn(localRoles); + Mockito.when(EcompPortalUtils.checkNameSpaceMatching("com.test.app", app.getNameSpace())).thenReturn(true); + Mockito.when(EcompPortalUtils.getFunctionCode("test_type2|test_instance2|*")).thenReturn("test_instance2"); + appSyncFuncsParams.put("functionCd", "test_instance2"); + List<CentralV2RoleFunction> roleFunctionList2 = new ArrayList<>(); + Mockito.when(dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams, null)) + .thenReturn(roleFunctionList2); + String code2 = "test_type2|test_instance2|*"; + appSyncFuncsParams.put("functionCd", code2); + CentralV2RoleFunction getCentralV2RoleFunction2 = new CentralV2RoleFunction(null, "test_type2|test_instance2|*", + "test_name2", app.getId(), null); + roleFunctionList2.add(getCentralV2RoleFunction2); + Mockito.when(dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams, null)) + .thenReturn(roleFunctionList2); + final Map<String, Long> params3 = new HashMap<>(); + params3.put("appId", app.getId()); + params3.put("roleId", getEPRole2.getId()); + List<EPAppRoleFunction> currentGlobalRoleFunctionsList = new ArrayList<>(); + EPAppRoleFunction addGlobalRoleFunction = new EPAppRoleFunction(); + addGlobalRoleFunction.setAppId(app.getId()); + addGlobalRoleFunction.setCode("test_type|test_instance|*"); + addGlobalRoleFunction.setRoleId(1111l); + currentGlobalRoleFunctionsList.add(addGlobalRoleFunction); + Mockito.when(dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", params3, null)) + .thenReturn(currentGlobalRoleFunctionsList); + final Map<String, String> roleParams = new HashMap<>(); + roleParams.put(APP_ROLE_NAME_PARAM, "test6"); + roleParams.put("appId", String.valueOf(app.getId())); + List<EPRole> roleCreated = new ArrayList<>(); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams, null)) + .thenReturn(roleCreated); + final Map<String, String> getRoleByNameParams = new HashMap<>(); + getRoleByNameParams.put(APP_ROLE_NAME_PARAM, "test6"); + getRoleByNameParams.put("appId", String.valueOf(app.getId())); + EPRole getNewEPRole = new EPRole(); + getNewEPRole.setName("test6"); + getNewEPRole.setId(8l); + getNewEPRole.setActive(true); + List<EPRole> roleCreated2 = new ArrayList<>(); + roleCreated2.add(getNewEPRole); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, + getRoleByNameParams, null)).thenReturn(roleCreated2); + EPRole getNewEPRoleFinal = new EPRole(); + getNewEPRoleFinal.setName("test6"); + getNewEPRoleFinal.setId(8l); + getNewEPRoleFinal.setActive(true); + getNewEPRoleFinal.setAppRoleId(8l); + final Map<String, String> getRoleByNameParams2 = new HashMap<>(); + getRoleByNameParams2.put(APP_ROLE_NAME_PARAM, "test6"); + getRoleByNameParams2.put("appId", String.valueOf(app.getId())); + List<EPRole> roleCreated3 = new ArrayList<>(); + roleCreated3.add(getNewEPRole); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, + getRoleByNameParams2, null)).thenReturn(roleCreated3); + List<EPRole> roleInfo = new ArrayList<>(); + roleInfo.add(getNewEPRoleFinal); + final Map<String, Long> getPartnerAppRoleParams = new HashMap<>(); + getPartnerAppRoleParams.put("appRoleId", getNewEPRoleFinal.getId()); + getPartnerAppRoleParams.put("appId", app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null)) + .thenReturn(roleInfo); + externalAccessRolesServiceImpl.syncRoleFunctionFromExternalAccessSystem(app); + } + + @Test + public void syncApplicationRolesWithEcompDBTest() { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + EPApp app = mockApp(); + app.setId(2l); + JSONObject mockJsonObjectRole = new JSONObject(); + JSONObject mockJsonObjectRole2 = new JSONObject(); + JSONObject mockJsonObjectFinalRole = new JSONObject(); + JSONObject mockJsonObjectPerm1 = new JSONObject(); + JSONObject mockJsonObjectPerm2 = new JSONObject(); + mockJsonObjectPerm1.put("type", "com.test.app.test_type"); + mockJsonObjectPerm1.put("instance", "test_instance"); + mockJsonObjectPerm1.put("action", "*"); + mockJsonObjectPerm2.put("type", "com.test.app.test_type2"); + mockJsonObjectPerm2.put("instance", "test_instance2"); + mockJsonObjectPerm2.put("action", "*"); + List<JSONObject> permsList = new ArrayList<>(); + permsList.add(mockJsonObjectPerm1); + permsList.add(mockJsonObjectPerm2); + mockJsonObjectRole.put("name", "com.test.app.Test"); + mockJsonObjectRole.put("perms", permsList); + mockJsonObjectRole.put("description", + "{\"id\":\"2\",\"name\":\"test1\",\"active\":\"true\",\"priority\":\"null\",\"appId\":\"2\",\"appRoleId\":\"2\"}"); + mockJsonObjectRole2.put("name", "com.test.app.Test2"); + List<JSONObject> permsList2 = new ArrayList<>(); + permsList2.add(mockJsonObjectPerm1); + mockJsonObjectRole2.put("perms", permsList2); + List<JSONObject> roleList = new ArrayList<>(); + roleList.add(mockJsonObjectRole); + roleList.add(mockJsonObjectRole2); + mockJsonObjectFinalRole.put("role", roleList); + ResponseEntity<String> getResponse = new ResponseEntity<>(mockJsonObjectFinalRole.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + List<EPRole> getCurrentRoleList = new ArrayList<>(); + EPRole getEPRole = new EPRole(); + getEPRole.setName("Test"); + getEPRole.setId(2l); + getEPRole.setAppId(app.getId()); + getEPRole.setAppRoleId(2l); + getEPRole.setActive(true); + EPRole getEPRole2 = new EPRole(); + getEPRole2.setName("Test3"); + getEPRole2.setId(3l); + getEPRole.setAppId(app.getId()); + getEPRole.setAppRoleId(3l); + getEPRole2.setActive(true); + getCurrentRoleList.add(getEPRole); + getCurrentRoleList.add(getEPRole2); + final Map<String, Long> appParams = new HashMap<>(); + appParams.put("appId", app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null)) + .thenReturn(getCurrentRoleList); + Mockito.when(EcompPortalUtils.checkNameSpaceMatching("com.test.app.test_type", app.getNameSpace())) + .thenReturn(true); + Mockito.when(EcompPortalUtils.checkNameSpaceMatching("com.test.app.test_type2", app.getNameSpace())) + .thenReturn(true); + List<EPAppRoleFunction> appRoleFunctions = new ArrayList<>(); + EPAppRoleFunction epAppRoleFunction = new EPAppRoleFunction(); + epAppRoleFunction.setAppId(app.getId()); + epAppRoleFunction.setCode("test_type|test_instance|*"); + epAppRoleFunction.setRoleId(getEPRole.getId()); + appRoleFunctions.add(epAppRoleFunction); + final Map<String, Long> appRoleFuncsParams = new HashMap<>(); + appRoleFuncsParams.put("appId", app.getId()); + appRoleFuncsParams.put("roleId", Long.valueOf(getEPRole.getId())); + Mockito.when( + dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null)) + .thenReturn(appRoleFunctions); + List<CentralV2RoleFunction> getV2RoleFunction = new ArrayList<>(); + final Map<String, String> appFuncsParams = new HashMap<>(); + appFuncsParams.put("appId", String.valueOf(app.getId())); + appFuncsParams.put("functionCd", "test_instance2"); + Mockito.when(dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appFuncsParams, null)) + .thenReturn(getV2RoleFunction); + appFuncsParams.put("functionCd", "test_type2|test_instance2|*"); + CentralV2RoleFunction centralV2RoleFunction = new CentralV2RoleFunction(); + centralV2RoleFunction.setAppId(app.getId()); + centralV2RoleFunction.setCode("test_type2|test_instance2|*"); + centralV2RoleFunction.setName("test_name2"); + getV2RoleFunction.add(centralV2RoleFunction); + final Map<String, String> extRoleParams = new HashMap<>(); + List<EPRole> roleListDeactivate = new ArrayList<>(); + extRoleParams.put(APP_ROLE_NAME_PARAM, "Test3"); + extRoleParams.put(APP_ID, app.getId().toString()); + EPRole getEPRoleDeactivate = new EPRole(); + getEPRoleDeactivate.setName("Test3"); + getEPRoleDeactivate.setId(3l); + getEPRoleDeactivate.setAppId(app.getId()); + getEPRoleDeactivate.setAppRoleId(3l); + roleListDeactivate.add(getEPRoleDeactivate); + Mockito.when( + dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, extRoleParams, null)) + .thenReturn(roleListDeactivate); + Mockito.when(dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appFuncsParams, null)) + .thenReturn(getV2RoleFunction); + List<EPRole> updateLocalFromExtAuth = new ArrayList<>(); + updateLocalFromExtAuth.add(getEPRole); + final Map<String, String> roleParams = new HashMap<>(); + roleParams.put(APP_ROLE_NAME_PARAM, getEPRole.getName()); + roleParams.put(APP_ID, app.getId().toString()); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams, null)) + .thenReturn(updateLocalFromExtAuth); + roleParams.put(APP_ROLE_NAME_PARAM, getEPRole2.getName()); + List<EPRole> updateLocalFromExtAuth2 = new ArrayList<>(); + updateLocalFromExtAuth.add(getEPRole); + Mockito.when(dataAccessService.executeNamedQuery("getRoletoUpdateInExternalAuthSystem", roleParams, null)) + .thenReturn(updateLocalFromExtAuth2); + final Map<String, String> globalRoleParams = new HashMap<>(); + globalRoleParams.put("appId", String.valueOf(app.getId())); + globalRoleParams.put("appRoleName", "Test2"); + List<EPRole> addNewRoleList = new ArrayList<>(); + EPRole addRoleInLocal = new EPRole(); + addRoleInLocal.setName("Test2"); + addRoleInLocal.setId(4l); + addRoleInLocal.setAppId(app.getId()); + addRoleInLocal.setActive(true); + addNewRoleList.add(addRoleInLocal); + Mockito.when( + dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, globalRoleParams, null)) + .thenReturn(addNewRoleList); + final Map<String, String> params = new HashMap<>(); + params.put(APP_ROLE_NAME_PARAM, "Test2"); + params.put(APP_ID, app.getId().toString()); + addRoleInLocal.setAppRoleId(4l); + addNewRoleList.add(addRoleInLocal); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, params, null)) + .thenReturn(addNewRoleList); + externalAccessRolesServiceImpl.syncApplicationRolesWithEcompDB(app); + } + + @Test + public void deleteDependencyRoleRecord() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + SQLQuery SqlQuery = Mockito.mock(SQLQuery.class); + EPApp app = mockApp(); + app.setId(2l); + EPUser user = mockUser.mockEPUser(); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<EPRole> epRoleList = new ArrayList<>(); + EPRole getEPRole = new EPRole(); + getEPRole.setName("Test"); + getEPRole.setId(2l); + getEPRole.setAppRoleId(2l); + getEPRole.setActive(true); + epRoleList.add(getEPRole); + final Map<String, Long> getPartnerAppRoleParams = new HashMap<>(); + getPartnerAppRoleParams.put("appRoleId", getEPRole.getId()); + getPartnerAppRoleParams.put("appId", app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null)) + .thenReturn(epRoleList); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + JSONObject getUser = new JSONObject(); + getUser.put("name", "com.test.app.test1"); + ResponseEntity<String> getResponse = new ResponseEntity<>(getUser.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + ResponseEntity<String> DelResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(DelResponse); + Mockito.when(session.createSQLQuery(Matchers.anyString())).thenReturn(SqlQuery); + ExternalRequestFieldsValidator actual = externalAccessRolesServiceImpl.deleteDependencyRoleRecord(2l, + app.getUebKey(), user.getOrgUserId()); + ExternalRequestFieldsValidator expected = new ExternalRequestFieldsValidator(true, ""); + assertEquals(expected, actual); + } + + @Test + public void deleteDependencyRoleRecordForPortal() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + SQLQuery SqlQuery = Mockito.mock(SQLQuery.class); + EPApp app = mockApp(); + app.setId(1l); + EPUser user = mockUser.mockEPUser(); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<EPRole> epRoleList = new ArrayList<>(); + EPRole getEPRole = new EPRole(); + getEPRole.setName("Test"); + getEPRole.setId(2l); + getEPRole.setAppRoleId(2l); + getEPRole.setActive(true); + epRoleList.add(getEPRole); + final Map<String, Long> getPartnerAppRoleParams = new HashMap<>(); + getPartnerAppRoleParams.put("roleId", getEPRole.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPortalAppRoleByRoleId", getPartnerAppRoleParams, null)) + .thenReturn(epRoleList); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + JSONObject getUser = new JSONObject(); + getUser.put("name", "com.test.app.test1"); + ResponseEntity<String> getResponse = new ResponseEntity<>(getUser.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + ResponseEntity<String> DelResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(DelResponse); + Mockito.when(session.createSQLQuery(Matchers.anyString())).thenReturn(SqlQuery); + ExternalRequestFieldsValidator actual = externalAccessRolesServiceImpl.deleteDependencyRoleRecord(2l, + app.getUebKey(), user.getOrgUserId()); + ExternalRequestFieldsValidator expected = new ExternalRequestFieldsValidator(true, ""); + assertEquals(expected, actual); + } + + @Test + public void bulkUploadFunctionsTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + EPApp app = mockApp(); + app.setId(2l); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<RoleFunction> roleFuncList = new ArrayList<>(); + RoleFunction roleFunc = new RoleFunction(); + roleFunc.setCode("test_code"); + roleFunc.setName("test_name"); + RoleFunction roleFunc2 = new RoleFunction(); + roleFunc2.setCode("test_code2"); + roleFunc2.setName("test_name2"); + roleFuncList.add(roleFunc); + roleFuncList.add(roleFunc2); + Mockito.when(dataAccessService.executeNamedQuery("getAllFunctions", null, null)).thenReturn(roleFuncList); + JSONObject perm = new JSONObject(); + JSONObject permList = new JSONObject(); + perm.put("type", app.getNameSpace() + ".access"); + perm.put("instance", "type_instance"); + perm.put("action", "*"); + List<JSONObject> addPerms = new ArrayList<>(); + addPerms.add(perm); + permList.put("perm", addPerms); + ResponseEntity<String> getResponse = new ResponseEntity<>(permList.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + ResponseEntity<String> postResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(postResponse); + Integer actual = externalAccessRolesServiceImpl.bulkUploadFunctions(app.getUebKey()); + Integer expected = 2; + assertEquals(expected, actual); + } + + @Test + public void bulkUploadRolesTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + EPApp app = mockApp(); + app.setId(2l); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<EPRole> epRoleList = new ArrayList<>(); + EPRole getEPRole = new EPRole(); + getEPRole.setName("Test"); + getEPRole.setId(2l); + getEPRole.setAppRoleId(2l); + getEPRole.setActive(true); + EPRole getEPRole2 = new EPRole(); + getEPRole2.setName("Test2"); + getEPRole2.setId(3l); + getEPRole2.setAppRoleId(3l); + getEPRole2.setActive(true); + epRoleList.add(getEPRole); + epRoleList.add(getEPRole2); + final Map<String, Long> appParams = new HashMap<>(); + appParams.put("appId", app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null)) + .thenReturn(epRoleList); + List<EPRole> epRoleList1 = new ArrayList<>(); + EPRole ePRole = new EPRole(); + ePRole.setName("Test"); + ePRole.setId(2l); + ePRole.setAppRoleId(2l); + ePRole.setActive(true); + epRoleList1.add(ePRole); + final Map<String, Long> getPartnerAppRoleParams = new HashMap<>(); + getPartnerAppRoleParams.put("appRoleId", ePRole.getId()); + getPartnerAppRoleParams.put("appId", app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null)) + .thenReturn(epRoleList1); + List<EPRole> epRoleList2 = new ArrayList<>(); + EPRole ePRole2 = new EPRole(); + ePRole2.setName("Test2"); + ePRole2.setId(3l); + ePRole2.setAppRoleId(3l); + ePRole2.setActive(true); + epRoleList2.add(ePRole2); + final Map<String, Long> getPartnerAppRoleParams2 = new HashMap<>(); + getPartnerAppRoleParams2.put("appRoleId", ePRole2.getId()); + getPartnerAppRoleParams2.put("appId", app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams2, null)) + .thenReturn(epRoleList2); + ResponseEntity<String> postResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(postResponse); + Integer actual = externalAccessRolesServiceImpl.bulkUploadRoles(app.getUebKey()); + Integer expected = 2; + assertEquals(expected, actual); + } + + @Test + public void bulkUploadUserRolesTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + EPApp app = mockApp(); + app.setId(2l); + EPUser user = mockUser.mockEPUser(); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<BulkUploadUserRoles> userRolesList = new ArrayList<>(); + BulkUploadUserRoles bulkUploadUserRoles = new BulkUploadUserRoles(); + bulkUploadUserRoles.setAppNameSpace(app.getName()); + bulkUploadUserRoles.setOrgUserId(user.getOrgUserId()); + bulkUploadUserRoles.setRoleName("Test1"); + BulkUploadUserRoles bulkUploadUserRoles2 = new BulkUploadUserRoles(); + bulkUploadUserRoles2.setAppNameSpace(app.getName()); + bulkUploadUserRoles2.setOrgUserId(user.getOrgUserId()); + bulkUploadUserRoles2.setRoleName("Test2"); + userRolesList.add(bulkUploadUserRoles); + userRolesList.add(bulkUploadUserRoles2); + final Map<String, String> appParams = new HashMap<>(); + appParams.put("uebKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getBulkUserRoles", appParams, null)) + .thenReturn(userRolesList); + ResponseEntity<String> postResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(postResponse); + Integer actual = externalAccessRolesServiceImpl.bulkUploadUserRoles(app.getUebKey()); + Integer expected = 2; + assertEquals(expected, actual); + } + + @Test + public void getUserRolesTest() throws Exception { + EPApp app = mockApp(); + EPUser user = mockUser.mockEPUser(); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + final Map<String, String> userParams = new HashMap<>(); + userParams.put("org_user_id", user.getOrgUserId()); + List<EPUser> userList = new ArrayList<>(); + Set<EPUserApp> userAppSet = user.getEPUserApps(); + EPUserApp epUserApp = new EPUserApp(); + EPRole epRole = new EPRole(); + epRole.setName("test"); + epRole.setId(1l); + epRole.setActive(true); + epRole.setAppRoleId(11l); + epUserApp.setApp(app); + epUserApp.setUserId(user.getId()); + epUserApp.setRole(epRole); + userAppSet.add(epUserApp); + user.setUserApps(userAppSet); + userList.add(user); + Mockito.when(dataAccessService.executeNamedQuery("getEPUserByOrgUserId", userParams, null)) + .thenReturn(userList); + CentralUser actual = externalAccessRolesServiceImpl.getUserRoles(user.getOrgUserId(), app.getUebKey()); + assertNotNull(actual); + } + + @SuppressWarnings("unchecked") + @Test + public void getActiveRolesTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(Restrictions.class); + PowerMockito.mockStatic(Criterion.class); + EPApp app = mockApp(); + app.setId(1l); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<EPRole> epRoles = new ArrayList<>(); + EPRole getEPRole = new EPRole(); + getEPRole.setName("Test"); + getEPRole.setId(2l); + getEPRole.setActive(true); + EPRole getEPRole2 = new EPRole(); + getEPRole2.setName("Test2"); + getEPRole2.setId(3l); + getEPRole2.setActive(true); + epRoles.add(getEPRole); + epRoles.add(getEPRole2); + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion active_ynCrt = Restrictions.eq("active", Boolean.TRUE); + Criterion appIdCrt = Restrictions.isNull("appId"); + Criterion andCrit = Restrictions.and(active_ynCrt, appIdCrt); + restrictionsList.add(andCrit); + Mockito.when((List<EPRole>) dataAccessService.getList(EPRole.class, null, restrictionsList, null)) + .thenReturn(epRoles); + final Map<String, Long> params = new HashMap<>(); + params.put("roleId", getEPRole.getId()); + params.put(APP_ID, app.getId()); + List<CentralV2RoleFunction> cenRoleFuncList = new ArrayList<>(); + CentralV2RoleFunction centralV2RoleFunction = new CentralV2RoleFunction("test_type|test_instance|*", + "test_name"); + CentralV2RoleFunction centralV2RoleFunction2 = new CentralV2RoleFunction("test_instance2", "test_name2"); + cenRoleFuncList.add(centralV2RoleFunction); + cenRoleFuncList.add(centralV2RoleFunction2); + Mockito.when(dataAccessService.executeNamedQuery("getAppRoleFunctionList", params, null)) + .thenReturn(cenRoleFuncList); + final Map<String, Long> params2 = new HashMap<>(); + params2.put("roleId", getEPRole2.getId()); + params2.put(APP_ID, app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getAppRoleFunctionList", params2, null)) + .thenReturn(cenRoleFuncList); + List<GlobalRoleWithApplicationRoleFunction> mockGlobalRoles = new ArrayList<>(); + GlobalRoleWithApplicationRoleFunction mockGlobalRole = new GlobalRoleWithApplicationRoleFunction(); + mockGlobalRole.setActive(true); + mockGlobalRole.setAppId(app.getId()); + mockGlobalRole.setRoleId(1111l); + mockGlobalRole.setRoleName("global_test"); + mockGlobalRole.setFunctionCd("test_type|test_code|*"); + mockGlobalRole.setFunctionName("test name"); + mockGlobalRoles.add(mockGlobalRole); + Map<String, Long> params3 = new HashMap<>(); + params3.put("appId", app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getGlobalRoleWithApplicationRoleFunctions", params3, null)) + .thenReturn(mockGlobalRoles); + Mockito.when(EcompPortalUtils.getFunctionCode(centralV2RoleFunction.getCode())).thenReturn("test_instance"); + Mockito.when(EcompPortalUtils.getFunctionCode(centralV2RoleFunction2.getCode())).thenReturn("test_instance2"); + List<CentralV2Role> actual = externalAccessRolesServiceImpl.getActiveRoles(app.getUebKey()); + assertEquals(actual.size(), 3); + } + + @Test + public void bulkUploadRolesFunctionsTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + EPApp app = mockApp(); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<EPRole> applicationRoles = new ArrayList<>(); + EPRole getEPRole = new EPRole(); + getEPRole.setName("Test"); + getEPRole.setId(2l); + getEPRole.setActive(true); + EPRole getEPRole2 = new EPRole(); + getEPRole2.setName("Test2"); + getEPRole2.setId(3l); + getEPRole2.setActive(true); + applicationRoles.add(getEPRole); + applicationRoles.add(getEPRole2); + final Map<String, Long> appParams = new HashMap<>(); + appParams.put("appId", app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null)) + .thenReturn(applicationRoles); + final Map<String, Long> params = new HashMap<>(); + params.put("roleId", getEPRole.getId()); + List<BulkUploadRoleFunction> appRoleFunc = new ArrayList<>(); + BulkUploadRoleFunction bulkUploadRoleFunction = new BulkUploadRoleFunction(); + bulkUploadRoleFunction.setFunctionCd("testcode"); + bulkUploadRoleFunction.setFunctionName("test_name"); + BulkUploadRoleFunction bulkUploadRoleFunction2 = new BulkUploadRoleFunction(); + bulkUploadRoleFunction2.setFunctionCd("menu_testcode2"); + bulkUploadRoleFunction2.setFunctionName("test_name2"); + appRoleFunc.add(bulkUploadRoleFunction); + appRoleFunc.add(bulkUploadRoleFunction2); + Mockito.when(dataAccessService.executeNamedQuery("uploadAllRoleFunctions", params, null)) + .thenReturn(appRoleFunc); + final Map<String, Long> params2 = new HashMap<>(); + params2.put("roleId", getEPRole2.getId()); + List<BulkUploadRoleFunction> appRoleFunc2 = new ArrayList<>(); + appRoleFunc2.add(bulkUploadRoleFunction); + appRoleFunc2.add(bulkUploadRoleFunction2); + Mockito.when(dataAccessService.executeNamedQuery("uploadAllRoleFunctions", params2, null)) + .thenReturn(appRoleFunc2); + ResponseEntity<String> getResponse = new ResponseEntity<>(HttpStatus.CREATED); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + Integer actual = externalAccessRolesServiceImpl.bulkUploadRolesFunctions(app.getUebKey()); + Integer expected = 4; + assertEquals(actual, expected); + } + + @Test + public void bulkUploadPartnerRoleFunctionsTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + EPApp app = mockApp(); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<Role> roles = new ArrayList<>(); + Role role = new Role(); + role.setName("Test"); + role.setId(2l); + role.setActive(true); + Role role2 = new Role(); + role2.setName("Test2"); + role2.setId(3l); + role2.setActive(true); + roles.add(role); + roles.add(role2); + SortedSet<RoleFunction> roleFuncSet = new TreeSet<>(); + RoleFunction roleFunc = new RoleFunction(); + roleFunc.setName("Test Name"); + roleFunc.setCode("testcode"); + RoleFunction roleFunc2 = new RoleFunction(); + roleFunc2.setName("Test Name3"); + roleFunc2.setCode("menu_testcode2"); + roleFuncSet.add(roleFunc); + roleFuncSet.add(roleFunc2); + role.setRoleFunctions(roleFuncSet); + role2.setRoleFunctions(roleFuncSet); + ResponseEntity<String> getResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.PUT), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + externalAccessRolesServiceImpl.bulkUploadPartnerRoleFunctions(app.getUebKey(), roles); + } + + @Test + public void getMenuFunctionsListTest() throws Exception { + EPApp app = mockApp(); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + final Map<String, Long> appParams = new HashMap<>(); + appParams.put(APP_ID, app.getId()); + List<String> expected = new ArrayList<>(); + expected.add("test_menu1"); + expected.add("test_menu2"); + Mockito.when(dataAccessService.executeNamedQuery("getMenuFunctions", appParams, null)).thenReturn(expected); + List<String> actual = externalAccessRolesServiceImpl.getMenuFunctionsList(app.getUebKey()); + assertEquals(expected, actual); + } + + @Test + public void getCentralizedAppsOfUserTest() { + EPUser user = mockUser.mockEPUser(); + Map<String, String> params = new HashMap<>(); + params.put("userId", user.getOrgUserId()); + List<CentralizedApp> expected = new ArrayList<>(); + CentralizedApp centralizedApp = new CentralizedApp(); + centralizedApp.setAppId(2); + centralizedApp.setAppName("testapp1"); + expected.add(centralizedApp); + Mockito.when(dataAccessService.executeNamedQuery("getCentralizedAppsOfUser", params, null)) + .thenReturn(expected); + List<CentralizedApp> actual = externalAccessRolesServiceImpl.getCentralizedAppsOfUser(user.getOrgUserId()); + assertEquals(expected, actual); + } + + @Test + public void ConvertCentralRoleToRoleTest() throws Exception { + ObjectMapper mapper = new ObjectMapper(); + Role role = new Role(); + role.setName("Test"); + role.setId(3l); + role.setActive(true); + SortedSet<RoleFunction> roleFuncSet = new TreeSet<>(); + RoleFunction roleFunc = new RoleFunction(); + roleFunc.setName("Test Name"); + roleFunc.setCode("testcode"); + RoleFunction roleFunc2 = new RoleFunction(); + roleFunc2.setName("Test Name3"); + roleFunc2.setCode("menu_testcode2"); + roleFuncSet.add(roleFunc); + roleFuncSet.add(roleFunc2); + role.setRoleFunctions(roleFuncSet); + String roleInfo = mapper.writeValueAsString(role); + Role actual = externalAccessRolesServiceImpl.ConvertCentralRoleToRole(roleInfo); + assertNotNull(actual); + } + + @Test + public void convertV2CentralRoleListToOldVerisonCentralRoleListTest() { + List<CentralV2Role> v2CenRoleList = new ArrayList<>(); + CentralV2Role cenV2Role = new CentralV2Role(2l, "test1"); + CentralV2RoleFunction CentralV2Role = new CentralV2RoleFunction("testcode", "test_name"); + SortedSet<CentralV2RoleFunction> setV2RoleFuncs = new TreeSet<>(); + setV2RoleFuncs.add(CentralV2Role); + cenV2Role.setRoleFunctions(setV2RoleFuncs); + v2CenRoleList.add(cenV2Role); + List<CentralRole> actual = externalAccessRolesServiceImpl.convertV2CentralRoleListToOldVerisonCentralRoleList(v2CenRoleList); + assertEquals(1, actual.size()); + } } diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/FunctionalMenuServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/FunctionalMenuServiceImplTest.java deleted file mode 100644 index c954fcbd..00000000 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/FunctionalMenuServiceImplTest.java +++ /dev/null @@ -1,92 +0,0 @@ -package org.onap.portalapp.portal.service; -/*- - * ============LICENSE_START========================================== - * ONAP Portal - * =================================================================== - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * =================================================================== - * - * Unless otherwise specified, all software contained herein is licensed - * under the Apache License, Version 2.0 (the "License"); - * you may not use this software except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Unless otherwise specified, all documentation contained herein is licensed - * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); - * you may not use this documentation except in compliance with the License. - * You may obtain a copy of the License at - * - * https://creativecommons.org/licenses/by/4.0/ - * - * Unless required by applicable law or agreed to in writing, documentation - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ============LICENSE_END============================================ - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -//package org.openecomp.portalapp.portal.test.service; -// -//import static org.junit.Assert.assertTrue; -// -//import java.util.ArrayList; -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -// -//import org.junit.Test; -//import org.openecomp.portalapp.portal.service.FunctionalMenuService; -//import org.openecomp.portalapp.portal.transport.BusinessCardApplicationRole; -//import org.openecomp.portalapp.portal.transport.FunctionalMenuRole; -//import org.openecomp.portalapp.test.framework.ApplicationCommonContextTestSuite; -//import org.springframework.beans.factory.annotation.Autowired; -// -//public class FunctionalMenuServiceImplTest extends ApplicationCommonContextTestSuite { -// -// @Autowired -// FunctionalMenuService functionalMenuService; -// -// @Test -// public void getAppListTestService() throws Exception { -// -// String userId = "guestT"; -// List<BusinessCardApplicationRole> userAppRolesActualResult = null; -// -// List<BusinessCardApplicationRole> userAppRolesExpectedResult = new ArrayList<BusinessCardApplicationRole>(); -// BusinessCardApplicationRole businessCardApplicationRole = new BusinessCardApplicationRole(); -// businessCardApplicationRole.setAppName("ECOMP Portal"); -// businessCardApplicationRole.setRoleName("System Administrator"); -// userAppRolesExpectedResult.add(businessCardApplicationRole); -// Map<String, String> params = new HashMap<String, String>(); -// params.put("userId", userId); -// userAppRolesActualResult = functionalMenuService.getUserAppRolesList(userId); -// assertTrue(userAppRolesActualResult.contains(businessCardApplicationRole)); -// -// } -// -// @Test -// public void getFunctionalMenuRoleTest() throws Exception { -// -// FunctionalMenuRole expectedFunctionalMenuRole = new FunctionalMenuRole(); -// expectedFunctionalMenuRole.setId(new Integer(-1)); -// -// expectedFunctionalMenuRole.setMenuId((long) 137); -// expectedFunctionalMenuRole.setAppId(new Integer(456)); -// expectedFunctionalMenuRole.setRoleId(new Integer(6214)); -// List<FunctionalMenuRole> actualFunctionalMenuRoleList = null; -// actualFunctionalMenuRoleList = functionalMenuService.getFunctionalMenuRole(); -// assertTrue(actualFunctionalMenuRoleList.contains(expectedFunctionalMenuRole)); -// -// } -//} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/MicroserviceServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/MicroserviceServiceImplTest.java new file mode 100644 index 00000000..fba7e6d2 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/MicroserviceServiceImplTest.java @@ -0,0 +1,207 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.portal.service; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.ArrayList; +import java.util.List; + +import javax.crypto.BadPaddingException; + +import org.hibernate.criterion.Criterion; +import org.hibernate.criterion.Restrictions; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.domain.MicroserviceData; +import org.onap.portalapp.portal.domain.MicroserviceParameter; +import org.onap.portalapp.portal.utils.EPCommonSystemProperties; +import org.onap.portalsdk.core.onboarding.util.CipherUtil; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.service.DataAccessServiceImpl; +import org.onap.portalsdk.core.util.SystemProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({Criterion.class, Restrictions.class, CipherUtil.class, EPCommonSystemProperties.class, SystemProperties.class, Restrictions.class}) +public class MicroserviceServiceImplTest { + + @Mock + DataAccessService dataAccessService = new DataAccessServiceImpl(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @InjectMocks + MicroserviceServiceImpl microserviceServiceImpl = new MicroserviceServiceImpl(); + + @Test + public void saveMicroserviceTest() throws Exception { + MicroserviceData microserviceData = new MicroserviceData(); + List<MicroserviceParameter> microserviceParameters = new ArrayList<>(); + MicroserviceParameter microserviceParameter = new MicroserviceParameter(); + microserviceParameter.setId(1l); + microserviceParameter.setPara_key("test"); + microserviceParameter.setPara_value("test"); + microserviceParameters.add(microserviceParameter); + microserviceData.setActive("true"); + microserviceData.setAppId(1l); + microserviceData.setId(1l); + microserviceData.setParameterList(microserviceParameters); + Long actual = microserviceServiceImpl.saveMicroservice(microserviceData); + assertEquals((Long)1l, actual); + } + + @Test + public void saveServiceParametersTest() throws Exception { + MicroserviceData microserviceData = new MicroserviceData(); + List<MicroserviceParameter> microserviceParameters = new ArrayList<>(); + MicroserviceParameter microserviceParameter = new MicroserviceParameter(); + microserviceParameter.setId(1l); + microserviceParameter.setPara_key("test"); + microserviceParameter.setPara_value("test"); + microserviceParameters.add(microserviceParameter); + microserviceData.setActive("true"); + microserviceData.setAppId(1l); + microserviceData.setId(1l); + microserviceData.setParameterList(microserviceParameters); + microserviceServiceImpl.saveServiceParameters(1l, microserviceParameters); + } + + @SuppressWarnings("unchecked") + @Test + public void getMicroserviceDataByIdTest() throws Exception { + PowerMockito.mockStatic(Restrictions.class); + PowerMockito.mockStatic(Criterion.class); + MicroserviceData microserviceData = new MicroserviceData(); + List<MicroserviceParameter> microserviceParameters = new ArrayList<>(); + MicroserviceParameter microserviceParameter = new MicroserviceParameter(); + microserviceParameter.setId(1l); + microserviceParameter.setPara_key("test"); + microserviceParameter.setPara_value("test"); + microserviceParameters.add(microserviceParameter); + microserviceData.setActive("true"); + microserviceData.setAppId(1l); + microserviceData.setId(1l); + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion idCriterion = Restrictions.eq("id", 1l); + restrictionsList.add(idCriterion); + List<MicroserviceData> microserviceDatas = new ArrayList<>(); + microserviceDatas.add(microserviceData); + Mockito.when((List<MicroserviceData>) dataAccessService.getList(MicroserviceData.class, null, restrictionsList, null)).thenReturn(microserviceDatas); + List<Criterion> restrictionsList2 = new ArrayList<Criterion>(); + Criterion serviceIdCriterion = Restrictions.eq("serviceId", 1l); + restrictionsList2.add(serviceIdCriterion); + Mockito.when((List<MicroserviceParameter>) dataAccessService.getList(MicroserviceParameter.class, null, restrictionsList2, null)).thenReturn(microserviceParameters); + MicroserviceData actual = microserviceServiceImpl.getMicroserviceDataById(1l); + assertNotNull(actual); + } + + @SuppressWarnings({ "unchecked", "deprecation" }) + @Test + public void getMicroserviceDataTest() throws Exception { + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + PowerMockito.mockStatic(Restrictions.class); + PowerMockito.mockStatic(Criterion.class); + List<MicroserviceParameter> microserviceParameters = new ArrayList<>(); + MicroserviceData microserviceData = new MicroserviceData(); + MicroserviceParameter microserviceParameter = new MicroserviceParameter(); + microserviceParameter.setId(1l); + microserviceParameter.setPara_key("test"); + microserviceParameter.setPara_value("test"); + microserviceParameters.add(microserviceParameter); + microserviceData.setActive("true"); + microserviceData.setAppId(1l); + microserviceData.setPassword("xyz"); + microserviceData.setId(1l); + List<MicroserviceData> microserviceDatas = new ArrayList<>(); + microserviceDatas.add(microserviceData); + Mockito.when((List<MicroserviceData>) dataAccessService.getList(MicroserviceData.class, null)).thenReturn(microserviceDatas); + List<Criterion> restrictionsList2 = new ArrayList<Criterion>(); + Criterion serviceIdCriterion = Restrictions.eq("serviceId", 1l); + restrictionsList2.add(serviceIdCriterion); + Mockito.when((List<MicroserviceParameter>) dataAccessService.getList(MicroserviceParameter.class, null, restrictionsList2, null)).thenReturn(microserviceParameters); + Mockito.when(CipherUtil.decryptPKC("xyz", + SystemProperties.getProperty(SystemProperties.Decryption_Key))).thenReturn("abc"); + List<MicroserviceData> actual = microserviceServiceImpl.getMicroserviceData(); + assertNotNull(actual); + } + + @SuppressWarnings({ "unchecked", "deprecation", "static-access" }) + @Test + public void getMicroserviceDataBadPaddingExceptionTest() throws Exception { + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + PowerMockito.mockStatic(Restrictions.class); + PowerMockito.mockStatic(Criterion.class); + List<MicroserviceParameter> microserviceParameters = new ArrayList<>(); + MicroserviceData microserviceData = new MicroserviceData(); + MicroserviceParameter microserviceParameter = new MicroserviceParameter(); + microserviceParameter.setId(1l); + microserviceParameter.setPara_key("test"); + microserviceParameter.setPara_value("test"); + microserviceParameters.add(microserviceParameter); + microserviceData.setActive("true"); + microserviceData.setAppId(1l); + microserviceData.setPassword("xyz"); + microserviceData.setId(1l); + List<MicroserviceData> microserviceDatas = new ArrayList<>(); + microserviceDatas.add(microserviceData); + Mockito.when((List<MicroserviceData>) dataAccessService.getList(MicroserviceData.class, null)).thenReturn(microserviceDatas); + List<Criterion> restrictionsList2 = new ArrayList<Criterion>(); + Criterion serviceIdCriterion = Restrictions.eq("serviceId", 1l); + restrictionsList2.add(serviceIdCriterion); + Mockito.when((List<MicroserviceParameter>) dataAccessService.getList(MicroserviceParameter.class, null, restrictionsList2, null)).thenReturn(microserviceParameters); + Mockito.when(CipherUtil.decryptPKC("xyz", + SystemProperties.getProperty(SystemProperties.Decryption_Key))).thenThrow(BadPaddingException.class); + List<MicroserviceData> actual = microserviceServiceImpl.getMicroserviceData(); + assertNotNull(actual); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/PersUserWidgetServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/PersUserWidgetServiceImplTest.java new file mode 100644 index 00000000..67c56eb3 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/PersUserWidgetServiceImplTest.java @@ -0,0 +1,145 @@ +/* +* ============LICENSE_START======================================================= +* ONAP : PORTAL +* ================================================================================ +* Copyright 2018 TechMahindra +*================================================================================= +* Licensed 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 +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* ============LICENSE_END========================================================= +*/ +package org.onap.portalapp.portal.service; + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.domain.PersUserWidgetSelection; +import org.onap.portalapp.portal.framework.MockitoTestSuite; +import org.onap.portalsdk.core.service.DataAccessService; + +public class PersUserWidgetServiceImplTest { + + @Mock + DataAccessService dataAccessService; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @InjectMocks + PersUserWidgetServiceImpl persUserWidgetServiceImpl = new PersUserWidgetServiceImpl(); + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + NullPointerException nullPointerException = new NullPointerException(); + MockEPUser mockUser = new MockEPUser(); + + + @Test(expected = IllegalArgumentException.class) + public void setPersUserAppValueIfUserNull() { + persUserWidgetServiceImpl.setPersUserAppValue(null, null, false); + } + + @Test + public void setPersUserAppValueTest() { + EPUser user = mockUser.mockEPUser(); + List<PersUserWidgetSelection> persUserAppSelectionList = new ArrayList<>(); + PersUserWidgetSelection persUserWidgetSelection = new PersUserWidgetSelection(); + persUserWidgetSelection.setId((long) 1); + persUserAppSelectionList.add(persUserWidgetSelection); + Mockito.when(dataAccessService.getList(PersUserWidgetSelection.class, "test", null, null)) + .thenReturn(persUserAppSelectionList); + persUserWidgetServiceImpl.setPersUserAppValue(user, (long)999, false); + } + + public void setPersUserAppValueTestPass() { + EPUser user = mockUser.mockEPUser(); + List<PersUserWidgetSelection> persUserAppSelectionList = new ArrayList<>(); + PersUserWidgetSelection persUserWidgetSelection = new PersUserWidgetSelection(); + persUserWidgetSelection.setId((long) 1); + persUserAppSelectionList.add(persUserWidgetSelection); + Mockito.when(dataAccessService.getList(PersUserWidgetSelection.class, "test", null, null)) + .thenReturn(persUserAppSelectionList); + persUserWidgetServiceImpl.setPersUserAppValue(user, (long)999, false); + } + + @Test + public void setPersUserAppValueIfSelectTest_DeleteDomain() { + EPUser user = mockUser.mockEPUser(); + List<PersUserWidgetSelection> persUserAppSelectionList = new ArrayList<>(); + PersUserWidgetSelection persUserWidgetSelection = new PersUserWidgetSelection(); + persUserWidgetSelection.setId((long) 1); + persUserAppSelectionList.add(persUserWidgetSelection); + Mockito.when(dataAccessService.getList(PersUserWidgetSelection.class, "test", null, null)) + .thenReturn(persUserAppSelectionList); + persUserWidgetServiceImpl.setPersUserAppValue(user, (long)999, true); + Mockito.doNothing().when(dataAccessService).deleteDomainObject(persUserWidgetSelection, null); + } + + @Test + public void setPersUserAppValueIfSelectTest_SaveDomain() { + EPUser user = mockUser.mockEPUser(); + List<PersUserWidgetSelection> persUserAppSelectionList = new ArrayList<>(); + PersUserWidgetSelection persUserWidgetSelection = new PersUserWidgetSelection(); + persUserWidgetSelection.setId(null); + persUserAppSelectionList.add(persUserWidgetSelection); + Mockito.when(dataAccessService.getList(PersUserWidgetSelection.class, "test", null, null)) + .thenReturn(persUserAppSelectionList); + Mockito.doNothing().when(dataAccessService).saveDomainObject(persUserWidgetSelection, null); + persUserWidgetServiceImpl.setPersUserAppValue(user, (long)999, true); + persUserWidgetSelection.setStatusCode("S"); + Mockito.doNothing().when(dataAccessService).saveDomainObject(persUserWidgetSelection, null); + } + + @Test + public void setPersUserAppValueWithoutSelectTest_DeleteDomain() { + EPUser user = mockUser.mockEPUser(); + List<PersUserWidgetSelection> persUserAppSelectionList = new ArrayList<>(); + PersUserWidgetSelection persUserWidgetSelection = new PersUserWidgetSelection(); + persUserAppSelectionList.add(persUserWidgetSelection); + Mockito.when(dataAccessService.getList(PersUserWidgetSelection.class, "test", null, null)) + .thenReturn(persUserAppSelectionList); + persUserWidgetServiceImpl.setPersUserAppValue(user, (long)999, false); + persUserWidgetSelection.setId((long) 1); + Mockito.doNothing().when(dataAccessService).deleteDomainObject(persUserWidgetSelection, null); + } + + @Test + public void setPersUserAppValueWithoutSelectTest_SaveDomain() { + EPUser user = mockUser.mockEPUser(); + List<PersUserWidgetSelection> persUserAppSelectionList = new ArrayList<>(); + PersUserWidgetSelection persUserWidgetSelection = new PersUserWidgetSelection(); + persUserWidgetSelection.setId(null); + persUserAppSelectionList.add(persUserWidgetSelection); + Mockito.when(dataAccessService.getList(PersUserWidgetSelection.class, "test", null, null)) + .thenReturn(persUserAppSelectionList); + persUserWidgetServiceImpl.setPersUserAppValue(user, (long)999, false); + persUserWidgetSelection.setStatusCode("H"); + Mockito.doNothing().when(dataAccessService).saveDomainObject(persUserWidgetSelection, null); + } + + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/PortalAdminServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/PortalAdminServiceImplTest.java new file mode 100644 index 00000000..ffad364c --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/PortalAdminServiceImplTest.java @@ -0,0 +1,300 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.portal.service; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletResponse; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.criterion.Criterion; +import org.hibernate.criterion.Restrictions; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.EPApp; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.transport.FieldsValidator; +import org.onap.portalapp.portal.transport.PortalAdmin; +import org.onap.portalapp.portal.utils.EPCommonSystemProperties; +import org.onap.portalapp.portal.utils.EcompPortalUtils; +import org.onap.portalapp.portal.utils.PortalConstants; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.service.DataAccessServiceImpl; +import org.onap.portalsdk.core.util.SystemProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ EcompPortalUtils.class, Criterion.class, Restrictions.class, PortalConstants.class, + SystemProperties.class, EPCommonSystemProperties.class }) +public class PortalAdminServiceImplTest { + + @Mock + DataAccessService dataAccessService = new DataAccessServiceImpl(); + + @Mock + EPAppCommonServiceImpl epAppCommonServiceImpl = new EPAppCommonServiceImpl(); + + @Mock + SearchServiceImpl searchServiceImpl = new SearchServiceImpl(); + + @Mock + SessionFactory sessionFactory; + + @Mock + Session session; + + @Mock + Transaction transaction; + + @Mock + RestTemplate template = new RestTemplate(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + Mockito.when(sessionFactory.openSession()).thenReturn(session); + Mockito.when(session.beginTransaction()).thenReturn(transaction); + } + + @After + public void after() { + session.close(); + } + + @InjectMocks + PortalAdminServiceImpl portalAdminServiceImpl = new PortalAdminServiceImpl(); + + public EPApp mockApp() { + EPApp app = new EPApp(); + app.setName("Test"); + app.setImageUrl("test"); + app.setNameSpace("com.test.app"); + app.setCentralAuth(true); + app.setDescription("test"); + app.setNotes("test"); + app.setUrl("test"); + app.setId((long) 1); + app.setAppRestEndpoint("test"); + app.setAlternateUrl("test"); + app.setName("test"); + app.setMlAppName("test"); + app.setMlAppAdminId("test"); + app.setUsername("test"); + app.setAppPassword("test"); + app.setOpen(false); + app.setEnabled(true); + app.setUebKey("test"); + app.setUebSecret("test"); + app.setUebTopicName("test"); + app.setAppType(1); + return app; + } + + MockEPUser mockUser = new MockEPUser(); + + @SuppressWarnings("unchecked") + @Test + public void getPortalAdminsTest() { + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + List<PortalAdmin> portalAdmins = new ArrayList<>(); + PortalAdmin portalAdmin = new PortalAdmin(); + portalAdmin.setFirstName("guest"); + portalAdmin.setLastName("test"); + portalAdmin.setLoginId("test"); + portalAdmin.setUserId(1l); + portalAdmins.add(portalAdmin); + Map<String, String> params = new HashMap<>(); + params.put("adminRoleId", "1"); + Mockito.when((List<PortalAdmin>) dataAccessService.executeNamedQuery("getPortalAdmins", params, null)) + .thenReturn(portalAdmins); + List<PortalAdmin> actual = portalAdminServiceImpl.getPortalAdmins(); + assertEquals(1, actual.size()); + } + + @Test + public void getPortalAdminsExceptionTest() { + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + List<PortalAdmin> portalAdmins = new ArrayList<>(); + PortalAdmin portalAdmin = new PortalAdmin(); + portalAdmin.setFirstName("guest"); + portalAdmin.setLastName("test"); + portalAdmin.setLoginId("test"); + portalAdmin.setUserId(1l); + portalAdmins.add(portalAdmin); + Map<String, String> params = new HashMap<>(); + params.put("adminRoleId", "1"); + Mockito.doThrow(new NullPointerException()).when(dataAccessService).executeNamedQuery("getPortalAdmins", params, + null); + List<PortalAdmin> actual = portalAdminServiceImpl.getPortalAdmins(); + assertNull(actual); + } + + @SuppressWarnings("unchecked") + @Test + public void createPortalAdminNewUserTest() { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(PortalConstants.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(Restrictions.class); + PowerMockito.mockStatic(Criterion.class); + EPUser user = mockUser.mockEPUser(); + EPApp app = mockApp(); + List<EPUser> users = new ArrayList<>(); + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion orgUserIdCriterion = Restrictions.eq("orgUserId", user.getOrgUserId()); + restrictionsList.add(orgUserIdCriterion); + Mockito.when((List<EPUser>) dataAccessService.getList(EPUser.class, null, restrictionsList, null)) + .thenReturn(users); + List<PortalAdmin> portalAdmins = new ArrayList<>(); + Mockito.when(dataAccessService.executeSQLQuery(Matchers.anyString(), Matchers.any() , Matchers.anyMap())) + .thenReturn(portalAdmins); + Mockito.when(searchServiceImpl.searchUserByUserId(user.getOrgUserId())).thenReturn(user); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + Mockito.when( + EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn(true); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn("@test.com"); + Mockito.when(epAppCommonServiceImpl.getApp(PortalConstants.PORTAL_APP_ID)).thenReturn(app); + ResponseEntity<String> addResponse = new ResponseEntity<>(HttpStatus.CREATED); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(addResponse); + FieldsValidator actual = portalAdminServiceImpl.createPortalAdmin(user.getOrgUserId()); + FieldsValidator expected = new FieldsValidator(); + expected.setHttpStatusCode(Long.valueOf(HttpServletResponse.SC_OK)); + assertEquals(expected, actual); + } + + @SuppressWarnings("unchecked") + @Test + public void createPortalAdminExistingUserTest() { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(PortalConstants.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(Restrictions.class); + PowerMockito.mockStatic(Criterion.class); + EPUser user = mockUser.mockEPUser(); + EPApp app = mockApp(); + List<EPUser> users = new ArrayList<>(); + users.add(user); + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion orgUserIdCriterion = Restrictions.eq("orgUserId", user.getOrgUserId()); + restrictionsList.add(orgUserIdCriterion); + Mockito.when((List<EPUser>) dataAccessService.getList(EPUser.class, null, restrictionsList, null)) + .thenReturn(users); + List<PortalAdmin> portalAdmins = new ArrayList<>(); + Mockito.when(dataAccessService.executeSQLQuery(Matchers.anyString(), Matchers.any() , Matchers.anyMap())) + .thenReturn(portalAdmins); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + Mockito.when( + EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn(true); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn("@test.com"); + Mockito.when(epAppCommonServiceImpl.getApp(PortalConstants.PORTAL_APP_ID)).thenReturn(app); + ResponseEntity<String> addResponse = new ResponseEntity<>(HttpStatus.CREATED); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(addResponse); + FieldsValidator actual = portalAdminServiceImpl.createPortalAdmin(user.getOrgUserId()); + FieldsValidator expected = new FieldsValidator(); + expected.setHttpStatusCode(Long.valueOf(HttpServletResponse.SC_OK)); + assertEquals(expected, actual); + } + + @SuppressWarnings("unchecked") + @Test + public void deletePortalAdminTest() { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(PortalConstants.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(Restrictions.class); + PowerMockito.mockStatic(Criterion.class); + EPUser user = mockUser.mockEPUser(); + EPApp app = mockApp(); + List<EPUser> users = new ArrayList<>(); + users.add(user); + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion orgUserIdCriterion = Restrictions.eq("id", user.getId()); + restrictionsList.add(orgUserIdCriterion); + Mockito.when((List<EPUser>) dataAccessService.getList(EPUser.class, null, restrictionsList, null)) + .thenReturn(users); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + Mockito.when( + EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn(true); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn("@test.com"); + Mockito.when(epAppCommonServiceImpl.getApp(PortalConstants.PORTAL_APP_ID)).thenReturn(app); + ResponseEntity<String> addResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(addResponse); + FieldsValidator actual = portalAdminServiceImpl.deletePortalAdmin(user.getId()); + FieldsValidator expected = new FieldsValidator(); + expected.setHttpStatusCode(Long.valueOf(HttpServletResponse.SC_OK)); + assertEquals(expected, actual); + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/SearchServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/SearchServiceImplTest.java new file mode 100644 index 00000000..61244ddd --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/SearchServiceImplTest.java @@ -0,0 +1,141 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.portal.service; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNull; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.utils.EPCommonSystemProperties; +import org.onap.portalapp.portal.utils.EcompPortalUtils; +import org.onap.portalapp.portal.utils.PortalConstants; +import org.onap.portalsdk.core.command.support.SearchResult; +import org.onap.portalsdk.core.util.SystemProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ EcompPortalUtils.class, PortalConstants.class, SystemProperties.class, + EPCommonSystemProperties.class }) +public class SearchServiceImplTest { + + @InjectMocks + SearchServiceImpl searchServiceImpl = new SearchServiceImpl(); + + @Mock + EPLdapService epLdapService; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + MockEPUser mockUser = new MockEPUser(); + + @SuppressWarnings("unchecked") + @Test + public void searchUsersInPhoneBookTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + List<String> tokens = new ArrayList<>(); + tokens.add("ts1234"); + tokens.add("TestName"); + EPUser user = new EPUser(); + user.setOrgUserId("ts1234"); + user.setFirstName("TestName"); + Mockito.when(EcompPortalUtils.parsingByRegularExpression(Matchers.anyString(), Matchers.anyString())).thenReturn(tokens); + SearchResult searchResult = new SearchResult(); + searchResult.add(user); + Mockito.when(epLdapService.searchPost(Matchers.any(EPUser.class), Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.anyInt(), Matchers.anyInt(), Matchers.anyInt())).thenReturn(searchResult); + String actual = searchServiceImpl.searchUsersInPhoneBook("ts1234"); + assertNotEquals("[]", actual); + } + + @SuppressWarnings("unchecked") + @Test + public void searchUsersInPhoneBookFirtAndLastNameTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + List<String> tokens = new ArrayList<>(); + tokens.add("ts1234"); + tokens.add("TestFirstName"); + tokens.add("TestLastName"); + EPUser user = new EPUser(); + user.setOrgUserId("ts1234"); + user.setFirstName("TestFirstName"); + user.setLastName("TestLastName"); + Mockito.when(EcompPortalUtils.parsingByRegularExpression(Matchers.anyString(), Matchers.anyString())).thenReturn(tokens); + SearchResult searchResult = new SearchResult(); + searchResult.add(user); + Mockito.when(epLdapService.searchPost(Matchers.any(EPUser.class), Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.anyInt(), Matchers.anyInt(), Matchers.anyInt())).thenReturn(searchResult); + String actual = searchServiceImpl.searchUsersInPhoneBook("ts1234"); + assertNotEquals("[]", actual); + } + + @SuppressWarnings("unchecked") + @Test + public void searchUserByUserIdTest() throws Exception { + EPUser user = new EPUser(); + user.setOrgUserId("ts1234"); + SearchResult searchResult = new SearchResult(); + searchResult.add(user); + Mockito.when(epLdapService.searchPost(Matchers.any(EPUser.class), Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.anyInt(), Matchers.anyInt(), Matchers.anyInt())).thenReturn(searchResult); + EPUser actual = searchServiceImpl.searchUserByUserId("ts1234"); + assertEquals(user, actual); + } + + @Test + public void searchUserByUserIdExceptionTest() throws Exception { + Mockito.doThrow(new NullPointerException()).when(epLdapService).searchPost(Matchers.any(EPUser.class), Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.anyInt(), Matchers.anyInt(), Matchers.anyInt()); + EPUser actual = searchServiceImpl.searchUserByUserId("ts1234"); + assertNull(actual); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/SharedContextServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/SharedContextServiceImplTest.java new file mode 100644 index 00000000..417c8b06 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/SharedContextServiceImplTest.java @@ -0,0 +1,131 @@ +/* + * ============LICENSE_START======================================================= + * ONAP PORTAL + * ================================================================================ + * Copyright 2018 TechMahindra + *================================================================================= + * Licensed 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.portalapp.portal.service; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import org.hibernate.criterion.Criterion; +import org.hibernate.criterion.Restrictions; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.SharedContext; +import org.onap.portalsdk.core.service.DataAccessService; + +public class SharedContextServiceImplTest { + + @Mock + DataAccessService dataAccessService; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @InjectMocks + SharedContextServiceImpl sharedContextServiceImpl = new SharedContextServiceImpl(); + + MockEPUser mockUser = new MockEPUser(); + + @Test + public void getSharedContextsTest() { + String contextId = "test"; + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion contextIdCrit = Restrictions.eq("context_id", contextId); + restrictionsList.add(contextIdCrit); + List<SharedContext> contextsList = new ArrayList<>(); + SharedContext sharedContext = new SharedContext(); + contextsList.add(sharedContext); + Mockito.when((List<SharedContext>) dataAccessService.getList(SharedContext.class, null)) + .thenReturn(contextsList); + sharedContextServiceImpl.getSharedContexts("test"); + } + + @Test + public void getSharedContextsTest_usingKey() { + String contextId = "test"; + String key = "key"; + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion contextIdCrit = Restrictions.eq("context_id", "test"); + Criterion keyCrit = Restrictions.eq("ckey", "key"); + restrictionsList.add(contextIdCrit); + restrictionsList.add(keyCrit); + List<SharedContext> contextsList = new ArrayList<>(); + SharedContext sharedContext = new SharedContext(); + contextsList.add(sharedContext); + Mockito.when((List<SharedContext>) dataAccessService.getList(SharedContext.class, null)) + .thenReturn(contextsList); + sharedContextServiceImpl.getSharedContext("test", "key"); + } + + @Test + public void addSharedContextTest() { + SharedContext context = new SharedContext(); + context.setContext_id("test"); + context.setCkey("key"); + context.setCvalue("demo"); + context.setId(1l); + Mockito.doNothing().when(dataAccessService).saveDomainObject(context, null); + sharedContextServiceImpl.addSharedContext("test", "key", "demo"); + } + + @Test + public void saveSharedContext() { + SharedContext context = new SharedContext(); + Mockito.doNothing().when(dataAccessService).saveDomainObject(context, null); + sharedContextServiceImpl.saveSharedContext(context);//("test", "key", "demo"); + } + + @Test + public void deleteSharedContextsTest() { + List<SharedContext> contextsList = new ArrayList<>(); + SharedContext sharedContext = new SharedContext(); + contextsList.add(sharedContext); + String contextId = "test"; + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion contextIdCrit = Restrictions.eq("context_id", contextId); + restrictionsList.add(contextIdCrit); + Mockito.when((List<SharedContext>) dataAccessService.getList(SharedContext.class, null)) + .thenReturn(contextsList); + sharedContextServiceImpl.deleteSharedContexts("test"); + } + + @Test + public void deleteSharedContextTest() { + SharedContext context = new SharedContext(); + Mockito.doNothing().when(dataAccessService).deleteDomainObject(context, null); + sharedContextServiceImpl.deleteSharedContext(context); + } + + @Test + public void expireSharedContextsTest() { + final SimpleDateFormat dateFormat = new SimpleDateFormat("2018-02-22 10:00:00"); + Date expiredDateTime = new Date(System.currentTimeMillis() - 3600 * 1000); + final String whereClause = " create_time < '" + dateFormat.format(expiredDateTime) + "'"; + Mockito.doNothing().when(dataAccessService).deleteDomainObjects(SharedContext.class, whereClause, null); + sharedContextServiceImpl.expireSharedContexts(3600); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserNotificationServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserNotificationServiceImplTest.java new file mode 100644 index 00000000..ad41d5f6 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserNotificationServiceImplTest.java @@ -0,0 +1,209 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.portal.service; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.domain.EPUserNotification; +import org.onap.portalapp.portal.domain.EcompAppRole; +import org.onap.portalapp.portal.transport.EpNotificationItem; +import org.onap.portalapp.portal.transport.EpNotificationItemVO; +import org.onap.portalapp.portal.transport.EpRoleNotificationItem; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.service.DataAccessServiceImpl; + +public class UserNotificationServiceImplTest { + + @Mock + DataAccessService dataAccessService = new DataAccessServiceImpl(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @InjectMocks + UserNotificationServiceImpl userNotificationServiceImpl = new UserNotificationServiceImpl(); + + MockEPUser mockUser = new MockEPUser(); + + @Test + public void getNotificationsTest() { + EPUser user = mockUser.mockEPUser(); + Map<String, String> params = new HashMap<>(); + params.put("user_id", String.valueOf(user.getId())); + List<EpNotificationItem> mockNotificationList = new ArrayList<>(); + Mockito.when(dataAccessService.executeNamedQuery("getNotifications", params, null)).thenReturn(mockNotificationList); + List<EpNotificationItem> notificationList = userNotificationServiceImpl.getNotifications(user.getId()); + assertEquals(notificationList, mockNotificationList); + } + + @Test + public void getNotificationHistoryVOTest() { + EPUser user = mockUser.mockEPUser(); + Map<String, String> params = new HashMap<String, String>(); + params.put("user_id", String.valueOf(user.getId())); + List<EpNotificationItemVO> mockNotificationListVO = new ArrayList<>(); + Mockito.when(dataAccessService.executeNamedQuery("getNotificationHistoryVO", + params, null)).thenReturn(mockNotificationListVO); + List<EpNotificationItemVO> notificationListVO = userNotificationServiceImpl.getNotificationHistoryVO(user.getId()); + assertEquals(notificationListVO,mockNotificationListVO); + } + + @Test + public void getAdminNotificationVOSTest() { + EPUser user = mockUser.mockEPUser(); + Map<String, String> params = new HashMap<String, String>(); + params.put("user_id", String.valueOf(user.getId())); + List<EpNotificationItemVO> mockAdminNotificationListItemVO = new ArrayList<>(); + Mockito.when(dataAccessService.executeNamedQuery("getAdminNotificationHistoryVO", + params, null)).thenReturn(mockAdminNotificationListItemVO); + List<EpNotificationItemVO> adminNotificationListItemVO = userNotificationServiceImpl.getAdminNotificationVOS(user.getId()); + assertEquals(adminNotificationListItemVO,mockAdminNotificationListItemVO); + } + + @Test + public void getNotificationRolesTest() { + Map<String, String> params = new HashMap<String, String>(); + params.put("notificationId", Long.toString(1l)); + List<EpRoleNotificationItem> mockRoleNotifList = new ArrayList<>(); + Mockito.when(dataAccessService.executeNamedQuery("getNotificationRoles", + params, null)).thenReturn(mockRoleNotifList); + List<EpRoleNotificationItem> roleNotifList = userNotificationServiceImpl.getNotificationRoles(1l); + assertEquals(roleNotifList,mockRoleNotifList); + } + + @Test + public void getAppRoleListTest() { + List<EcompAppRole> mockAppRoleList = new ArrayList<>(); + Mockito.when(dataAccessService + .executeNamedQuery("getEpNotificationAppRoles", null, null)).thenReturn(mockAppRoleList); + List<EcompAppRole> appRoleList = userNotificationServiceImpl.getAppRoleList(); + assertEquals(mockAppRoleList, appRoleList); + } + + @Test + public void setNotificationReadTest() { + EPUserNotification mockUserNotification = new EPUserNotification(); + mockUserNotification.setNotificationId(1l); + mockUserNotification.setId(1l); + mockUserNotification.setUpdateTime(new Date()); + mockUserNotification.setViewed("Y"); + mockUserNotification.setUserId((long) 1); + Mockito.doNothing().when(dataAccessService).saveDomainObject(mockUserNotification, null); + userNotificationServiceImpl.setNotificationRead(1l, 1); + } + + @Test + public void saveNotificationTest() throws Exception { + EpNotificationItem epNotificationItem = new EpNotificationItem(); + List<Long> roleIdList = new ArrayList<>(); + Long roleId = new Long(1l); + Long roleId2 = new Long(16l); + roleIdList.add(roleId); + roleIdList.add(roleId2); + epNotificationItem.setIsForAllRoles("N"); + epNotificationItem.setRoleIds(roleIdList); + epNotificationItem.setNotificationId(1l); + Mockito.doNothing().when(dataAccessService).saveDomainObject(epNotificationItem, null); + userNotificationServiceImpl.saveNotification(epNotificationItem); + } + + @Test + public void getUsersByOrgIdsTest() { + Map<String, Object> params = new HashMap<String, Object>(); + params.put("OrgIds", "test"); + List<EPUser> mockUserList = new ArrayList<>(); + Mockito.when(dataAccessService.executeNamedQuery("getUsersByOrgIdsNotifications", + params, null)).thenReturn(mockUserList); + List<String> orgIdsList = new ArrayList<>(); + String orgId = "test"; + orgIdsList.add(orgId); + List<EPUser> userList = userNotificationServiceImpl.getUsersByOrgIds(orgIdsList); + assertEquals(userList, mockUserList); + } + + @Test + public void getMessageRecipientsTest() { + Map<String, String> params = new HashMap<>(); + params.put("notificationId", Long.toString(1l)); + List<String> mockActiveUsers = new ArrayList<>(); + Mockito.when(dataAccessService.executeNamedQuery("messageRecipients", + params, null)).thenReturn(mockActiveUsers); + List<String> activeUsers = userNotificationServiceImpl.getMessageRecipients(1l); + assertEquals(activeUsers, mockActiveUsers); + } + + @Test + public void deleteNotificationsFromEpNotificationTableTest() { + Map<String, String> params = new HashMap<String, String>(); + Mockito.when(dataAccessService + .executeNamedQuery("deleteNotificationsFromEpUserNotificationTable", params, null)).thenReturn(null); + userNotificationServiceImpl.deleteNotificationsFromEpNotificationTable(); + } + + @Test + public void deleteNotificationsFromEpUserNotificationTable() { + Map<String, String> params = new HashMap<String, String>(); + Mockito.when(dataAccessService + .executeNamedQuery("deleteNotificationsFromEpUserNotificationTable", params, null)).thenReturn(null); + userNotificationServiceImpl.deleteNotificationsFromEpUserNotificationTable(); + } + + @Test + public void deleteNotificationsFromEpRoleNotificationTable() { + Map<String, String> params = new HashMap<String, String>(); + Mockito.when(dataAccessService + .executeNamedQuery("deleteNotificationsFromEpRoleNotificationTable", params, null)).thenReturn(null); + userNotificationServiceImpl.deleteNotificationsFromEpRoleNotificationTable(); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImplTest.java new file mode 100644 index 00000000..2cb285f3 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImplTest.java @@ -0,0 +1,1466 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.portal.service; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; + +import javax.servlet.http.HttpServletResponse; + +import org.apache.cxf.transport.http.HTTPException; +import org.hibernate.Query; +import org.hibernate.SQLQuery; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.json.JSONObject; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.externalsystemapproval.model.ExternalSystemRoleApproval; +import org.onap.portalapp.externalsystemapproval.model.ExternalSystemUser; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.EPApp; +import org.onap.portalapp.portal.domain.EPRole; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.domain.EPUserApp; +import org.onap.portalapp.portal.domain.EPUserAppCatalogRoles; +import org.onap.portalapp.portal.domain.EPUserAppRoles; +import org.onap.portalapp.portal.domain.EPUserAppRolesRequest; +import org.onap.portalapp.portal.domain.EPUserAppRolesRequestDetail; +import org.onap.portalapp.portal.domain.ExternalSystemAccess; +import org.onap.portalapp.portal.transport.AppWithRolesForUser; +import org.onap.portalapp.portal.transport.CentralV2Role; +import org.onap.portalapp.portal.transport.EPUserAppCurrentRoles; +import org.onap.portalapp.portal.transport.EcompUserAppRoles; +import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator; +import org.onap.portalapp.portal.transport.FieldsValidator; +import org.onap.portalapp.portal.transport.FunctionalMenuItem; +import org.onap.portalapp.portal.transport.FunctionalMenuRole; +import org.onap.portalapp.portal.transport.RemoteRole; +import org.onap.portalapp.portal.transport.RemoteUserWithRoles; +import org.onap.portalapp.portal.transport.RoleInAppForUser; +import org.onap.portalapp.portal.transport.UserApplicationRoles; +import org.onap.portalapp.portal.utils.EPCommonSystemProperties; +import org.onap.portalapp.portal.utils.EcompPortalUtils; +import org.onap.portalapp.portal.utils.PortalConstants; +import org.onap.portalsdk.core.domain.Role; +import org.onap.portalsdk.core.restful.domain.EcompRole; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.service.DataAccessServiceImpl; +import org.onap.portalsdk.core.service.RoleServiceImpl; +import org.onap.portalsdk.core.util.SystemProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ EcompPortalUtils.class, SystemProperties.class, PortalConstants.class, + EPCommonSystemProperties.class }) +public class UserRolesCommonServiceImplTest { + + @Mock + DataAccessService dataAccessService = new DataAccessServiceImpl(); + + @Mock + EPAppCommonServiceImpl epAppCommonServiceImpl = new EPAppCommonServiceImpl(); + + @Mock + ExternalAccessRolesServiceImpl externalAccessRolesServiceImpl = new ExternalAccessRolesServiceImpl(); + + @Mock + ApplicationsRestClientService applicationsRestClientService; + + @Mock + RoleServiceImpl roleServiceImpl = new RoleServiceImpl(); + + @Mock + SearchServiceImpl searchServiceImpl = new SearchServiceImpl(); + + @Mock + EPRoleServiceImpl epRoleServiceImpl = new EPRoleServiceImpl(); + + @Mock + RestTemplate template = new RestTemplate(); + + @Mock + SessionFactory sessionFactory; + + @Mock + Session session; + + @Mock + Transaction transaction; + + @InjectMocks + UserRolesCommonServiceImpl userRolesCommonServiceImpl = new UserRolesCommonServiceImpl(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + Mockito.when(sessionFactory.openSession()).thenReturn(session); + Mockito.when(session.beginTransaction()).thenReturn(transaction); + } + + @After + public void after() { + session.close(); + } + + MockEPUser mockUser = new MockEPUser(); + + public EPApp mockApp() { + EPApp app = new EPApp(); + app.setName("Test"); + app.setImageUrl("test"); + app.setDescription("test"); + app.setNotes("test"); + app.setUrl("test"); + app.setId((long) 1); + app.setAppRestEndpoint("test"); + app.setAlternateUrl("test"); + app.setName("test"); + app.setMlAppName("test"); + app.setMlAppAdminId("test"); + app.setUsername("test"); + app.setAppPassword("test"); + app.setOpen(false); + app.setEnabled(false); + app.setCentralAuth(true); + app.setUebKey("test"); + app.setUebSecret("test"); + app.setUebTopicName("test"); + app.setAppType(1); + return app; + } + + @SuppressWarnings("unchecked") + @Test + public void getAppRolesForUserCentralizedForPortal() throws Exception { + EPUser user = mockUser.mockEPUser(); + EPApp mockApp = mockApp(); + Mockito.when(epAppCommonServiceImpl.getApp(mockApp.getId())).thenReturn(mockApp); + List<RoleInAppForUser> mockRoleInAppForUserList = getMockedRoleInAppUserList(); + List<CentralV2Role> mockCenV2Role = new ArrayList<>(); + CentralV2Role cenV2Role = new CentralV2Role(1l, null, null, null, null, null, "test1", true, null, + new TreeSet<>(), new TreeSet<>(), new TreeSet<>()); + CentralV2Role cenV2Role2 = new CentralV2Role(16l, null, null, null, null, null, "test2", true, null, + new TreeSet<>(), new TreeSet<>(), new TreeSet<>()); + mockCenV2Role.add(cenV2Role); + mockCenV2Role.add(cenV2Role2); + Mockito.when(externalAccessRolesServiceImpl.getRolesForApp(mockApp.getUebKey())).thenReturn(mockCenV2Role); + List<EPUser> mockUserList = new ArrayList<>(); + mockUserList.add(user); + Mockito.when((List<EPUser>) dataAccessService + .executeQuery("from EPUser where orgUserId='" + user.getOrgUserId() + "'", null)) + .thenReturn(mockUserList); + Mockito.when(userRolesCommonServiceImpl.getAppRolesForUser(1l, user.getOrgUserId(), true)) + .thenReturn(mockRoleInAppForUserList); + List<RoleInAppForUser> roleInAppForUser = userRolesCommonServiceImpl.getAppRolesForUser(1l, "test", true); + assertEquals(roleInAppForUser, mockRoleInAppForUserList); + } + + private List<RoleInAppForUser> getMockedRoleInAppUserList() { + List<RoleInAppForUser> mockRoleInAppForUserList = new ArrayList<>(); + RoleInAppForUser mockRoleInAppForUser = new RoleInAppForUser(); + mockRoleInAppForUser.setIsApplied(false); + mockRoleInAppForUser.setRoleId(1l); + mockRoleInAppForUser.setRoleName("test1"); + RoleInAppForUser mockRoleInAppForUser2 = new RoleInAppForUser(); + mockRoleInAppForUser2.setIsApplied(false); + mockRoleInAppForUser2.setRoleId(16l); + mockRoleInAppForUser2.setRoleName("test2"); + mockRoleInAppForUserList.add(mockRoleInAppForUser); + mockRoleInAppForUserList.add(mockRoleInAppForUser2); + return mockRoleInAppForUserList; + } + + @SuppressWarnings("unchecked") + @Test + public void getAppRolesForUserNonCentralizedForPortal() throws Exception { + EPUser user = mockUser.mockEPUser(); + user.setId(1l); + EPApp mockApp = mockApp(); + mockApp.setCentralAuth(false); + EPRole mockEPRole = new EPRole(); + mockEPRole.setId(1l); + mockEPRole.setName("test1"); + mockEPRole.setActive(true); + SortedSet<EPUserApp> mockUserApps = new TreeSet<EPUserApp>(); + EPUserApp mockEPUserApp = new EPUserApp(); + mockEPUserApp.setApp(mockApp); + mockEPUserApp.setRole(mockEPRole); + mockEPUserApp.setUserId(1l); + mockUserApps.add(mockEPUserApp); + user.setEPUserApps(mockUserApps); + Mockito.when(epAppCommonServiceImpl.getApp(mockApp.getId())).thenReturn(mockApp); + List<RoleInAppForUser> mockRoleInAppForUserListNonCentralizedList = getMockedRoleInAppUserList(); + List<Role> mockRole = new ArrayList<>(); + Role role = new Role(); + role.setId(1l); + role.setName("test1"); + role.setActive(true); + Role role2 = new Role(); + role.setId(16l); + role.setName("test2"); + role.setActive(true); + mockRole.add(role); + mockRole.add(role2); + Mockito.when(roleServiceImpl.getAvailableRoles(user.getOrgUserId())).thenReturn(mockRole); + List<EPUser> mockUserList = new ArrayList<>(); + mockUserList.add(user); + Mockito.when((List<EPUser>) dataAccessService + .executeQuery("from EPUser where orgUserId='" + user.getOrgUserId() + "'", null)) + .thenReturn(mockUserList); + Mockito.when(userRolesCommonServiceImpl.getAppRolesForUser(1l, user.getOrgUserId(), true)) + .thenReturn(mockRoleInAppForUserListNonCentralizedList); + List<RoleInAppForUser> roleInAppForUserNonCentralized = userRolesCommonServiceImpl.getAppRolesForUser(1l, + user.getOrgUserId(), true); + assertNull(roleInAppForUserNonCentralized); + } + + @Test + public void getAppRolesForCentralizedPartnerAppTest() throws Exception { + EPUser user = mockUser.mockEPUser(); + EPApp mockApp = mockApp(); + mockApp.setId(2l); + Mockito.when(epAppCommonServiceImpl.getApp(mockApp.getId())).thenReturn(mockApp); + List<RoleInAppForUser> mockRoleInAppForUserList = getMockedRoleInAppUserList(); + List<EPRole> mockEPRoleList = new ArrayList<>(); + EPRole mockEpRole = new EPRole(); + mockEpRole.setActive(true); + mockEpRole.setAppId(2l); + mockEpRole.setName("test1"); + mockEpRole.setAppRoleId(333l); + mockEpRole.setId(1l); + EPRole mockEpRole2 = new EPRole(); + mockEpRole2.setActive(true); + mockEpRole2.setAppId(2l); + mockEpRole2.setName("test2"); + mockEpRole2.setAppRoleId(444l); + mockEpRole2.setId(16l); + mockEPRoleList.add(mockEpRole); + mockEPRoleList.add(mockEpRole2); + final Map<String, Long> appParams = new HashMap<>(); + appParams.put("appId", 2l); + Mockito.when(dataAccessService.executeNamedQuery("getActiveRolesOfApplication", appParams, null)) + .thenReturn(mockEPRoleList); + final Map<String, String> params = new HashMap<>(); + params.put("orgUserIdValue", "guestT"); + List<EPUser> mockEPUserList = new ArrayList<>(); + mockEPUserList.add(user); + Mockito.when(dataAccessService.executeNamedQuery("epUserAppId", params, null)).thenReturn(mockEPUserList); + final Map<String, Long> userParams = new HashMap<>(); + userParams.put("appId", mockApp.getId()); + userParams.put("userId", mockEPUserList.get(0).getId()); + List<EPUserAppCurrentRoles> epUserAppCurrentRolesList = new ArrayList<>(); + EPUserAppCurrentRoles epUserAppCurrentRoles = new EPUserAppCurrentRoles(); + epUserAppCurrentRoles.setRoleId(444l); + epUserAppCurrentRoles.setRoleName("TestPartnerRole2"); + epUserAppCurrentRoles.setUserId(mockEPUserList.get(0).getId()); + epUserAppCurrentRolesList.add(epUserAppCurrentRoles); + Mockito.when(dataAccessService.executeNamedQuery("getUserAppCurrentRoles", userParams, null)) + .thenReturn(epUserAppCurrentRolesList); + Mockito.when(userRolesCommonServiceImpl.getAppRolesForUser(2l, user.getOrgUserId(), true)) + .thenReturn(mockRoleInAppForUserList); + List<RoleInAppForUser> roleInAppForUser = userRolesCommonServiceImpl.getAppRolesForUser(2l, user.getOrgUserId(), + true); + assertEquals(roleInAppForUser, mockRoleInAppForUserList); + } + + @Test + public void getAppRolesForNonCentralizedPartnerAppTest() throws Exception { + EPUser user = mockUser.mockEPUser(); + user.setId(2l); + List<EPUser> mockEpUserList = new ArrayList<>(); + mockEpUserList.add(user); + EPApp mockApp = mockApp(); + mockApp.setId(2l); + mockApp.setCentralAuth(false); + Mockito.when(epAppCommonServiceImpl.getApp(mockApp.getId())).thenReturn(mockApp); + List<RoleInAppForUser> mockRoleInAppForUserList = new ArrayList<>(); + RoleInAppForUser mockRoleInAppForUser = new RoleInAppForUser(); + mockRoleInAppForUser.setIsApplied(true); + mockRoleInAppForUser.setRoleId(333l); + mockRoleInAppForUser.setRoleName("test1"); + RoleInAppForUser mockRoleInAppForUser2 = new RoleInAppForUser(); + mockRoleInAppForUser2.setIsApplied(true); + mockRoleInAppForUser2.setRoleId(777l); + mockRoleInAppForUser2.setRoleName("test2"); + RoleInAppForUser mockRoleInAppForUser3 = new RoleInAppForUser(); + mockRoleInAppForUser3.setIsApplied(false); + mockRoleInAppForUser3.setRoleId(888l); + mockRoleInAppForUser3.setRoleName("test5"); + mockRoleInAppForUserList.add(mockRoleInAppForUser); + mockRoleInAppForUserList.add(mockRoleInAppForUser2); + mockRoleInAppForUserList.add(mockRoleInAppForUser3); + List<EcompRole> mockEcompRoleList = new ArrayList<>(); + EcompRole mockEcompRole = new EcompRole(); + mockEcompRole.setId(333l); + mockEcompRole.setName("test1"); + EcompRole mockEcompRole2 = new EcompRole(); + mockEcompRole2.setId(777l); + mockEcompRole2.setName("test2"); + EcompRole mockEcompRole3 = new EcompRole(); + mockEcompRole3.setId(888l); + mockEcompRole3.setName("test5"); + mockEcompRoleList.add(mockEcompRole); + mockEcompRoleList.add(mockEcompRole2); + mockEcompRoleList.add(mockEcompRole3); + EcompRole[] mockEcompRoleArray = mockEcompRoleList.toArray(new EcompRole[mockEcompRoleList.size()]); + List<EPRole> mockEPRoleList = new ArrayList<>(); + EPRole mockEpRole = new EPRole(); + mockEpRole.setActive(true); + mockEpRole.setAppId(2l); + mockEpRole.setName("test1"); + mockEpRole.setAppRoleId(333l); + mockEpRole.setId(16l); + EPRole mockEpRole2 = new EPRole(); + mockEpRole2.setActive(true); + mockEpRole2.setAppId(2l); + mockEpRole2.setName("test3"); + mockEpRole2.setAppRoleId(555l); + mockEpRole2.setId(15l); + EPRole mockEpRole3 = new EPRole(); + mockEpRole3.setActive(true); + mockEpRole3.setAppId(2l); + mockEpRole3.setName("test4"); + mockEpRole3.setAppRoleId(888l); + mockEpRole3.setId(17l); + mockEPRoleList.add(mockEpRole); + mockEPRoleList.add(mockEpRole2); + mockEPRoleList.add(mockEpRole3); + List<EPUserApp> mockUserRolesList = new ArrayList<>(); + EPUserApp mockEpUserApp = new EPUserApp(); + mockEpUserApp.setApp(mockApp); + mockEpUserApp.setRole(mockEpRole2); + mockEpUserApp.setUserId(user.getId()); + mockUserRolesList.add(mockEpUserApp); + List<FunctionalMenuRole> mockFunctionalMenuRolesList = new ArrayList<>(); + FunctionalMenuRole mockFunctionalMenuRole = new FunctionalMenuRole(); + mockFunctionalMenuRole.setAppId((int) (long) mockApp.getId()); + mockFunctionalMenuRole.setRoleId((int) (long) 15l); + mockFunctionalMenuRole.setMenuId(10l); + mockFunctionalMenuRole.setId(10); + mockFunctionalMenuRolesList.add(mockFunctionalMenuRole); + List<FunctionalMenuItem> mockFunctionalMenuItemList = new ArrayList<>(); + FunctionalMenuItem mockFunctionalMenuItem = new FunctionalMenuItem(); + List<Integer> mockRolesList = new ArrayList<>(); + Integer role1 = 1; + mockRolesList.add(role1); + mockFunctionalMenuItem.setRestrictedApp(false); + mockFunctionalMenuItem.setRoles(mockRolesList); + mockFunctionalMenuItem.setUrl("http://test.com"); + mockFunctionalMenuItemList.add(mockFunctionalMenuItem); + Query epRoleQuery = Mockito.mock(Query.class); + Query epUserAppsQuery = Mockito.mock(Query.class); + Query epFunctionalMenuQuery = Mockito.mock(Query.class); + Query epFunctionalMenuQuery2 = Mockito.mock(Query.class); + Query epFunctionalMenuItemQuery = Mockito.mock(Query.class); + Query epUserListQuery = Mockito.mock(Query.class); + Query epUserRolesListQuery = Mockito.mock(Query.class); + Mockito.when(applicationsRestClientService.get(EcompRole[].class, mockApp.getId(), "/roles")) + .thenReturn(mockEcompRoleArray); + // syncAppRolesTest + Mockito.when(session.createQuery("from " + EPRole.class.getName() + " where appId=" + mockApp.getId())) + .thenReturn(epRoleQuery); + Mockito.doReturn(mockEPRoleList).when(epRoleQuery).list(); + Mockito.when(session.createQuery( + "from " + EPUserApp.class.getName() + " where app.id=" + mockApp.getId() + " and role_id=" + 15l)) + .thenReturn(epUserAppsQuery); + Mockito.doReturn(mockUserRolesList).when(epUserAppsQuery).list(); + + Mockito.when(session.createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + 15l)) + .thenReturn(epFunctionalMenuQuery); + Mockito.doReturn(mockFunctionalMenuRolesList).when(epFunctionalMenuQuery).list(); + + Mockito.when(session.createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + 10l)) + .thenReturn(epFunctionalMenuQuery2); + Mockito.doReturn(mockFunctionalMenuRolesList).when(epFunctionalMenuQuery2).list(); + + Mockito.when(session.createQuery("from " + FunctionalMenuItem.class.getName() + " where menuId=" + 10l)) + .thenReturn(epFunctionalMenuItemQuery); + Mockito.doReturn(mockFunctionalMenuItemList).when(epFunctionalMenuItemQuery).list(); + List<EcompRole> mockEcompRoleList2 = new ArrayList<>(); + EcompRole mockUserAppRoles = new EcompRole(); + mockUserAppRoles.setId(333l); + mockUserAppRoles.setName("test1"); + EcompRole mockUserAppRoles2 = new EcompRole(); + mockUserAppRoles2.setId(777l); + mockUserAppRoles2.setName("test2"); + mockEcompRoleList2.add(mockUserAppRoles); + mockEcompRoleList2.add(mockUserAppRoles2); + EcompRole[] mockEcompRoleArray2 = mockEcompRoleList2.toArray(new EcompRole[mockEcompRoleList2.size()]); + Mockito.when(applicationsRestClientService.get(EcompRole[].class, mockApp.getId(), + String.format("/user/%s/roles", user.getOrgUserId()))).thenReturn(mockEcompRoleArray2); + // SyncUserRoleTest + Mockito.when(session + .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + user.getOrgUserId() + "'")) + .thenReturn(epUserListQuery); + Mockito.doReturn(mockEpUserList).when(epUserListQuery).list(); + + List<EPUserApp> mockUserRolesList2 = new ArrayList<>(); + EPUserApp mockEpUserAppRoles = new EPUserApp(); + mockEpUserAppRoles.setApp(mockApp); + mockEpUserAppRoles.setRole(mockEpRole3); + mockEpUserAppRoles.setUserId(user.getId()); + mockUserRolesList2.add(mockEpUserAppRoles); + Mockito.when(session.createQuery( + "from org.onap.portalapp.portal.domain.EPUserApp where app.id=2 and role.active = 'Y' and userId=2")) + .thenReturn(epUserRolesListQuery); + Mockito.doReturn(mockUserRolesList2).when(epUserRolesListQuery).list(); + List<RoleInAppForUser> roleInAppForUser = userRolesCommonServiceImpl.getAppRolesForUser(2l, user.getOrgUserId(), + true); + assertEquals(roleInAppForUser, mockRoleInAppForUserList); + } + + @SuppressWarnings("unchecked") + @Test + public void setAppWithUserRoleStateForUserTestForCentralizedAppForPortal() throws Exception { + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(PortalConstants.class); + EPUser user = mockUser.mockEPUser(); + user.setId(2l); + List<EPUser> mockEpUserList = new ArrayList<>(); + mockEpUserList.add(user); + EPApp mockApp = mockApp(); + mockApp.setNameSpace("com.test.com"); + mockApp.setId(1l); + mockApp.setCentralAuth(true); + Mockito.when(epAppCommonServiceImpl.getApp(mockApp.getId())).thenReturn(mockApp); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + AppWithRolesForUser mockWithRolesForUser = new AppWithRolesForUser(); + List<RoleInAppForUser> mockRoleInAppForUserList = new ArrayList<>(); + RoleInAppForUser mockRoleInAppForUser = new RoleInAppForUser(); + mockRoleInAppForUser.setIsApplied(true); + mockRoleInAppForUser.setRoleId(1l); + mockRoleInAppForUser.setRoleName("test1"); + RoleInAppForUser mockRoleInAppForUser2 = new RoleInAppForUser(); + mockRoleInAppForUser2.setIsApplied(true); + mockRoleInAppForUser2.setRoleId(1000l); + mockRoleInAppForUser2.setRoleName("test3"); + mockRoleInAppForUserList.add(mockRoleInAppForUser); + mockRoleInAppForUserList.add(mockRoleInAppForUser2); + mockWithRolesForUser.setAppId(mockApp.getId()); + mockWithRolesForUser.setAppName(mockApp.getName()); + mockWithRolesForUser.setOrgUserId(user.getOrgUserId()); + mockWithRolesForUser.setAppRoles(mockRoleInAppForUserList); + List<EPUserAppRolesRequest> mockEpRequestIdValList = new ArrayList<EPUserAppRolesRequest>(); + Set<EPUserAppRolesRequestDetail> mockEpUserAppRolesRequestDetailList = new TreeSet<>(); + EPUserAppRolesRequestDetail mockEpUserAppRolesRequestDetail = new EPUserAppRolesRequestDetail(); + mockEpUserAppRolesRequestDetail.setId(2l); + mockEpUserAppRolesRequestDetail.setReqType("P"); + mockEpUserAppRolesRequestDetail.setReqRoleId(16l); + EPUserAppRolesRequest mockEPUserAppRolesRequest = new EPUserAppRolesRequest(); + mockEPUserAppRolesRequest.setAppId(mockApp.getId()); + mockEPUserAppRolesRequest.setId(1l); + mockEPUserAppRolesRequest.setRequestStatus("P"); + mockEPUserAppRolesRequest.setUserId(user.getId()); + mockEPUserAppRolesRequest.setEpRequestIdDetail(mockEpUserAppRolesRequestDetailList); + mockEpRequestIdValList.add(mockEPUserAppRolesRequest); + mockEpUserAppRolesRequestDetail.setEpRequestIdData(mockEPUserAppRolesRequest); + mockEpUserAppRolesRequestDetailList.add(mockEpUserAppRolesRequestDetail); + + // Update Requests if any requests are pending + final Map<String, Long> params = new HashMap<>(); + params.put("appId", mockApp.getId()); + params.put("userId", user.getId()); + Mockito.when((List<EPUserAppRolesRequest>) dataAccessService.executeNamedQuery("userAppRolesRequestList", + params, null)).thenReturn(mockEpRequestIdValList); + mockEPUserAppRolesRequest.setUpdatedDate(new Date()); + mockEPUserAppRolesRequest.setRequestStatus("O"); + HashMap<String, Long> additionalUpdateParam = new HashMap<String, Long>(); + Mockito.doNothing().when(dataAccessService).saveDomainObject(mockEPUserAppRolesRequest, additionalUpdateParam); + List<EPUserAppRolesRequestDetail> mockGetEpUserAppRolesRequestDetailList = new ArrayList<EPUserAppRolesRequestDetail>(); + EPUserAppRolesRequestDetail mockGetEpUserAppRolesRequestDetail = new EPUserAppRolesRequestDetail(); + mockEpUserAppRolesRequestDetail.setId(2l); + mockEpUserAppRolesRequestDetail.setReqType("P"); + mockEpUserAppRolesRequestDetail.setReqRoleId(16l); + mockGetEpUserAppRolesRequestDetailList.add(mockGetEpUserAppRolesRequestDetail); + // Updates in External Auth System + final Map<String, String> userParams = new HashMap<>(); + userParams.put("orgUserIdValue", user.getOrgUserId()); + Mockito.when((List<EPUser>) dataAccessService.executeNamedQuery("epUserAppId", userParams, null)) + .thenReturn(mockEpUserList); + PowerMockito + .when(EPCommonSystemProperties + .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn(true); + PowerMockito.when(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn("@test.com"); + HttpHeaders headers = new HttpHeaders(); + Mockito.when(EcompPortalUtils.base64encodeKeyForAAFBasicAuth()).thenReturn(headers); + JSONObject mockJsonObject1 = new JSONObject(); + JSONObject mockJsonObject2 = new JSONObject(); + JSONObject mockJsonObject3 = new JSONObject(); + mockJsonObject1.put("name", "com.test.com.test1"); + mockJsonObject2.put("name", "com.test.com.test2"); + List<JSONObject> mockJson = new ArrayList<>(); + mockJson.add(mockJsonObject1); + mockJson.add(mockJsonObject2); + mockJsonObject3.put("role", mockJson); + ResponseEntity<String> getResponse = new ResponseEntity<>(mockJsonObject3.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + EPRole mockEPRole = new EPRole(); + mockEPRole.setActive(true); + mockEPRole.setAppId(null); + mockEPRole.setAppRoleId(null); + mockEPRole.setId(1l); + mockEPRole.setName("test1"); + EPRole mockEPRole2 = new EPRole(); + mockEPRole2.setActive(true); + mockEPRole2.setAppId(null); + mockEPRole2.setAppRoleId(null); + mockEPRole2.setId(16l); + mockEPRole2.setName("test2"); + EPRole mockEPRole3 = new EPRole(); + mockEPRole3.setActive(true); + mockEPRole3.setAppId(null); + mockEPRole3.setAppRoleId(null); + mockEPRole3.setId(1000l); + mockEPRole3.setName("test3"); + Map<String, EPRole> mockEPRoleList = new HashMap<>(); + mockEPRoleList.put("test1", mockEPRole); + mockEPRoleList.put("test2", mockEPRole2); + mockEPRoleList.put("test3", mockEPRole3); + Mockito.when(externalAccessRolesServiceImpl.getCurrentRolesInDB(mockApp)).thenReturn(mockEPRoleList); + final Map<String, Long> params2 = new HashMap<>(); + params2.put("appId", mockApp.getId()); + params2.put("userId", user.getId()); + List<EcompUserAppRoles> mockEPuserAppList = getCurrentUserRoles(user, mockApp); + Mockito.when(dataAccessService.executeNamedQuery("getUserAppExistingRoles", params2, null)) + .thenReturn(mockEPuserAppList); + final Map<String, Long> epDetailParams = new HashMap<>(); + epDetailParams.put("reqId", mockEPUserAppRolesRequest.getId()); + Mockito.when(dataAccessService.executeNamedQuery("userAppRolesRequestDetailList", epDetailParams, null)) + .thenReturn(mockGetEpUserAppRolesRequestDetailList); + + ResponseEntity<String> addResponse = new ResponseEntity<>(HttpStatus.CREATED); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(addResponse); + + ResponseEntity<String> deleteResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(deleteResponse); + + // Updates in EP DB + Query epsetAppWithUserRoleGetUserQuery = Mockito.mock(Query.class); + Query epsetAppWithUserRoleGetUserAppsQuery = Mockito.mock(Query.class); + Query epsetAppWithUserRoleGetRolesQuery = Mockito.mock(Query.class); + SQLQuery epsetAppWithUserRoleUpdateEPRoleQuery = Mockito.mock(SQLQuery.class); + Mockito.when(session.get(EPApp.class, mockApp.getId())).thenReturn(mockApp); + Mockito.when(session + .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + user.getOrgUserId() + "'")) + .thenReturn(epsetAppWithUserRoleGetUserQuery); + Mockito.doReturn(mockEpUserList).when(epsetAppWithUserRoleGetUserQuery).list(); + List<EPUserApp> mockUserRolesList2 = new ArrayList<>(); + EPUserApp mockEpUserAppRoles = new EPUserApp(); + mockEpUserAppRoles.setApp(mockApp); + mockEpUserAppRoles.setRole(mockEPRole); + mockEpUserAppRoles.setUserId(user.getId()); + mockUserRolesList2.add(mockEpUserAppRoles); + Mockito.when(session.createQuery( + "from org.onap.portalapp.portal.domain.EPUserApp where app.id=1 and role.active = 'Y' and userId=2")) + .thenReturn(epsetAppWithUserRoleGetUserAppsQuery); + Mockito.doReturn(mockUserRolesList2).when(epsetAppWithUserRoleGetUserAppsQuery).list(); + List<EPRole> mockEPRoles = new ArrayList<>(); + mockEPRoles.add(mockEPRole2); + mockEPRoles.add(mockEPRole3); + Mockito.when(session.createQuery("from " + EPRole.class.getName() + " where appId is null and id != 1")) + .thenReturn(epsetAppWithUserRoleGetRolesQuery); + Mockito.doReturn(mockEPRoles).when(epsetAppWithUserRoleGetRolesQuery).list(); + Mockito.when(session.createSQLQuery("update fn_role set app_id = null where app_id = 1 ")) + .thenReturn(epsetAppWithUserRoleUpdateEPRoleQuery); + boolean actual = userRolesCommonServiceImpl.setAppWithUserRoleStateForUser(user, mockWithRolesForUser); + assertTrue(actual); + } + + private List<EcompUserAppRoles> getCurrentUserRoles(EPUser user, EPApp mockApp) { + List<EcompUserAppRoles> mockEPuserAppList = new ArrayList<>(); + EcompUserAppRoles mockEcompUserAppRoles = new EcompUserAppRoles(); + mockEcompUserAppRoles.setAppId(String.valueOf(mockApp.getId())); + mockEcompUserAppRoles.setRoleId(1l); + mockEcompUserAppRoles.setRoleName("test1"); + mockEcompUserAppRoles.setUserId(user.getId()); + mockEPuserAppList.add(mockEcompUserAppRoles); + return mockEPuserAppList; + } + + @SuppressWarnings("unchecked") + @Test + public void setAppWithUserRoleStateForUserTestForNonCentralizedApp() throws Exception { + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(PortalConstants.class); + EPUser user = mockUser.mockEPUser(); + user.setId(2l); + List<EPUser> mockEpUserList = new ArrayList<>(); + mockEpUserList.add(user); + EPApp mockApp = mockApp(); + mockApp.setNameSpace("com.test.com"); + mockApp.setId(2l); + mockApp.setCentralAuth(false); + Mockito.when(epAppCommonServiceImpl.getApp(mockApp.getId())).thenReturn(mockApp); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + AppWithRolesForUser mockWithRolesForUser = new AppWithRolesForUser(); + List<RoleInAppForUser> mockRoleInAppForUserList = new ArrayList<>(); + RoleInAppForUser mockRoleInAppForUser = new RoleInAppForUser(); + mockRoleInAppForUser.setIsApplied(true); + mockRoleInAppForUser.setRoleId(1l); + mockRoleInAppForUser.setRoleName("test1"); + RoleInAppForUser mockRoleInAppForUser2 = new RoleInAppForUser(); + mockRoleInAppForUser2.setIsApplied(true); + mockRoleInAppForUser2.setRoleId(1000l); + mockRoleInAppForUser2.setRoleName("test3"); + mockRoleInAppForUserList.add(mockRoleInAppForUser); + mockRoleInAppForUserList.add(mockRoleInAppForUser2); + mockWithRolesForUser.setAppId(mockApp.getId()); + mockWithRolesForUser.setAppName(mockApp.getName()); + mockWithRolesForUser.setOrgUserId(user.getOrgUserId()); + mockWithRolesForUser.setAppRoles(mockRoleInAppForUserList); + List<EPUserAppRolesRequest> mockEpRequestIdValList = new ArrayList<EPUserAppRolesRequest>(); + Set<EPUserAppRolesRequestDetail> mockEpUserAppRolesRequestDetailList = new TreeSet<>(); + EPUserAppRolesRequestDetail mockEpUserAppRolesRequestDetail = new EPUserAppRolesRequestDetail(); + mockEpUserAppRolesRequestDetail.setId(2l); + mockEpUserAppRolesRequestDetail.setReqType("P"); + mockEpUserAppRolesRequestDetail.setReqRoleId(16l); + EPUserAppRolesRequest mockEPUserAppRolesRequest = new EPUserAppRolesRequest(); + mockEPUserAppRolesRequest.setAppId(mockApp.getId()); + mockEPUserAppRolesRequest.setId(1l); + mockEPUserAppRolesRequest.setRequestStatus("P"); + mockEPUserAppRolesRequest.setUserId(user.getId()); + mockEPUserAppRolesRequest.setEpRequestIdDetail(mockEpUserAppRolesRequestDetailList); + mockEpRequestIdValList.add(mockEPUserAppRolesRequest); + mockEpUserAppRolesRequestDetail.setEpRequestIdData(mockEPUserAppRolesRequest); + mockEpUserAppRolesRequestDetailList.add(mockEpUserAppRolesRequestDetail); + + // Update Requests if any requests are pending + final Map<String, Long> params = new HashMap<>(); + params.put("appId", mockApp.getId()); + params.put("userId", user.getId()); + Mockito.when((List<EPUserAppRolesRequest>) dataAccessService.executeNamedQuery("userAppRolesRequestList", + params, null)).thenReturn(mockEpRequestIdValList); + mockEPUserAppRolesRequest.setUpdatedDate(new Date()); + mockEPUserAppRolesRequest.setRequestStatus("O"); + HashMap<String, Long> additionalUpdateParam = new HashMap<String, Long>(); + Mockito.doNothing().when(dataAccessService).saveDomainObject(mockEPUserAppRolesRequest, additionalUpdateParam); + List<EPUserAppRolesRequestDetail> mockGetEpUserAppRolesRequestDetailList = new ArrayList<EPUserAppRolesRequestDetail>(); + EPUserAppRolesRequestDetail mockGetEpUserAppRolesRequestDetail = new EPUserAppRolesRequestDetail(); + mockEpUserAppRolesRequestDetail.setId(2l); + mockEpUserAppRolesRequestDetail.setReqType("P"); + mockEpUserAppRolesRequestDetail.setReqRoleId(16l); + mockGetEpUserAppRolesRequestDetailList.add(mockGetEpUserAppRolesRequestDetail); + final Map<String, Long> epDetailParams = new HashMap<>(); + epDetailParams.put("reqId", mockEPUserAppRolesRequest.getId()); + + final Map<String, String> userParams = new HashMap<>(); + userParams.put("orgUserIdValue", user.getOrgUserId()); + Mockito.when((List<EPUser>) dataAccessService.executeNamedQuery("epUserAppId", userParams, null)) + .thenReturn(mockEpUserList); + + PowerMockito + .when(EPCommonSystemProperties + .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn(true); + PowerMockito.when(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn("@test.com"); + HttpHeaders headers = new HttpHeaders(); + Mockito.when(EcompPortalUtils.base64encodeKeyForAAFBasicAuth()).thenReturn(headers); + EPRole mockEPRole = new EPRole(); + mockEPRole.setActive(true); + mockEPRole.setAppId(2l); + mockEPRole.setAppRoleId(null); + mockEPRole.setId(10l); + mockEPRole.setAppRoleId(1l); + mockEPRole.setName("test1"); + EPRole mockEPRole2 = new EPRole(); + mockEPRole2.setActive(true); + mockEPRole2.setAppId(2l); + mockEPRole2.setAppRoleId(null); + mockEPRole2.setId(160l); + mockEPRole2.setName("test2"); + mockEPRole2.setAppRoleId(16l); + EPRole mockEPRole3 = new EPRole(); + mockEPRole3.setActive(true); + mockEPRole3.setAppId(2l); + mockEPRole3.setAppRoleId(null); + mockEPRole3.setId(1100l); + mockEPRole3.setAppRoleId(100l); + mockEPRole3.setName("test3"); + Mockito.when(applicationsRestClientService.get(EPUser.class, mockApp.getId(), + String.format("/user/%s", user.getOrgUserId()), true)).thenReturn(user); + // Updates in EP DB + Query epsetAppWithUserRoleNonCentralizedGetUserQuery = Mockito.mock(Query.class); + Query epsetAppWithUserRoleNonCentralizedGetUserAppsQuery = Mockito.mock(Query.class); + Query epsetAppWithUserRoleNonCentralizedGetRolesQuery = Mockito.mock(Query.class); + Mockito.when(session.get(EPApp.class, mockApp.getId())).thenReturn(mockApp); + Mockito.when(session + .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + user.getOrgUserId() + "'")) + .thenReturn(epsetAppWithUserRoleNonCentralizedGetUserQuery); + Mockito.doReturn(mockEpUserList).when(epsetAppWithUserRoleNonCentralizedGetUserQuery).list(); + List<EPUserApp> mockUserRolesList2 = new ArrayList<>(); + EPUserApp mockEpUserAppRoles = new EPUserApp(); + mockEpUserAppRoles.setApp(mockApp); + mockEpUserAppRoles.setRole(mockEPRole); + mockEpUserAppRoles.setUserId(user.getId()); + mockUserRolesList2.add(mockEpUserAppRoles); + Mockito.when(session.createQuery( + "from org.onap.portalapp.portal.domain.EPUserApp where app.id=2 and role.active = 'Y' and userId=2")) + .thenReturn(epsetAppWithUserRoleNonCentralizedGetUserAppsQuery); + Mockito.doReturn(mockUserRolesList2).when(epsetAppWithUserRoleNonCentralizedGetUserAppsQuery).list(); + List<EPRole> mockEPRoles = new ArrayList<>(); + mockEPRoles.add(mockEPRole2); + mockEPRoles.add(mockEPRole3); + Mockito.when(session.createQuery("from " + EPRole.class.getName() + " where appId=2")) + .thenReturn(epsetAppWithUserRoleNonCentralizedGetRolesQuery); + Mockito.doReturn(mockEPRoles).when(epsetAppWithUserRoleNonCentralizedGetRolesQuery).list(); + boolean expected = userRolesCommonServiceImpl.setAppWithUserRoleStateForUser(user, mockWithRolesForUser); + assertEquals(expected, true); + } + + @SuppressWarnings("unchecked") + @Test + public void setExternalRequestUserAppRoleMerdianCentralizedAppTest() throws Exception { + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(PortalConstants.class); + EPUser user = mockUser.mockEPUser(); + user.setId(2l); + List<EPUser> mockEpUserList = new ArrayList<>(); + mockEpUserList.add(user); + EPApp mockApp = mockApp(); + mockApp.setNameSpace("com.test.com"); + mockApp.setId(1l); + mockApp.setCentralAuth(true); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + ExternalSystemUser externalSystemUser = new ExternalSystemUser(); + List<ExternalSystemRoleApproval> mockExternalSystemRoleApprovalList = new ArrayList<>(); + ExternalSystemRoleApproval mockExternalSystemRoleApproval = new ExternalSystemRoleApproval(); + mockExternalSystemRoleApproval.setRoleName("test1"); + ExternalSystemRoleApproval mockExternalSystemRoleApproval2 = new ExternalSystemRoleApproval(); + mockExternalSystemRoleApproval2.setRoleName("test2"); + mockExternalSystemRoleApprovalList.add(mockExternalSystemRoleApproval); + mockExternalSystemRoleApprovalList.add(mockExternalSystemRoleApproval2); + externalSystemUser.setApplicationName(mockApp.getMlAppName()); + externalSystemUser.setLoginId(user.getOrgUserId()); + externalSystemUser.setRoles(mockExternalSystemRoleApprovalList); + EPRole mockEPRole = new EPRole(); + mockEPRole.setActive(true); + mockEPRole.setAppId(null); + mockEPRole.setAppRoleId(null); + mockEPRole.setId(1l); + mockEPRole.setName("test1"); + EPRole mockEPRole2 = new EPRole(); + mockEPRole2.setActive(true); + mockEPRole2.setAppId(null); + mockEPRole2.setAppRoleId(null); + mockEPRole2.setId(16l); + mockEPRole2.setName("test2"); + EPRole mockEPRole3 = new EPRole(); + mockEPRole3.setActive(true); + mockEPRole3.setAppId(null); + mockEPRole3.setAppRoleId(null); + mockEPRole3.setId(1000l); + mockEPRole3.setName("test3"); + + Mockito.when(epAppCommonServiceImpl.getAppDetail(mockApp.getMlAppName())).thenReturn(mockApp); + final Map<String, String> userParams = new HashMap<>(); + userParams.put("orgUserIdValue", user.getOrgUserId()); + Mockito.when((List<EPUser>) dataAccessService.executeNamedQuery("epUserAppId", userParams, null)) + .thenReturn(mockEpUserList); + + List<EPUserAppRolesRequest> mockMerdianEpRequestIdValList = new ArrayList<EPUserAppRolesRequest>(); + Set<EPUserAppRolesRequestDetail> mockEpUserAppRolesRequestDetailList = new TreeSet<>(); + EPUserAppRolesRequestDetail mockEpUserAppRolesRequestDetail = new EPUserAppRolesRequestDetail(); + mockEpUserAppRolesRequestDetail.setId(2l); + mockEpUserAppRolesRequestDetail.setReqType("P"); + mockEpUserAppRolesRequestDetail.setReqRoleId(16l); + EPUserAppRolesRequest mockEPUserAppRolesRequest = new EPUserAppRolesRequest(); + mockEPUserAppRolesRequest.setAppId(mockApp.getId()); + mockEPUserAppRolesRequest.setId(1l); + mockEPUserAppRolesRequest.setRequestStatus("P"); + mockEPUserAppRolesRequest.setUserId(user.getId()); + mockEPUserAppRolesRequest.setEpRequestIdDetail(mockEpUserAppRolesRequestDetailList); + mockMerdianEpRequestIdValList.add(mockEPUserAppRolesRequest); + mockEpUserAppRolesRequestDetail.setEpRequestIdData(mockEPUserAppRolesRequest); + mockEpUserAppRolesRequestDetailList.add(mockEpUserAppRolesRequestDetail); + + final Map<String, Long> params = new HashMap<>(); + params.put("appId", mockApp.getId()); + params.put("userId", user.getId()); + Mockito.when((List<EPUserAppRolesRequest>) dataAccessService.executeNamedQuery("userAppRolesRequestList", + params, null)).thenReturn(mockMerdianEpRequestIdValList); + RoleInAppForUser mockRoleInAppForUser1 = new RoleInAppForUser(); + mockRoleInAppForUser1.setIsApplied(true); + mockRoleInAppForUser1.setRoleId(1l); + mockRoleInAppForUser1.setRoleName("test1"); + RoleInAppForUser mockRoleInAppForUser2 = new RoleInAppForUser(); + mockRoleInAppForUser2.setIsApplied(true); + mockRoleInAppForUser2.setRoleId(16l); + mockRoleInAppForUser2.setRoleName("test2"); + Mockito.when(epRoleServiceImpl.getAppRole(mockExternalSystemRoleApproval.getRoleName(), mockApp.getId())) + .thenReturn(mockEPRole); + Mockito.when(epRoleServiceImpl.getAppRole(mockExternalSystemRoleApproval2.getRoleName(), mockApp.getId())) + .thenReturn(mockEPRole2); + List<EcompUserAppRoles> mockEPuserAppList = getCurrentUserRoles(user, mockApp); + final Map<String, Long> params2 = new HashMap<>(); + params2.put("userId", user.getId()); + params2.put("appId", mockApp.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getUserAppExistingRoles", params2, null)) + .thenReturn(mockEPuserAppList); + // Updates in External Auth System + List<EPUserAppRolesRequestDetail> mockGetEpUserAppRolesRequestDetailList = new ArrayList<EPUserAppRolesRequestDetail>(); + EPUserAppRolesRequestDetail mockGetEpUserAppRolesRequestDetail = new EPUserAppRolesRequestDetail(); + mockEpUserAppRolesRequestDetail.setId(2l); + mockEpUserAppRolesRequestDetail.setReqType("P"); + mockEpUserAppRolesRequestDetail.setReqRoleId(16l); + mockGetEpUserAppRolesRequestDetailList.add(mockGetEpUserAppRolesRequestDetail); + final Map<String, String> userParams2 = new HashMap<>(); + userParams2.put("orgUserIdValue", user.getOrgUserId()); + Mockito.when((List<EPUser>) dataAccessService.executeNamedQuery("epUserAppId", userParams2, null)) + .thenReturn(mockEpUserList); + PowerMockito + .when(EPCommonSystemProperties + .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn(true); + PowerMockito.when(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn("@test.com"); + HttpHeaders headers = new HttpHeaders(); + Mockito.when(EcompPortalUtils.base64encodeKeyForAAFBasicAuth()).thenReturn(headers); + JSONObject mockJsonObject1 = new JSONObject(); + JSONObject mockJsonObject2 = new JSONObject(); + JSONObject mockJsonObject3 = new JSONObject(); + mockJsonObject1.put("name", "com.test.com.test1"); + mockJsonObject2.put("name", "com.test.com.test2"); + List<JSONObject> mockJson = new ArrayList<>(); + mockJson.add(mockJsonObject1); + mockJson.add(mockJsonObject2); + mockJsonObject3.put("role", mockJson); + ResponseEntity<String> getResponse = new ResponseEntity<>(mockJsonObject3.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + Map<String, EPRole> mockEPRoleList = new HashMap<>(); + mockEPRoleList.put("test1", mockEPRole); + mockEPRoleList.put("test2", mockEPRole2); + mockEPRoleList.put("test3", mockEPRole3); + Mockito.when(externalAccessRolesServiceImpl.getCurrentRolesInDB(mockApp)).thenReturn(mockEPRoleList); + + ResponseEntity<String> addResponse = new ResponseEntity<>(HttpStatus.CREATED); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(addResponse); + + ResponseEntity<String> deleteResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(deleteResponse); + // Updated in EP DB + Query epsetExternalRequestUserAppRoleGetUserQuery = Mockito.mock(Query.class); + Query epsetExternalRequestUserAppRoleGetUserAppsQuery = Mockito.mock(Query.class); + Query epsetExternalRequestUserAppRoleGetRolesQuery = Mockito.mock(Query.class); + SQLQuery epsetAppWithUserRoleUpdateEPRoleQuery = Mockito.mock(SQLQuery.class); + Mockito.when(session.get(EPApp.class, mockApp.getId())).thenReturn(mockApp); + Mockito.when(session + .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + user.getOrgUserId() + "'")) + .thenReturn(epsetExternalRequestUserAppRoleGetUserQuery); + Mockito.doReturn(mockEpUserList).when(epsetExternalRequestUserAppRoleGetUserQuery).list(); + List<EPUserApp> mockUserRolesList2 = new ArrayList<>(); + EPUserApp mockEpUserAppRoles = new EPUserApp(); + mockEpUserAppRoles.setApp(mockApp); + mockEpUserAppRoles.setRole(mockEPRole); + mockEpUserAppRoles.setUserId(user.getId()); + mockUserRolesList2.add(mockEpUserAppRoles); + Mockito.when(session.createQuery( + "from org.onap.portalapp.portal.domain.EPUserApp where app.id=1 and role.active = 'Y' and userId=2")) + .thenReturn(epsetExternalRequestUserAppRoleGetUserAppsQuery); + Mockito.doReturn(mockUserRolesList2).when(epsetExternalRequestUserAppRoleGetUserAppsQuery).list(); + List<EPRole> mockEPRoles = new ArrayList<>(); + mockEPRoles.add(mockEPRole2); + mockEPRoles.add(mockEPRole3); + Mockito.when(session.createQuery("from org.onap.portalapp.portal.domain.EPRole where appId is null ")) + .thenReturn(epsetExternalRequestUserAppRoleGetRolesQuery); + Mockito.doReturn(mockEPRoles).when(epsetExternalRequestUserAppRoleGetRolesQuery).list(); + Mockito.when(session.createSQLQuery("update fn_role set app_id = null where app_id = 1 ")) + .thenReturn(epsetAppWithUserRoleUpdateEPRoleQuery); + + ExternalRequestFieldsValidator mockExternalRequestFieldsValidator = new ExternalRequestFieldsValidator(true, + "Updated Successfully"); + ExternalRequestFieldsValidator externalRequestFieldsValidator = userRolesCommonServiceImpl + .setExternalRequestUserAppRole(externalSystemUser, "POST"); + assertTrue(mockExternalRequestFieldsValidator.equals(externalRequestFieldsValidator)); + } + + @SuppressWarnings("unchecked") + @Test + public void setExternalRequestUserAppRoleMerdianNonCentralizedAppTest() throws Exception { + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(PortalConstants.class); + EPUser user = mockUser.mockEPUser(); + user.setId(2l); + List<EPUser> mockEpUserList = new ArrayList<>(); + mockEpUserList.add(user); + EPApp mockApp = mockApp(); + mockApp.setId(2l); + mockApp.setEnabled(true); + mockApp.setCentralAuth(false); + ExternalSystemUser externalSystemUser = new ExternalSystemUser(); + List<ExternalSystemRoleApproval> mockExternalSystemRoleApprovalList = new ArrayList<>(); + ExternalSystemRoleApproval mockExternalSystemRoleApproval = new ExternalSystemRoleApproval(); + mockExternalSystemRoleApproval.setRoleName("test1"); + ExternalSystemRoleApproval mockExternalSystemRoleApproval2 = new ExternalSystemRoleApproval(); + mockExternalSystemRoleApproval2.setRoleName("test2"); + mockExternalSystemRoleApprovalList.add(mockExternalSystemRoleApproval); + mockExternalSystemRoleApprovalList.add(mockExternalSystemRoleApproval2); + externalSystemUser.setApplicationName(mockApp.getMlAppName()); + externalSystemUser.setLoginId(user.getOrgUserId()); + externalSystemUser.setRoles(mockExternalSystemRoleApprovalList); + + EPRole mockEPRole = new EPRole(); + mockEPRole.setActive(true); + mockEPRole.setAppId(2l); + mockEPRole.setAppRoleId(1l); + mockEPRole.setId(1000l); + mockEPRole.setName("test1"); + EPRole mockEPRole2 = new EPRole(); + mockEPRole2.setActive(true); + mockEPRole2.setAppId(2l); + mockEPRole2.setAppRoleId(16l); + mockEPRole2.setId(160l); + mockEPRole2.setName("test2"); + EPRole mockEPRole3 = new EPRole(); + mockEPRole3.setActive(true); + mockEPRole3.setAppId(2l); + mockEPRole3.setAppRoleId(10l); + mockEPRole3.setId(100l); + mockEPRole3.setName("test3"); + + Mockito.when(epAppCommonServiceImpl.getAppDetail(mockApp.getMlAppName())).thenReturn(mockApp); + final Map<String, String> userParams = new HashMap<>(); + userParams.put("orgUserIdValue", user.getOrgUserId()); + Mockito.when((List<EPUser>) dataAccessService.executeNamedQuery("epUserAppId", userParams, null)) + .thenReturn(mockEpUserList); + + List<EPUserAppRolesRequest> mockMerdianEpRequestIdValList = new ArrayList<EPUserAppRolesRequest>(); + Set<EPUserAppRolesRequestDetail> mockEpUserAppRolesRequestDetailList = new TreeSet<>(); + EPUserAppRolesRequestDetail mockEpUserAppRolesRequestDetail = new EPUserAppRolesRequestDetail(); + mockEpUserAppRolesRequestDetail.setId(2l); + mockEpUserAppRolesRequestDetail.setReqType("P"); + mockEpUserAppRolesRequestDetail.setReqRoleId(16l); + EPUserAppRolesRequest mockEPUserAppRolesRequest = new EPUserAppRolesRequest(); + mockEPUserAppRolesRequest.setAppId(mockApp.getId()); + mockEPUserAppRolesRequest.setId(1l); + mockEPUserAppRolesRequest.setRequestStatus("P"); + mockEPUserAppRolesRequest.setUserId(user.getId()); + mockEPUserAppRolesRequest.setEpRequestIdDetail(mockEpUserAppRolesRequestDetailList); + mockMerdianEpRequestIdValList.add(mockEPUserAppRolesRequest); + mockEpUserAppRolesRequestDetail.setEpRequestIdData(mockEPUserAppRolesRequest); + mockEpUserAppRolesRequestDetailList.add(mockEpUserAppRolesRequestDetail); + + final Map<String, Long> params = new HashMap<>(); + params.put("appId", mockApp.getId()); + params.put("userId", user.getId()); + Mockito.when((List<EPUserAppRolesRequest>) dataAccessService.executeNamedQuery("userAppRolesRequestList", + params, null)).thenReturn(mockMerdianEpRequestIdValList); + RoleInAppForUser mockRoleInAppForUser1 = new RoleInAppForUser(); + mockRoleInAppForUser1.setIsApplied(true); + mockRoleInAppForUser1.setRoleId(1l); + mockRoleInAppForUser1.setRoleName("test1"); + RoleInAppForUser mockRoleInAppForUser2 = new RoleInAppForUser(); + mockRoleInAppForUser2.setIsApplied(true); + mockRoleInAppForUser2.setRoleId(16l); + mockRoleInAppForUser2.setRoleName("test2"); + Mockito.when(epRoleServiceImpl.getAppRole(mockExternalSystemRoleApproval.getRoleName(), mockApp.getId())) + .thenReturn(mockEPRole); + Mockito.when(epRoleServiceImpl.getAppRole(mockExternalSystemRoleApproval2.getRoleName(), mockApp.getId())) + .thenReturn(mockEPRole2); + List<EcompUserAppRoles> mockEPuserAppList = new ArrayList<>(); + EcompUserAppRoles mockEcompUserAppRoles = new EcompUserAppRoles(); + mockEcompUserAppRoles.setAppId(String.valueOf(mockApp.getId())); + mockEcompUserAppRoles.setRoleId(100l); + mockEcompUserAppRoles.setRoleName("test1"); + mockEcompUserAppRoles.setUserId(user.getId()); + mockEPuserAppList.add(mockEcompUserAppRoles); + final Map<String, Long> params2 = new HashMap<>(); + params2.put("userId", user.getId()); + params2.put("appId", mockApp.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getUserAppExistingRoles", params2, null)) + .thenReturn(mockEPuserAppList); + List<EcompRole> mockEcompRoleList = new ArrayList<>(); + EcompRole mockEcompRole = new EcompRole(); + mockEcompRole.setId(1l); + mockEcompRole.setName("test1"); + EcompRole mockEcompRole2 = new EcompRole(); + mockEcompRole2.setId(16l); + mockEcompRole2.setName("test2"); + mockEcompRoleList.add(mockEcompRole); + mockEcompRoleList.add(mockEcompRole2); + EcompRole[] mockEcompRoleArray = mockEcompRoleList.toArray(new EcompRole[mockEcompRoleList.size()]); + Mockito.when(applicationsRestClientService.get(EcompRole[].class, mockApp.getId(), "/roles")) + .thenReturn(mockEcompRoleArray); + + // SyncAppRoles + List<EPUserApp> mockUserRolesList = new ArrayList<>(); + EPUserApp mockEpUserApp = new EPUserApp(); + mockEpUserApp.setApp(mockApp); + mockEpUserApp.setRole(mockEPRole2); + mockEpUserApp.setUserId(user.getId()); + mockUserRolesList.add(mockEpUserApp); + List<FunctionalMenuRole> mockFunctionalMenuRolesList = new ArrayList<>(); + FunctionalMenuRole mockFunctionalMenuRole = new FunctionalMenuRole(); + mockFunctionalMenuRole.setAppId((int) (long) mockApp.getId()); + mockFunctionalMenuRole.setRoleId((int) (long) 15l); + mockFunctionalMenuRole.setMenuId(10l); + mockFunctionalMenuRole.setId(10); + mockFunctionalMenuRolesList.add(mockFunctionalMenuRole); + List<FunctionalMenuItem> mockFunctionalMenuItemList = new ArrayList<>(); + FunctionalMenuItem mockFunctionalMenuItem = new FunctionalMenuItem(); + List<Integer> mockRolesList = new ArrayList<>(); + Integer role1 = 1; + mockRolesList.add(role1); + mockFunctionalMenuItem.setRestrictedApp(false); + mockFunctionalMenuItem.setRoles(mockRolesList); + mockFunctionalMenuItem.setUrl("http://test.com"); + mockFunctionalMenuItemList.add(mockFunctionalMenuItem); + Query epRoleQuery = Mockito.mock(Query.class); + Query epUserAppsQuery = Mockito.mock(Query.class); + Query epFunctionalMenuQuery = Mockito.mock(Query.class); + Query epFunctionalMenuQuery2 = Mockito.mock(Query.class); + Query epFunctionalMenuItemQuery = Mockito.mock(Query.class); + Mockito.when(applicationsRestClientService.get(EcompRole[].class, mockApp.getId(), "/roles")) + .thenReturn(mockEcompRoleArray); + // syncAppRolesTest + Mockito.when(session.createQuery("from " + EPRole.class.getName() + " where appId=" + mockApp.getId())) + .thenReturn(epRoleQuery); + Mockito.doReturn(mockEcompRoleList).when(epRoleQuery).list(); + Mockito.when(session.createQuery( + "from " + EPUserApp.class.getName() + " where app.id=" + mockApp.getId() + " and role_id=" + 100l)) + .thenReturn(epUserAppsQuery); + Mockito.doReturn(mockUserRolesList).when(epUserAppsQuery).list(); + + Mockito.when(session.createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + 100l)) + .thenReturn(epFunctionalMenuQuery); + Mockito.doReturn(mockFunctionalMenuRolesList).when(epFunctionalMenuQuery).list(); + + Mockito.when(session.createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + 10l)) + .thenReturn(epFunctionalMenuQuery2); + Mockito.doReturn(mockFunctionalMenuRolesList).when(epFunctionalMenuQuery2).list(); + + Mockito.when(session.createQuery("from " + FunctionalMenuItem.class.getName() + " where menuId=" + 10l)) + .thenReturn(epFunctionalMenuItemQuery); + Mockito.doReturn(mockFunctionalMenuItemList).when(epFunctionalMenuItemQuery).list(); + + Mockito.when(applicationsRestClientService.get(EPUser.class, mockApp.getId(), + String.format("/user/%s", user.getOrgUserId()), true)).thenReturn(user); + // Updated in EP DB + Query epsetExternalRequestUserAppRoleGetUserQuery = Mockito.mock(Query.class); + Query epsetExternalRequestUserAppRoleGetUserAppsQuery = Mockito.mock(Query.class); + Query epsetExternalRequestUserAppRoleGetRolesQuery = Mockito.mock(Query.class); + Mockito.when(session.get(EPApp.class, mockApp.getId())).thenReturn(mockApp); + Mockito.when(session + .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + user.getOrgUserId() + "'")) + .thenReturn(epsetExternalRequestUserAppRoleGetUserQuery); + Mockito.doReturn(mockEpUserList).when(epsetExternalRequestUserAppRoleGetUserQuery).list(); + List<EPUserApp> mockUserRolesList2 = new ArrayList<>(); + EPUserApp mockEpUserAppRoles = new EPUserApp(); + mockEpUserAppRoles.setApp(mockApp); + mockEpUserAppRoles.setRole(mockEPRole); + mockEpUserAppRoles.setUserId(user.getId()); + mockUserRolesList2.add(mockEpUserAppRoles); + Mockito.when(session.createQuery( + "from org.onap.portalapp.portal.domain.EPUserApp where app.id=2 and role.active = 'Y' and userId=2")) + .thenReturn(epsetExternalRequestUserAppRoleGetUserAppsQuery); + Mockito.doReturn(mockUserRolesList2).when(epsetExternalRequestUserAppRoleGetUserAppsQuery).list(); + List<EPRole> mockEPRoles = new ArrayList<>(); + mockEPRoles.add(mockEPRole2); + mockEPRoles.add(mockEPRole3); + Mockito.when(session.createQuery("from org.onap.portalapp.portal.domain.EPRole where appId=2")) + .thenReturn(epsetExternalRequestUserAppRoleGetRolesQuery); + Mockito.doReturn(mockEPRoles).when(epsetExternalRequestUserAppRoleGetRolesQuery).list(); + + ExternalRequestFieldsValidator mockExternalRequestFieldsValidator = new ExternalRequestFieldsValidator(true, + "Updated Successfully"); + ExternalRequestFieldsValidator externalRequestFieldsValidator = userRolesCommonServiceImpl + .setExternalRequestUserAppRole(externalSystemUser, "POST"); + assertTrue(mockExternalRequestFieldsValidator.equals(externalRequestFieldsValidator)); + } + + @SuppressWarnings("unchecked") + @Test + public void getUsersFromAppEndpointCentralizedAppTest() throws HTTPException { + EPApp mockApp = mockApp(); + mockApp.setId(1l); + mockApp.setEnabled(true); + mockApp.setCentralAuth(true); + EPUser user = mockUser.mockEPUser(); + EPUser user2 = mockUser.mockEPUser(); + user2.setActive(true); + user2.setOrgUserId("guestT2"); + user2.setId(2l); + user2.setFirstName("Guest2"); + user2.setLastName("Test2"); + user.setId(1l); + user.setFirstName("Guest"); + user.setLastName("Test"); + EPRole mockEPRole1 = new EPRole(); + mockEPRole1.setId(1l); + mockEPRole1.setName("test1"); + mockEPRole1.setActive(true); + EPRole mockEPRole2 = new EPRole(); + mockEPRole2.setId(16l); + mockEPRole2.setName("test2"); + mockEPRole2.setActive(true); + SortedSet<EPUserApp> mockUserApps1 = new TreeSet<EPUserApp>(); + EPUserApp mockEPUserApp1 = new EPUserApp(); + mockEPUserApp1.setApp(mockApp); + mockEPUserApp1.setRole(mockEPRole1); + mockEPUserApp1.setUserId(1l); + mockUserApps1.add(mockEPUserApp1); + user.setEPUserApps(mockUserApps1); + SortedSet<EPUserApp> mockUserApps2 = new TreeSet<EPUserApp>(); + EPUserApp mockEPUserApp2 = new EPUserApp(); + mockEPUserApp2.setApp(mockApp); + mockEPUserApp2.setRole(mockEPRole2); + mockEPUserApp2.setUserId(2l); + mockUserApps2.add(mockEPUserApp2); + user2.setEPUserApps(mockUserApps2); + List<EPUser> mockEpUserList = new ArrayList<>(); + mockEpUserList.add(user); + mockEpUserList.add(user2); + Mockito.when(epAppCommonServiceImpl.getApp(mockApp.getId())).thenReturn(mockApp); + List<UserApplicationRoles> mockUserApplicationRolesList = new ArrayList<>(); + UserApplicationRoles mockUserApplicationRoles = new UserApplicationRoles(); + List<RemoteRole> mockRemoteRoleList = new ArrayList<>(); + RemoteRole mockRemoteRole = new RemoteRole(); + mockRemoteRole.setId(1l); + mockRemoteRole.setName("test1"); + mockRemoteRoleList.add(mockRemoteRole); + mockUserApplicationRoles.setAppId(mockApp.getId()); + mockUserApplicationRoles.setFirstName("Guest"); + mockUserApplicationRoles.setLastName("Test"); + mockUserApplicationRoles.setOrgUserId("guestT"); + mockUserApplicationRoles.setRoles(mockRemoteRoleList); + UserApplicationRoles mockUserApplicationRoles2 = new UserApplicationRoles(); + List<RemoteRole> mockRemoteRoleList2 = new ArrayList<>(); + RemoteRole mockRemoteRole2 = new RemoteRole(); + mockRemoteRole2.setId(16l); + mockRemoteRole2.setName("test2"); + mockRemoteRoleList2.add(mockRemoteRole2); + mockUserApplicationRoles2.setAppId(mockApp.getId()); + mockUserApplicationRoles2.setFirstName("Guest2"); + mockUserApplicationRoles2.setLastName("Test2"); + mockUserApplicationRoles2.setOrgUserId("guestT2"); + mockUserApplicationRoles2.setRoles(mockRemoteRoleList2); + mockUserApplicationRolesList.add(mockUserApplicationRoles); + mockUserApplicationRolesList.add(mockUserApplicationRoles2); + Mockito.when((List<EPUser>) dataAccessService.executeNamedQuery("getActiveUsers", null, null)) + .thenReturn(mockEpUserList); + assertEquals(userRolesCommonServiceImpl.getUsersFromAppEndpoint(1l).size(), + mockUserApplicationRolesList.size()); + } + + @Test + public void getUsersFromAppEndpointNonCentralizedAppTest() throws HTTPException, JsonProcessingException { + EPApp mockApp = mockApp(); + mockApp.setId(2l); + mockApp.setEnabled(true); + mockApp.setCentralAuth(false); + Mockito.when(epAppCommonServiceImpl.getApp(mockApp.getId())).thenReturn(mockApp); + List<UserApplicationRoles> mockUserApplicationRolesNonCentralizedList = new ArrayList<>(); + UserApplicationRoles mockUserApplicationRoles = new UserApplicationRoles(); + List<RemoteRole> mockRemoteRoleList = new ArrayList<>(); + RemoteRole mockRemoteRole = new RemoteRole(); + mockRemoteRole.setId(1l); + mockRemoteRole.setName("test1"); + mockRemoteRoleList.add(mockRemoteRole); + mockUserApplicationRoles.setAppId(mockApp.getId()); + mockUserApplicationRoles.setFirstName("Guest"); + mockUserApplicationRoles.setLastName("Test"); + mockUserApplicationRoles.setOrgUserId("guestT"); + mockUserApplicationRoles.setRoles(mockRemoteRoleList); + UserApplicationRoles mockUserApplicationRoles2 = new UserApplicationRoles(); + List<RemoteRole> mockRemoteRoleList2 = new ArrayList<>(); + RemoteRole mockRemoteRole2 = new RemoteRole(); + mockRemoteRole2.setId(16l); + mockRemoteRole2.setName("test2"); + mockRemoteRoleList2.add(mockRemoteRole2); + mockUserApplicationRoles2.setAppId(mockApp.getId()); + mockUserApplicationRoles2.setFirstName("Guest2"); + mockUserApplicationRoles2.setLastName("Test2"); + mockUserApplicationRoles2.setOrgUserId("guestT2"); + mockUserApplicationRoles2.setRoles(mockRemoteRoleList2); + mockUserApplicationRolesNonCentralizedList.add(mockUserApplicationRoles); + mockUserApplicationRolesNonCentralizedList.add(mockUserApplicationRoles2); + RemoteUserWithRoles mockRemoteUserWithRoles1 = new RemoteUserWithRoles(); + mockRemoteUserWithRoles1.setFirstName("Guest1"); + mockRemoteUserWithRoles1.setLastName("Test1"); + mockRemoteUserWithRoles1.setOrgUserId("guestT"); + mockRemoteUserWithRoles1.setRoles(mockRemoteRoleList); + RemoteUserWithRoles mockRemoteUserWithRoles2 = new RemoteUserWithRoles(); + mockRemoteUserWithRoles2.setFirstName("Guest2"); + mockRemoteUserWithRoles2.setLastName("Test2"); + mockRemoteUserWithRoles2.setOrgUserId("guestT"); + mockRemoteUserWithRoles2.setRoles(mockRemoteRoleList2); + List<RemoteUserWithRoles> mockRemoteUserWithRolesList = new ArrayList<>(); + mockRemoteUserWithRolesList.add(mockRemoteUserWithRoles1); + mockRemoteUserWithRolesList.add(mockRemoteUserWithRoles2); + ObjectMapper mapper = new ObjectMapper(); + String mockGetRemoteUsersWithRoles = mapper.writeValueAsString(mockRemoteUserWithRolesList); + Mockito.when(applicationsRestClientService.getIncomingJsonString(mockApp.getId(), "/users")) + .thenReturn(mockGetRemoteUsersWithRoles); + List<UserApplicationRoles> userApplicationRolesNonCentralizedList = userRolesCommonServiceImpl + .getUsersFromAppEndpoint(2l); + assertEquals(mockUserApplicationRolesNonCentralizedList.size(), userApplicationRolesNonCentralizedList.size()); + } + + @SuppressWarnings("unchecked") + @Test + public void putUserAppRolesRequestTest() { + EPApp mockApp = mockApp(); + mockApp.setId(2l); + mockApp.setEnabled(true); + mockApp.setCentralAuth(false); + EPUser user = mockUser.mockEPUser(); + AppWithRolesForUser appWithRolesForUser = new AppWithRolesForUser(); + List<RoleInAppForUser> mockRoleInAppForUserList = new ArrayList<>(); + RoleInAppForUser roleInAppForUser = new RoleInAppForUser(); + roleInAppForUser.setIsApplied(true); + roleInAppForUser.setRoleId(1l); + roleInAppForUser.setRoleName("test1"); + RoleInAppForUser roleInAppForUser2 = new RoleInAppForUser(); + roleInAppForUser2.setIsApplied(true); + roleInAppForUser2.setRoleId(1000l); + roleInAppForUser2.setRoleName("test3"); + mockRoleInAppForUserList.add(roleInAppForUser); + mockRoleInAppForUserList.add(roleInAppForUser2); + appWithRolesForUser.setAppId(mockApp.getId()); + appWithRolesForUser.setAppName(mockApp.getName()); + appWithRolesForUser.setOrgUserId(user.getOrgUserId()); + appWithRolesForUser.setAppRoles(mockRoleInAppForUserList); + List<EPUserAppRoles> epUserAppRolesList = new ArrayList<>(); + EPUserAppRoles appRole1 = new EPUserAppRoles(); + appRole1.setAppId(mockApp.getId()); + appRole1.setId(10l); + appRole1.setRoleId(roleInAppForUser.roleId); + epUserAppRolesList.add(appRole1); + List<EPUserAppRoles> epUserAppRolesList2 = new ArrayList<>(); + EPUserAppRoles appRole2 = new EPUserAppRoles(); + appRole2.setAppId(mockApp.getId()); + appRole2.setId(11l); + appRole2.setRoleId(roleInAppForUser2.roleId); + epUserAppRolesList2.add(appRole2); + EPUserAppRolesRequest mockEpAppRolesRequestData = new EPUserAppRolesRequest(); + Mockito.doNothing().when(dataAccessService).saveDomainObject(mockEpAppRolesRequestData, null); + final Map<String, Long> params = new HashMap<>(); + params.put("appId", appWithRolesForUser.appId); + params.put("appRoleId", roleInAppForUser.roleId); + Mockito.when((List<EPUserAppRoles>) dataAccessService.executeNamedQuery("appRoles", params, null)) + .thenReturn(epUserAppRolesList); + params.put("appRoleId", roleInAppForUser2.roleId); + Mockito.when((List<EPUserAppRoles>) dataAccessService.executeNamedQuery("appRoles", params, null)) + .thenReturn(epUserAppRolesList2); + EPUserAppRolesRequestDetail mockEPAppRoleDetail = new EPUserAppRolesRequestDetail(); + Mockito.doNothing().when(dataAccessService).saveDomainObject(mockEPAppRoleDetail, null); + FieldsValidator expected = new FieldsValidator(); + expected.setHttpStatusCode(Long.valueOf(HttpServletResponse.SC_OK)); + FieldsValidator actual = userRolesCommonServiceImpl.putUserAppRolesRequest(appWithRolesForUser, user); + assertEquals(expected, actual); + } + + @Test + public void importRolesFromRemoteApplicationTest() throws HTTPException { + EPApp mockApp = mockApp(); + mockApp.setId(2l); + mockApp.setEnabled(true); + mockApp.setCentralAuth(false); + List<EPRole> expected = new ArrayList<>(); + EPRole epRole = new EPRole(); + epRole.setAppId(mockApp.getId()); + epRole.setActive(true); + epRole.setId(10l); + epRole.setName("test1"); + EPRole epRole2 = new EPRole(); + epRole2.setAppId(mockApp.getId()); + epRole2.setActive(true); + epRole2.setId(11l); + epRole2.setName("test2"); + expected.add(epRole); + expected.add(epRole2); + EPRole[] epRoleArray = expected.toArray(new EPRole[expected.size()]); + Mockito.when(applicationsRestClientService.get(EPRole[].class, mockApp.getId(), "/rolesFull")) + .thenReturn(epRoleArray); + Mockito.when(epRoleServiceImpl.getRole(mockApp.getId(), epRole.getId())).thenReturn(epRole); + Mockito.when(epRoleServiceImpl.getRole(mockApp.getId(), epRole2.getId())).thenReturn(epRole2); + List<EPRole> actual = userRolesCommonServiceImpl.importRolesFromRemoteApplication(mockApp.getId()); + assertEquals(expected.size(), actual.size()); + } + + @SuppressWarnings("deprecation") + @Test + public void getCachedAppRolesForUserTest() { + EPApp mockApp = mockApp(); + mockApp.setId(2l); + mockApp.setEnabled(true); + mockApp.setCentralAuth(false); + EPUser user = mockUser.mockEPUser(); + List<EPUserApp> expected = new ArrayList<>(); + EPUserApp epUserApp = new EPUserApp(); + EPRole epRole = new EPRole(); + epRole.setAppId(mockApp.getId()); + epRole.setActive(true); + epRole.setId(10l); + epRole.setName("test1"); + epUserApp.setApp(mockApp); + epUserApp.setRole(epRole); + epUserApp.setUserId(user.getId()); + expected.add(epUserApp); + String filter = " where user_id = " + Long.toString(user.getId()) + " and app_id = " + + Long.toString(mockApp.getId()); + Mockito.when(dataAccessService.getList(EPUserApp.class, filter, null, null)).thenReturn(expected); + List<EPUserApp> actual = userRolesCommonServiceImpl.getCachedAppRolesForUser(mockApp.getId(), user.getId()); + assertEquals(expected.size(), actual.size()); + } + + @SuppressWarnings("unchecked") + @Test + public void getUserAppCatalogRolesTest() { + EPApp mockApp = mockApp(); + mockApp.setId(2l); + mockApp.setEnabled(true); + mockApp.setCentralAuth(false); + EPUser user = mockUser.mockEPUser(); + List<EPUserAppCatalogRoles> expected = new ArrayList<>(); + EPUserAppCatalogRoles epUserAppCatalogRoles = new EPUserAppCatalogRoles(); + epUserAppCatalogRoles.setAppId(mockApp.getId()); + epUserAppCatalogRoles.setId(2l); + epUserAppCatalogRoles.setRequestedRoleId(10l); + epUserAppCatalogRoles.setRequestStatus("S"); + epUserAppCatalogRoles.setRolename("test1"); + expected.add(epUserAppCatalogRoles); + Map<String, String> params = new HashMap<>(); + params.put("userid", user.getId().toString()); + params.put("appName", mockApp.getName()); + Mockito.when( + (List<EPUserAppCatalogRoles>) dataAccessService.executeNamedQuery("userAppCatalogRoles", params, null)) + .thenReturn(expected); + List<EPUserAppCatalogRoles> actual = userRolesCommonServiceImpl.getUserAppCatalogRoles(user, mockApp.getName()); + assertEquals(expected.size(), actual.size()); + } + + @Test + public void getExternalRequestAccessTest() { + ExternalSystemAccess expected = new ExternalSystemAccess("external_access_enable", false); + ExternalSystemAccess actual = userRolesCommonServiceImpl.getExternalRequestAccess(); + assertEquals(expected, actual); + } + + @Test + public void getEPUserAppListTest() { + EPApp mockApp = mockApp(); + mockApp.setId(2l); + mockApp.setEnabled(true); + mockApp.setCentralAuth(false); + EPUser user = mockUser.mockEPUser(); + List<EPUserApp> expected = new ArrayList<>(); + EPUserApp epUserApp = new EPUserApp(); + EPRole epRole = new EPRole(); + epRole.setAppId(mockApp.getId()); + epRole.setActive(true); + epRole.setId(10l); + epRole.setName("test1"); + epUserApp.setApp(mockApp); + epUserApp.setRole(epRole); + epUserApp.setUserId(user.getId()); + expected.add(epUserApp); + final Map<String, Long> params = new HashMap<>(); + params.put("appId", mockApp.getId()); + params.put("userId", user.getId()); + params.put("roleId", epRole.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndRoleIdAndAppId", params, null)) + .thenReturn(expected); + List<EPUserApp> actual = userRolesCommonServiceImpl.getEPUserAppList(mockApp.getId(), user.getId(), + epRole.getId()); + assertEquals(expected.size(), actual.size()); + } + + @Test + public void updateRemoteUserProfileTest() { + EPApp mockApp = mockApp(); + EPApp mockApp2 = mockApp(); + mockApp.setId(2l); + mockApp.setEnabled(true); + mockApp.setCentralAuth(false); + EPUser user = mockUser.mockEPUser(); + List<EPApp> mockEpAppList = new ArrayList<>(); + mockEpAppList.add(mockApp); + mockEpAppList.add(mockApp2); + Mockito.when(searchServiceImpl.searchUserByUserId(user.getOrgUserId())).thenReturn(user); + Mockito.when(epAppCommonServiceImpl.getUserRemoteApps(user.getId().toString())).thenReturn(mockEpAppList); + String expected = "success"; + String actual = userRolesCommonServiceImpl.updateRemoteUserProfile(user.getOrgUserId(), mockApp.getId()); + assertEquals(expected, actual); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserServiceImplTest.java new file mode 100644 index 00000000..b8bb1652 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserServiceImplTest.java @@ -0,0 +1,178 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.portal.service; + +import static org.junit.Assert.assertEquals; + +import java.io.ByteArrayInputStream; +import java.net.HttpURLConnection; +import java.util.ArrayList; +import java.util.List; + +import org.hibernate.criterion.Criterion; +import org.hibernate.criterion.Restrictions; +import org.json.simple.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.EPApp; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.utils.EPCommonSystemProperties; +import org.onap.portalapp.portal.utils.EcompPortalUtils; +import org.onap.portalapp.portal.utils.PortalConstants; +import org.onap.portalsdk.core.onboarding.util.CipherUtil; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.service.DataAccessServiceImpl; +import org.onap.portalsdk.core.util.SystemProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ EcompPortalUtils.class, SystemProperties.class, PortalConstants.class, + EPCommonSystemProperties.class, Criterion.class, CipherUtil.class, Restrictions.class }) +public class UserServiceImplTest { + + @Mock + DataAccessService dataAccessService = new DataAccessServiceImpl(); + + @InjectMocks + UserServiceImpl userServiceImpl= new UserServiceImpl(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + public EPApp mockApp() { + EPApp app = new EPApp(); + app.setName("Test"); + app.setImageUrl("test"); + app.setNameSpace("com.test.app"); + app.setCentralAuth(true); + app.setDescription("test"); + app.setNotes("test"); + app.setUrl("test"); + app.setId((long) 10); + app.setAppRestEndpoint("test"); + app.setAlternateUrl("test"); + app.setName("test"); + app.setMlAppName("test"); + app.setMlAppAdminId("test"); + app.setUsername("test"); + app.setAppPassword("test"); + app.setOpen(false); + app.setEnabled(true); + app.setUebKey("test"); + app.setUebSecret("test"); + app.setUebTopicName("test"); + app.setAppType(1); + return app; + } + + MockEPUser mockUser = new MockEPUser(); + + @SuppressWarnings("unchecked") + @Test + public void getUserByUserIdExceptionTest() throws Exception { + PowerMockito.mockStatic(SystemProperties.class); + EPUser user = mockUser.mockEPUser(); + Mockito.when(SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM)).thenReturn("OIDC"); + Mockito.when(EPCommonSystemProperties.getProperty(EPCommonSystemProperties.AUTH_USER_SERVER)).thenReturn("http://www.test.com"); + HttpURLConnection connection = Mockito.mock(HttpURLConnection.class); + JSONObject response = new JSONObject(); + JSONObject userJson = new JSONObject(); + userJson.put("id", 1); + userJson.put("givenName", "Guest"); + userJson.put("familyName", "Test"); + userJson.put("email", "test@123.com"); + List<JSONObject> userListJson = new ArrayList<>(); + userListJson.add(userJson); + response.put("response", userListJson); + ByteArrayInputStream getBody = new ByteArrayInputStream(response.toString().getBytes("UTF-8")); + PowerMockito.when(connection.getInputStream()).thenReturn(getBody); + userServiceImpl.getUserByUserId(user.getOrgUserId()); + } + + @SuppressWarnings("unchecked") + @Test + public void saveNewUserTest() throws Exception { + PowerMockito.mockStatic(Restrictions.class); + PowerMockito.mockStatic(Criterion.class); + PowerMockito.mockStatic(CipherUtil.class); + EPUser user = mockUser.mockEPUser(); + List<EPUser> users = new ArrayList<>(); + Mockito.when(CipherUtil.encryptPKC(user.getLoginPwd())).thenReturn("xyz"); + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion orgUserIdCriterion = Restrictions.eq("orgUserId",user.getLoginId()); + restrictionsList.add(orgUserIdCriterion); + Mockito.when((List<EPUser>) dataAccessService.getList(EPUser.class, null, restrictionsList, null)).thenReturn(users); + String actual = userServiceImpl.saveNewUser(user, "No"); + assertEquals("success", actual); + } + + @SuppressWarnings("unchecked") + @Test + public void saveExistingUserTest() throws Exception { + PowerMockito.mockStatic(Restrictions.class); + PowerMockito.mockStatic(Criterion.class); + PowerMockito.mockStatic(CipherUtil.class); + EPUser user = mockUser.mockEPUser(); + user.setLoginPwd("xyz"); + List<EPUser> users = new ArrayList<>(); + users.add(user); + EPUser oldUser = mockUser.mockEPUser(); + oldUser.setLoginPwd("abc"); + List<EPUser> oldUsers = new ArrayList<>(); + oldUsers.add(oldUser); + Mockito.when(CipherUtil.encryptPKC(user.getLoginPwd())).thenReturn("xyz"); + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion orgUserIdCriterion = Restrictions.eq("orgUserId",user.getLoginId()); + restrictionsList.add(orgUserIdCriterion); + Mockito.when((List<EPUser>) dataAccessService.getList(EPUser.class, null, restrictionsList, null)).thenReturn(oldUsers); + String actual = userServiceImpl.saveNewUser(user, "No"); + assertEquals("success", actual); + } + + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/WidgetParameterServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/WidgetParameterServiceImplTest.java new file mode 100644 index 00000000..ffaee13f --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/WidgetParameterServiceImplTest.java @@ -0,0 +1,129 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.portal.service; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.hibernate.criterion.Criterion; +import org.hibernate.criterion.Restrictions; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.WidgetCatalogParameter; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.service.DataAccessServiceImpl; + +public class WidgetParameterServiceImplTest { + @Mock + DataAccessService dataAccessService = new DataAccessServiceImpl(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @InjectMocks + WidgetParameterServiceImpl widgetParameterServiceImpl = new WidgetParameterServiceImpl(); + + MockEPUser mockUser = new MockEPUser(); + + @SuppressWarnings("unchecked") + @Test + public void getUserParamByIdTest() { + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion widgetIdCrit = Restrictions.eq("widgetId", "1"); + restrictionsList.add(widgetIdCrit); + Criterion userIdCrit = Restrictions.eq("userId", "1"); + restrictionsList.add(userIdCrit); + Criterion paramIdCrit = Restrictions.eq("paramId", "1"); + restrictionsList.add(paramIdCrit); + List<WidgetCatalogParameter> mockWidgetCatParamsList = new ArrayList<>(); + Mockito.when((List<WidgetCatalogParameter>)dataAccessService + .getList(WidgetCatalogParameter.class, null, restrictionsList, null)).thenReturn(mockWidgetCatParamsList); + WidgetCatalogParameter widgetCatalogParameter = widgetParameterServiceImpl.getUserParamById(1l, 1l, 1l); + if(mockWidgetCatParamsList.isEmpty()) { + mockWidgetCatParamsList = null; + } + assertEquals(widgetCatalogParameter, mockWidgetCatParamsList); + } + + @Test + public void saveUserParameterTest(){ + WidgetCatalogParameter mockWidgetParameter = new WidgetCatalogParameter(); + WidgetCatalogParameter widgetParameter = new WidgetCatalogParameter(); + widgetParameter.setId(1l); + widgetParameter.setParamId(1l); + widgetParameter.setUser_value("test"); + widgetParameter.setWidgetId(1l); + widgetParameter.setUserId(1l); + Mockito.doNothing().when(dataAccessService).saveDomainObject(mockWidgetParameter, null); + widgetParameterServiceImpl.saveUserParameter(widgetParameter); + } + + @SuppressWarnings("unchecked") + @Test + public void getUserParameterByIdTest() { + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion paramIdCrit = Restrictions.eq("paramId", 1); + restrictionsList.add(paramIdCrit); + List<WidgetCatalogParameter> mockWidgetCatalogParameter = new ArrayList<>(); + Mockito.when((List<WidgetCatalogParameter>) dataAccessService + .getList(WidgetCatalogParameter.class, null, restrictionsList, null)).thenReturn(mockWidgetCatalogParameter); + List<WidgetCatalogParameter> list = widgetParameterServiceImpl.getUserParameterById(1l); + assertEquals(list, mockWidgetCatalogParameter); + } + + @Test + public void deleteUserParameterById() { + Map<String, String> params = new HashMap<String, String>(); + params.put("paramId", Long.toString(1)); + Mockito.when(dataAccessService.executeNamedQuery("deleteWidgetCatalogParameter", params, null)).thenReturn(null); + Mockito.when(dataAccessService.executeNamedQuery("deleteMicroserviceParameterById", params, null)).thenReturn(null); + widgetParameterServiceImpl.deleteUserParameterById(1l); + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/WidgetServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/WidgetServiceImplTest.java new file mode 100644 index 00000000..2d016207 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/WidgetServiceImplTest.java @@ -0,0 +1,259 @@ +/* +* ============LICENSE_START======================================================= +* ONAP PORTAL +* ================================================================================ +* Copyright 2018 TechMahindra +*================================================================================= +* Licensed 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 +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* ============LICENSE_END========================================================= +*/ +package org.onap.portalapp.portal.service; + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.criterion.Criterion; +import org.hibernate.criterion.Restrictions; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.domain.EPUserApp; +import org.onap.portalapp.portal.domain.Widget; +import org.onap.portalapp.portal.framework.MockitoTestSuite; +import org.onap.portalapp.portal.transport.FieldsValidator; +import org.onap.portalapp.portal.transport.OnboardingWidget; +import org.onap.portalsdk.core.service.DataAccessService; + +public class WidgetServiceImplTest { + + @Mock + DataAccessService dataAccessService; + @Mock + AdminRolesService adminRolesService; + @Mock + SessionFactory sessionFactory; + @Mock + Session session; + + @Mock + Transaction transaction; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + Mockito.when(sessionFactory.openSession()).thenReturn(session); + Mockito.when(session.beginTransaction()).thenReturn(transaction); + } + + @InjectMocks + WidgetServiceImpl widgetServiceImpl = new WidgetServiceImpl(); + + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + NullPointerException nullPointerException = new NullPointerException(); + MockEPUser mockUser = new MockEPUser(); + + Long ACCOUNT_ADMIN_ROLE_ID = 99l; + Long LONG_ECOMP_APP_ID = 1l; + + + @Test + public void getOnboardingWidgetsTest_isSuperAdmin() { + EPUser user = mockUser.mockEPUser(); + List<OnboardingWidget> onboardingWidgets = new ArrayList<>(); + OnboardingWidget widget = new OnboardingWidget(); + onboardingWidgets.add(widget); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + String sql = "SELECT widget.WIDGET_ID, widget.WDG_NAME, widget.APP_ID, app.APP_NAME, widget.WDG_WIDTH, widget.WDG_HEIGHT, widget.WDG_URL" + + "from FN_WIDGET widget join FN_APP app ON widget.APP_ID = app.APP_ID"+ " validAppsFilter "; + + widgetServiceImpl.getOnboardingWidgets(user, true); + } + + @Test + public void getOnboardingWidgetsTest_isAccountAdmin() { + EPUser user = mockUser.mockEPUser(); + List<OnboardingWidget> onboardingWidgets = new ArrayList<>(); + OnboardingWidget widget = new OnboardingWidget(); + onboardingWidgets.add(widget); + Mockito.when(adminRolesService.isSuperAdmin(null)).thenReturn(false); + Mockito.when(adminRolesService.isAccountAdmin(user)).thenReturn(true); + String sql = "SELECT widget.WIDGET_ID, widget.WDG_NAME, widget.APP_ID, app.APP_NAME, widget.WDG_WIDTH, widget.WDG_HEIGHT, widget.WDG_URL" + + " from FN_WIDGET widget join FN_APP app ON widget.APP_ID = app.APP_ID" + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = " + 1l + + " AND FN_USER_ROLE.ROLE_ID = " + 99l + "validAppsFilter"; + widgetServiceImpl.getOnboardingWidgets(user, true); + } + + @Test + public void getOnboardingWidgetsTest_isUser() { + EPUser user = mockUser.mockEPUser(); + List<OnboardingWidget> onboardingWidgets = new ArrayList<>(); + OnboardingWidget widget = new OnboardingWidget(); + onboardingWidgets.add(widget); + Mockito.when(adminRolesService.isUser(user)).thenReturn(true); + Mockito.when(adminRolesService.isAccountAdmin(null)).thenReturn(false); + String sql = "SELECT DISTINCT widget.WIDGET_ID, widget.WDG_NAME, widget.APP_ID, app.APP_NAME, widget.WDG_WIDTH, widget.WDG_HEIGHT, widget.WDG_URL\"\r\n" + + " + \" from FN_WIDGET widget join FN_APP app ON widget.APP_ID = app.APP_ID" + + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = " + + 99l + "validAppsFilter"; + widgetServiceImpl.getOnboardingWidgets(user, false); + } + + + @Test + public void setOnboardingWidgetTest() { + EPUser user = mockUser.mockEPUser(); + OnboardingWidget widget = new OnboardingWidget(); + widget.name = "test"; + widget.appId = 1l; + widget.url = "demo"; + FieldsValidator fieldValidator = new FieldsValidator(); + fieldValidator.setHttpStatusCode(400l); + widgetServiceImpl.setOnboardingWidget(user, widget); + } + + @Test + public void setOnboardingWidgetTest_updateOrSaveWidget() { + EPUser user = mockUser.mockEPUser(); + OnboardingWidget widget = new OnboardingWidget(); + Mockito.when(adminRolesService.isSuperAdmin(null)).thenReturn(false); + widget.name = "test"; + widget.appId = 9l; + widget.url = "demo"; + widget.width = 1; + widget.height = 1; + FieldsValidator fieldValidator = new FieldsValidator(); + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion userIdCriterion = Restrictions.eq("userId",1l); + Criterion roleIDCriterion = Restrictions.eq("role.id", 99l); + Criterion appIDCriterion = Restrictions.eq("app.id", 2l); + restrictionsList.add(Restrictions.and(userIdCriterion, roleIDCriterion,appIDCriterion)); + List<EPUserApp> userRoles = new ArrayList<>(); + EPUserApp app = new EPUserApp(); + userRoles.add(app); + Mockito.when((List<EPUserApp>) dataAccessService.getList(EPUserApp.class, null, restrictionsList, null)) + .thenReturn(userRoles); + fieldValidator.setHttpStatusCode(403l); + widgetServiceImpl.setOnboardingWidget(user, widget); + } + + @Test + public void setOnboardingWidgetTest_updateOrSaveWidget_isSuperAdmin() { + FieldsValidator fieldValidator = new FieldsValidator(); + EPUser user = mockUser.mockEPUser(); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + user.setId(1l); + OnboardingWidget onboardingWidget = new OnboardingWidget(); + onboardingWidget.name="test"; + onboardingWidget.url="demo"; + onboardingWidget.id = 2l; + onboardingWidget.appId = 9l; + onboardingWidget.width = 1; + onboardingWidget.height = 1; + Widget widget = new Widget(); + Mockito.when(dataAccessService.getDomainObject(Widget.class, 2l, null)).thenReturn(widget); + widget.setId(1l); + + fieldValidator.setHttpStatusCode(404l); + widgetServiceImpl.setOnboardingWidget(user, onboardingWidget); + } + + @Test + public void setOnboardingWidgetTest_applyOnboardingWidget() { + FieldsValidator fieldValidator = new FieldsValidator(); + EPUser user = mockUser.mockEPUser(); + fieldValidator.setHttpStatusCode(200l); + OnboardingWidget onboardingWidget = new OnboardingWidget(); + onboardingWidget.name="test"; + onboardingWidget.url="demo"; + onboardingWidget.id = 2l; + onboardingWidget.appId = 9l; + onboardingWidget.width = 1; + onboardingWidget.height = 1; + Widget widget = new Widget(); + widget.setAppId(onboardingWidget.appId); + widget.setName(onboardingWidget.name); + widget.setWidth(onboardingWidget.width); + widget.setHeight(onboardingWidget.height); + widget.setUrl("demo"); + widgetServiceImpl.setOnboardingWidget(user, onboardingWidget); + } + + @Test + public void setOnboardingWidgetTest_validateOnboardingWidget() { + EPUser user = mockUser.mockEPUser(); + user.setId(1l); + FieldsValidator fieldsValidator = new FieldsValidator(); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + OnboardingWidget onboardingWidget = new OnboardingWidget(); + onboardingWidget.name="test"; + onboardingWidget.url="demo"; + onboardingWidget.appId = 9l; + onboardingWidget.width = 1; + onboardingWidget.height = 1; + onboardingWidget.id = null; + List<Widget> listWidget = new ArrayList<>(); + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion urlCriterion = Restrictions.eq("url", onboardingWidget.url); + Criterion nameCriterion = Restrictions.eq("name", onboardingWidget.name); + restrictionsList.add(Restrictions.or(urlCriterion, nameCriterion)); + Mockito.when((List<Widget>) dataAccessService.getList(Widget.class, null, restrictionsList, null)) + .thenReturn(listWidget); + Widget widget = new Widget(); + widget.setName("test"); + widget.setAppId(9l); + boolean dublicatedName = true; + boolean dublicatedUrl= true; + fieldsValidator.addProblematicFieldName("demo"); + fieldsValidator.addProblematicFieldName("test"); + fieldsValidator.setHttpStatusCode(409l); + widgetServiceImpl.setOnboardingWidget(user, onboardingWidget); + } + + @Test + public void deleteOnboardingWidgetTest() { + EPUser user = mockUser.mockEPUser(); + OnboardingWidget onboardingWidget = new OnboardingWidget(); + FieldsValidator fieldValidator = new FieldsValidator(); + Widget widget = new Widget(); + Mockito.when(dataAccessService.getDomainObject(Widget.class, 1l, null)).thenReturn(widget); + widget.setId(1l); + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion userIdCriterion = Restrictions.eq("userId",1l); + Criterion roleIDCriterion = Restrictions.eq("role.id", 99l); + Criterion appIDCriterion = Restrictions.eq("app.id", 2l); + restrictionsList.add(Restrictions.and(userIdCriterion, roleIDCriterion,appIDCriterion)); + List<EPUserApp> userRoles = new ArrayList<>(); + EPUserApp app = new EPUserApp(); + userRoles.add(app); + Mockito.when((List<EPUserApp>) dataAccessService.getList(EPUserApp.class, null, restrictionsList, null)) + .thenReturn(userRoles); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + fieldValidator.setHttpStatusCode(403l); + widgetServiceImpl.deleteOnboardingWidget(user, 1l); + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/ueb/EPUebHelperTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/ueb/EPUebHelperTest.java new file mode 100644 index 00000000..226d9709 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/ueb/EPUebHelperTest.java @@ -0,0 +1,157 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.portal.ueb; + +import static org.junit.Assert.assertFalse; + +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.domain.EcompApp; +import org.onap.portalapp.portal.service.EPAppCommonServiceImpl; +import org.onap.portalapp.portal.utils.PortalConstants; +import org.onap.portalsdk.core.onboarding.util.PortalApiConstants; +import org.onap.portalsdk.core.onboarding.util.PortalApiProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import com.att.nsa.apiClient.http.HttpClient; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({PortalApiProperties.class, HttpClient.class, URL.class, PortalConstants.class}) +public class EPUebHelperTest { + + @Mock + EPAppCommonServiceImpl epAppCommonServiceImpl = new EPAppCommonServiceImpl(); + + @Mock + SessionFactory sessionFactory; + + @Mock + Session session; + + @Mock + Transaction transaction; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + Mockito.when(sessionFactory.openSession()).thenReturn(session); + } + + @InjectMocks + EPUebHelper epUebHelper = new EPUebHelper(); + + @Test + public void refreshPublisherForPortalListTest() { + List<EcompApp> ecompApps = new ArrayList<>(); + EcompApp ecompApp = new EcompApp(); + ecompApp.setCentralAuth(true); + ecompApp.setId(1l); + ecompApp.setName("test"); + ecompApp.setEnabled(true); + ecompApp.setUebTopicName("ECOMP-PORTAL-INBOX"); + ecompApps.add(ecompApp); + Mockito.when(epAppCommonServiceImpl.getEcompAppAppsFullList()).thenReturn(ecompApps); + epUebHelper.refreshPublisherList(); + } + + @Test + public void refreshPublisherForPartnersListTest() { + PowerMockito.mockStatic(PortalConstants.class); + PowerMockito.mockStatic(PortalApiProperties.class); + List<EcompApp> ecompApps = new ArrayList<>(); + EcompApp ecompApp = new EcompApp(); + ecompApp.setCentralAuth(true); + ecompApp.setId(2l); + ecompApp.setName("test"); + ecompApp.setEnabled(true); + ecompApp.setUebTopicName("Test"); + ecompApps.add(ecompApp); + Mockito.when(epAppCommonServiceImpl.getEcompAppAppsFullList()).thenReturn(ecompApps); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME)).thenReturn("ecomp_portal_inbox_name"); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_INBOUND_MAILBOX_NAME)).thenReturn("ueb_app_mailbox_name"); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY)).thenReturn("ueb_app_key"); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET)).thenReturn("ueb_app_secret"); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_CONSUMER_GROUP_NAME)).thenReturn("ueb_app_consumer_group_name"); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.UEB_URL_LIST)).thenReturn("ueb_url_list"); + epUebHelper.refreshPublisherList(); + } + + @Test + public void refreshPublisherForExceptionListTest() { + List<EcompApp> ecompApps = new ArrayList<>(); + EcompApp ecompApp = new EcompApp(); + ecompApp.setCentralAuth(true); + ecompApp.setId(2l); + ecompApp.setName("test"); + ecompApp.setEnabled(true); + ecompApp.setUebTopicName("Test"); + ecompApps.add(ecompApp); + Mockito.doThrow(new NullPointerException()).when(epAppCommonServiceImpl).getEcompAppAppsFullList(); + epUebHelper.refreshPublisherList(); + } + + @Test + public void checkAvailabilityConectionRefusedTest() throws Exception { + PowerMockito.mockStatic(PortalConstants.class); + PowerMockito.mockStatic(PortalApiProperties.class); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.UEB_URL_LIST)).thenReturn("localhost"); + URL u = PowerMockito.mock(URL.class); + String url = "http://localhost:3904/topics/null"; + PowerMockito.whenNew(URL.class).withArguments(url).thenReturn(u); + HttpURLConnection huc = PowerMockito.mock(HttpURLConnection.class); + PowerMockito.when(u.openConnection()).thenReturn(huc); + PowerMockito.when(huc.getResponseCode()).thenReturn(200); + boolean actual = epUebHelper.checkAvailability(); + assertFalse(actual); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/utils/EcompPortalUtilsTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/utils/EcompPortalUtilsTest.java index efc1dab1..2af02c32 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/utils/EcompPortalUtilsTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/utils/EcompPortalUtilsTest.java @@ -39,11 +39,26 @@ package org.onap.portalapp.portal.utils; import static org.junit.Assert.assertEquals; +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + import org.junit.Test; -import org.onap.portalapp.portal.utils.EcompPortalUtils; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.framework.MockitoTestSuite; public class EcompPortalUtilsTest { + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + MockEPUser mockUser = new MockEPUser(); + + @Test public void legitimateAttuidSuccessTest() { assertEquals(true, EcompPortalUtils.legitimateUserId("mm016f")); @@ -53,4 +68,36 @@ public class EcompPortalUtilsTest { public void legitimateAttuidFailureTest() { assertEquals(false, EcompPortalUtils.legitimateUserId("1#@23456")); } + + + @Test + public void parsingByRegularExpressionTest() { + List<String> expected = new ArrayList<>(); + expected.add("test"); + expected.add("123"); + assertEquals(expected,EcompPortalUtils.parsingByRegularExpression("test 123"," ")); + } + + @Test + public void jsonErrorMessageResponseTest() { + String expected = "{\"error\":{\"code\":" + 200 + "," + "\"message\":\"" + "test" + "\"}}"; + assertEquals(expected,EcompPortalUtils.jsonErrorMessageResponse(200, "test")); + } + + @Test + public void jsonMessageResponseTest() { + String expected = "{\"message\":\"test\"}"; + assertEquals(expected,EcompPortalUtils.jsonMessageResponse("test")); + } + + @Test + public void logAndSerializeObjectTest() { + EcompPortalUtils.logAndSerializeObject("test", "test", EcompPortalUtils.class); + } + + @Test + public void setBadPermissionsForEmptyUserTest() { + EcompPortalUtils.setBadPermissions(new EPUser(), mockedResponse, "test"); + } + } |