diff options
Diffstat (limited to 'ecomp-sdk/epsdk-app-common')
15 files changed, 1902 insertions, 140 deletions
diff --git a/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/ElasticSearchControllerTest.java b/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/ElasticSearchControllerTest.java index 7a0d47cd..68e53039 100644 --- a/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/ElasticSearchControllerTest.java +++ b/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/ElasticSearchControllerTest.java @@ -45,6 +45,7 @@ import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.apache.http.conn.ssl.SSLInitializationException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -72,7 +73,6 @@ import io.searchbox.client.JestClientFactory; import io.searchbox.client.config.HttpClientConfig; import io.searchbox.client.http.JestHttpClient; - @RunWith(PowerMockRunner.class) @PrepareForTest({ JestClientFactory.class, JestClient.class }) public class ElasticSearchControllerTest { @@ -84,62 +84,48 @@ public class ElasticSearchControllerTest { public void setup() { MockitoAnnotations.initMocks(this); } + @Mock JestClientFactory factory; @Mock - JestClient client ; - + JestClient client; + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); - + @Test - public void searchTest() - { - ModelAndView expectedResult = elasticSearchController.search(); - assertEquals(expectedResult.getViewName(), "es_search_demo"); + public void searchTest() { + ModelAndView expectedResult = elasticSearchController.search(); + assertEquals(expectedResult.getViewName(), "es_search_demo"); } - + @Test - public void suggestTest() - { - ModelAndView expectedResult = elasticSearchController.suggest(); - assertEquals(expectedResult.getViewName(), "es_suggest_demo"); + public void suggestTest() { + ModelAndView expectedResult = elasticSearchController.suggest(); + assertEquals(expectedResult.getViewName(), "es_suggest_demo"); + } + + @Test(expected = Exception.class) + public void doSuggestTest() throws IOException { + String task = "{ \"data\" : \"Data\" , \"size\" : \"Size\" , \"fuzzy\" : \"Fuzzy\", \"resultname\" : \"Result Name\" }"; + elasticSearchController.doSuggest(task); } -// @Test -// public void doSuggestTest() throws IOException -// { -// PowerMockito.mockStatic(JestClient.class); -// PowerMockito.mockStatic(JestClientFactory.class); -// SearchResult result = new SearchResult(new Gson()); -// Mockito.when(factory.getObject()).thenReturn(client); -// Mockito.when(client.execute(Matchers.anyObject())).thenReturn(result); -//// Mockito.doNothing().when(factory).setHttpClientConfig(new HttpClientConfig -//// .Builder(Matchers.anyString()) -//// .multiThreaded(Matchers.anyBoolean()) -//// .build()); -// -// JestClientFactory factory = Mockito.spy(new JestClientFactory()); -// HttpClientConfig httpClientConfig = Mockito.spy(new HttpClientConfig.Builder("http://localhost:9200") -// .discoveryEnabled(true) -// .build()); -// factory.setHttpClientConfig(httpClientConfig); -// JestHttpClient jestClient = (JestHttpClient) factory.getObject(); -// -// elasticSearchController.doSearch("{\"data\":\"1\",\"size\":\"1\"}"); -// } - + @Test(expected = Exception.class) + public void doSearchTest() throws IOException { + String task = "{ \"data\" : \"Data\" , \"size\" : \"Size\" , \"fuzzy\" : \"Fuzzy\", \"resultname\" : \"Result Name\" }"; + elasticSearchController.doSearch(task); + } + @Test - public void sendResultTest() - { + public void sendResultTest() { ResponseEntity<Result> result = elasticSearchController.sendResult(null); assertEquals(result.getStatusCode(), HttpStatus.OK); } - + @Test - public void isRestFultest() - { + public void isRestFultest() { assertTrue(elasticSearchController.isRESTfulCall()); } } diff --git a/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/AdminControllerTest.java b/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/AdminControllerTest.java new file mode 100644 index 00000000..2b3b55a2 --- /dev/null +++ b/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/AdminControllerTest.java @@ -0,0 +1,63 @@ +/* + * + * ============LICENSE_START========================================== + * ONAP Portal SDK + * =================================================================== + * Copyright © 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.controller.core; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.portalapp.controller.core.AdminController.AngularSinglePageController; +import org.springframework.web.servlet.ModelAndView; + +public class AdminControllerTest { + + @Test + public void viewTest(){ + AdminController adminController = new AdminController(); + AngularSinglePageController angularController = adminController.new AngularSinglePageController(); + ModelAndView modelAndView = angularController.view(); + Assert.assertNotNull(modelAndView); + } + + @Test + public void adminViewTest(){ + AdminController adminController = new AdminController(); + AngularSinglePageController angularController = adminController.new AngularSinglePageController(); + ModelAndView modelAndView = angularController.adminView(); + Assert.assertNotNull(modelAndView); + } +} diff --git a/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/CacheAdminControllerTest.java b/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/CacheAdminControllerTest.java new file mode 100644 index 00000000..f547a0e7 --- /dev/null +++ b/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/CacheAdminControllerTest.java @@ -0,0 +1,54 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal SDK + * =================================================================== + * Copyright © 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.controller.core; + +import org.junit.Test; +import org.mockito.InjectMocks; +import org.springframework.web.servlet.ModelAndView; + +public class CacheAdminControllerTest { + + @InjectMocks + CacheAdminController cacheAdminController; + + @Test + public void cacheAdminTest(){ + // ModelAndView expectedModelAndView = cacheAdminController.cacheAdmin(); + // System.out.println(expectedModelAndView); + } +} diff --git a/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/FavoritesControllerTest.java b/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/FavoritesControllerTest.java new file mode 100644 index 00000000..f1bb40e2 --- /dev/null +++ b/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/FavoritesControllerTest.java @@ -0,0 +1,175 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal SDK + * =================================================================== + * Copyright © 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.controller.core; + +import java.io.PrintWriter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.portalsdk.core.domain.App; +import org.onap.portalsdk.core.domain.User; +import org.onap.portalsdk.core.onboarding.rest.FavoritesClient; +import org.onap.portalsdk.core.onboarding.util.CipherUtil; +import org.onap.portalsdk.core.service.AppService; +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({SystemProperties.class, CipherUtil.class, FavoritesClient.class}) +public class FavoritesControllerTest { + + @InjectMocks + private FavoritesController favoritesController; + + @Mock + private AppService appService; + + @Test + public void getFavoritesExceptionTest() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + HttpSession session = Mockito.mock(HttpSession.class); + Mockito.when(request.getSession()).thenReturn(session); + PowerMockito.mockStatic(SystemProperties.class); + Mockito.when(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)).thenReturn(null); + + favoritesController.getFavorites(request, response); + Assert.assertTrue(true); + } + + @Test + public void getFavoritesTest() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + HttpSession session = Mockito.mock(HttpSession.class); + Mockito.when(request.getSession()).thenReturn(session); + PowerMockito.mockStatic(SystemProperties.class); + User user = new User(); + user.setId(123L); + Mockito.when(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)).thenReturn("user"); + Mockito.when(session.getAttribute("user")).thenReturn(user); + + App app = new App(); + app.setName("App"); + app.setUsername("User"); + app.setAppPassword("Password"); + Mockito.when(appService.getDefaultApp()).thenReturn(app); + + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(SystemProperties.getProperty(SystemProperties.Decryption_Key)).thenReturn(app.getAppPassword()); + Mockito.when(CipherUtil.decryptPKC(app.getAppPassword(), app.getAppPassword())).thenReturn(app.getAppPassword()); + + PowerMockito.mockStatic(FavoritesClient.class); + Mockito.when(FavoritesClient.getFavorites(Mockito.anyString(), Mockito.anyString(), + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn("Response"); + PrintWriter writer = Mockito.mock(PrintWriter.class); + Mockito.when(response.getWriter()).thenReturn(writer); + favoritesController.getFavorites(request, response); + Assert.assertTrue(true); + } + + @Test + public void getFavoritesCipherExceptionTest() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + HttpSession session = Mockito.mock(HttpSession.class); + Mockito.when(request.getSession()).thenReturn(session); + PowerMockito.mockStatic(SystemProperties.class); + User user = new User(); + user.setId(123L); + Mockito.when(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)).thenReturn("user"); + Mockito.when(session.getAttribute("user")).thenReturn(user); + + App app = new App(); + app.setName("App"); + app.setUsername("User"); + app.setAppPassword("Password"); + Mockito.when(appService.getDefaultApp()).thenReturn(app); + + Mockito.when(SystemProperties.getProperty(SystemProperties.Decryption_Key)).thenReturn(app.getAppPassword()); + + PowerMockito.mockStatic(FavoritesClient.class); + Mockito.when(FavoritesClient.getFavorites(Mockito.anyString(), Mockito.anyString(), + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn("Response"); + PrintWriter writer = Mockito.mock(PrintWriter.class); + Mockito.when(response.getWriter()).thenReturn(writer); + favoritesController.getFavorites(request, response); + Assert.assertTrue(true); + } + + @Test + public void getFavoritesWithAppNullTest() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + HttpSession session = Mockito.mock(HttpSession.class); + Mockito.when(request.getSession()).thenReturn(session); + PowerMockito.mockStatic(SystemProperties.class); + User user = new User(); + user.setId(123L); + Mockito.when(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)).thenReturn("user"); + Mockito.when(session.getAttribute("user")).thenReturn(user); + + App app = new App(); + app.setName("App"); + app.setUsername("User"); + app.setAppPassword("Password"); + Mockito.when(appService.getDefaultApp()).thenReturn(null); + + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(SystemProperties.getProperty(SystemProperties.Decryption_Key)).thenReturn(app.getAppPassword()); + Mockito.when(CipherUtil.decryptPKC(app.getAppPassword(), app.getAppPassword())).thenReturn(app.getAppPassword()); + + PowerMockito.mockStatic(FavoritesClient.class); + Mockito.when(FavoritesClient.getFavorites(Mockito.anyString(), Mockito.anyString(), + Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn("Response"); + PrintWriter writer = Mockito.mock(PrintWriter.class); + Mockito.when(response.getWriter()).thenReturn(writer); + favoritesController.getFavorites(request, response); + Assert.assertTrue(true); + } +} diff --git a/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/FnMenuControllerTest.java b/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/FnMenuControllerTest.java index 1f1d2db3..d82e1ed5 100644 --- a/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/FnMenuControllerTest.java +++ b/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/FnMenuControllerTest.java @@ -48,12 +48,16 @@ import java.io.StringReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; +import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import org.junit.Assert; 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; @@ -63,12 +67,21 @@ import org.onap.portalsdk.core.domain.Menu; import org.onap.portalsdk.core.domain.MenuData; import org.onap.portalsdk.core.domain.RoleFunction; import org.onap.portalsdk.core.domain.User; +import org.onap.portalsdk.core.menu.MenuBuilder; +import org.onap.portalsdk.core.service.AppService; +import org.onap.portalsdk.core.service.DataAccessService; import org.onap.portalsdk.core.service.FnMenuService; import org.onap.portalsdk.core.service.FunctionalMenuListService; import org.onap.portalsdk.core.web.support.UserUtils; +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 com.fasterxml.jackson.databind.ObjectMapper; +@RunWith(PowerMockRunner.class) +@PrepareForTest({UserUtils.class}) public class FnMenuControllerTest { @InjectMocks @@ -79,6 +92,15 @@ public class FnMenuControllerTest { @Mock FunctionalMenuListService functionalMenuListService; + + @Mock + private MenuBuilder menuBuilder; + + @Mock + private DataAccessService dataAccessService; + + @Mock + private AppService appService; @Before public void setup() { @@ -226,4 +248,15 @@ public class FnMenuControllerTest { String actualResult = fnMenuController.getViewName(); assertEquals(expectedResult, actualResult); } + + @Test + public void getMenuTest() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + PowerMockito.mockStatic(UserUtils.class); + HttpSession session = Mockito.mock(HttpSession.class); + Mockito.when(request.getSession()).thenReturn(session); + Mockito.when(UserUtils.getUserSession(request)).thenReturn(new User()); + Map<String, Object> model = fnMenuController.getMenu(request); + Assert.assertTrue(model.size() > 0 ); + } } diff --git a/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/ManifestControllerTest.java b/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/ManifestControllerTest.java new file mode 100644 index 00000000..04184983 --- /dev/null +++ b/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/ManifestControllerTest.java @@ -0,0 +1,76 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal SDK + * =================================================================== + * Copyright © 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.controller.core; + +import java.io.InputStream; +import java.util.Map; + +import javax.servlet.ServletContext; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +public class ManifestControllerTest { + + @InjectMocks + private ManifestController manifestController; + + @Mock + private ServletContext context; + + @Test + public void getManifestTest(){ + InputStream inputStream = Mockito.mock(InputStream.class); + Mockito.when(context.getResourceAsStream(Mockito.anyString())).thenReturn(inputStream); + Map<Object, Object> response = manifestController.getManifest(); + Assert.assertNotNull(response); + + } + + @Test + public void getManifestExceptionTest(){ + Map<Object, Object> response = manifestController.getManifest(); + Assert.assertNotNull(response); + } +} diff --git a/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/PostSearchControllerTest.java b/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/PostSearchControllerTest.java new file mode 100644 index 00000000..1f0e5524 --- /dev/null +++ b/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/PostSearchControllerTest.java @@ -0,0 +1,156 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal SDK + * =================================================================== + * Copyright © 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.controller.core; + +import java.io.BufferedReader; +import java.io.PrintWriter; +import java.io.Reader; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.portalsdk.core.command.PostSearchBean; +import org.onap.portalsdk.core.command.support.SearchResult; +import org.onap.portalsdk.core.domain.Profile; +import org.onap.portalsdk.core.domain.User; +import org.onap.portalsdk.core.service.LdapService; +import org.onap.portalsdk.core.service.PostSearchService; +import org.onap.portalsdk.core.service.ProfileService; +import org.onap.portalsdk.core.web.support.UserUtils; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.web.servlet.ModelAndView; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({UserUtils.class}) +public class PostSearchControllerTest { + + @InjectMocks + private PostSearchController postSearchController; + + @Mock + private PostSearchService postSearchService; + + @Mock + private LdapService ldapService; + + @Mock + private ProfileService profileService; + + @Test + public void welcomeTest() throws Exception { + PostSearchBean postSearchBean = new PostSearchBean(); + Profile profile = new Profile(); + profile.setId(123L); + profile.setOrgUserId("123"); + List<Profile> list = new ArrayList<>(); + list.add(profile); + Mockito.when(profileService.findAll()).thenReturn(list); + + ModelAndView modelAndView = postSearchController.welcome(postSearchBean); + Assert.assertNotNull(modelAndView); + } + + @Test + public void getPostSearchProfileTest() throws Exception { + HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + PostSearchBean postSearchBean = new PostSearchBean(); + + PrintWriter writer = Mockito.mock(PrintWriter.class); + Mockito.when(response.getWriter()).thenReturn(writer); + postSearchController.getPostSearchProfile(response, postSearchBean); + Assert.assertTrue(true); + } + + @Test + public void getPostSearchProfileExceptionTest() throws Exception { + HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + PostSearchBean postSearchBean = new PostSearchBean(); + + postSearchController.getPostSearchProfile(response, postSearchBean); + Assert.assertTrue(true); + } + + @Test + public void searchTest() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + + String json = " { \"postSearchBean\": { \"selected\": [\"test\" ] }}"; + Reader inputString = new StringReader(json); + BufferedReader buffer = new BufferedReader(inputString); + + Mockito.when(request.getReader()).thenReturn(buffer); + + PowerMockito.mockStatic(UserUtils.class); + User user = new User(); + user.setId(123L); + Mockito.when(UserUtils.getUserSession(request)).thenReturn(user); + + Mockito.when(ldapService.searchPost(Mockito.any(), Mockito.anyString(), Mockito.anyString(), + Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt(), Mockito.anyInt())).thenReturn(new SearchResult()); + postSearchController.search(request, response); + Assert.assertTrue(true); + } + + @Test + public void processExceptionTest() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + + String json = " { \"postSearchBean\": { \"selected\": [\"test\" ] }}"; + Reader inputString = new StringReader(json); + BufferedReader buffer = new BufferedReader(inputString); + + Mockito.when(request.getReader()).thenReturn(buffer); + PrintWriter out = Mockito.mock(PrintWriter.class); + Mockito.when(response.getWriter()).thenReturn(out); + postSearchController.process(request, response); + Assert.assertTrue(true); + } +} diff --git a/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/ProfileControllerTest.java b/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/ProfileControllerTest.java index 41367a16..b0cbb7e3 100644 --- a/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/ProfileControllerTest.java +++ b/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/ProfileControllerTest.java @@ -34,14 +34,16 @@ * ============LICENSE_END============================================ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. -*/ +*/ package org.onap.portalapp.controller.core; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; +import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; +import java.io.StringReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; @@ -71,43 +73,43 @@ import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.web.servlet.ModelAndView; @RunWith(PowerMockRunner.class) -@PrepareForTest({ SystemProperties.class, AppUtils.class ,UserUtils.class}) +@PrepareForTest({ SystemProperties.class, AppUtils.class, UserUtils.class }) public class ProfileControllerTest { @InjectMocks ProfileController profileController = new ProfileController(); - + @Mock UserProfileService service; - + @Mock UserService userService; - + @Mock RoleService roleService; - + @Mock private SharedContextRestClient sharedContextRestClient; - + @Before public void setup() { MockitoAnnotations.initMocks(this); } - + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); - + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); - + NullPointerException nullPointerException = new NullPointerException(); - + User user = new User(); - + @Mock UserUtils userUtils = new UserUtils(); - + @Test - public void profileTest() throws IOException{ + public void profileTest() throws IOException { ModelAndView actualModelAndView = new ModelAndView("profile"); User user = new User(); user.setOrgUserId("test"); @@ -117,90 +119,95 @@ public class ProfileControllerTest { Mockito.when(mockedRequest.getRequestURI()).thenReturn("self_profile.htm"); Mockito.when(mockedRequest.getParameter("profile_id")).thenReturn("test"); Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); - Mockito.when(AppUtils.getLookupList("FN_LU_STATE", "STATE_CD", "STATE", null, "STATE_CD")).thenReturn(new ArrayList<>()); + Mockito.when(AppUtils.getLookupList("FN_LU_STATE", "STATE_CD", "STATE", null, "STATE_CD")) + .thenReturn(new ArrayList<>()); Mockito.when(userService.getUser(String.valueOf(profileId))).thenReturn(user); - ModelAndView expectedModelAndView = profileController.profile(mockedRequest); + ModelAndView expectedModelAndView = profileController.profile(mockedRequest); assertEquals(actualModelAndView.getViewName(), expectedModelAndView.getViewName()); } - + @Test - public void profileRequestURITest() throws IOException{ + public void profileRequestURITest() throws IOException { ModelAndView actualModelAndView = new ModelAndView("profile"); User user = new User(); user.setOrgUserId("test"); - int profileId = 1; + int profileId = 1; PowerMockito.mockStatic(AppUtils.class); PowerMockito.mockStatic(UserUtils.class); Mockito.when(mockedRequest.getRequestURI()).thenReturn("test"); Mockito.when(mockedRequest.getParameter("profile_id")).thenReturn("1"); Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); - Mockito.when(userService.getUser(String.valueOf(profileId))).thenReturn(user); - Mockito.when(AppUtils.getLookupList("FN_LU_STATE", "STATE_CD", "STATE", null, "STATE_CD")).thenReturn(new ArrayList<>()); Mockito.when(userService.getUser(String.valueOf(profileId))).thenReturn(user); - ModelAndView expectedModelAndView = profileController.profile(mockedRequest); + Mockito.when(AppUtils.getLookupList("FN_LU_STATE", "STATE_CD", "STATE", null, "STATE_CD")) + .thenReturn(new ArrayList<>()); + Mockito.when(userService.getUser(String.valueOf(profileId))).thenReturn(user); + ModelAndView expectedModelAndView = profileController.profile(mockedRequest); assertEquals(actualModelAndView.getViewName(), expectedModelAndView.getViewName()); } - + @Test - public void profileExceptionTest() throws IOException{ + public void profileExceptionTest() throws IOException { ModelAndView actualModelAndView = new ModelAndView("profile"); User profile = null; - Long profileId = null; + Long profileId = null; Mockito.when(mockedRequest.getRequestURI()).thenReturn("self_profile.htm"); Mockito.when(mockedRequest.getParameter("profile_id")).thenReturn("test"); Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); Mockito.when(userService.getUser(String.valueOf(profileId))).thenReturn(profile); - ModelAndView expectedModelAndView = profileController.profile(mockedRequest); + ModelAndView expectedModelAndView = profileController.profile(mockedRequest); assertEquals(actualModelAndView.getViewName(), expectedModelAndView.getViewName()); } - + @Test - public void selfProfileTest() throws Exception{ + public void selfProfileTest() throws Exception { ModelAndView actualModelAndView = new ModelAndView("profile"); PowerMockito.mockStatic(AppUtils.class); PowerMockito.mockStatic(UserUtils.class); - Mockito.when(AppUtils.getLookupList("FN_LU_STATE", "STATE_CD", "STATE", null, "STATE_CD")).thenReturn(new ArrayList<>()); + Mockito.when(AppUtils.getLookupList("FN_LU_STATE", "STATE_CD", "STATE", null, "STATE_CD")) + .thenReturn(new ArrayList<>()); Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); ModelAndView expectedModelAndView = profileController.selfProfile(mockedRequest); assertEquals(actualModelAndView.getViewName(), expectedModelAndView.getViewName()); } - + @Test - public void selfProfileExceptionTest() throws Exception{ + public void selfProfileExceptionTest() throws Exception { Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); profileController.selfProfile(mockedRequest); } @SuppressWarnings("rawtypes") @Test - public void getStatesTest(){ + public void getStatesTest() { List actualList = new ArrayList(); PowerMockito.mockStatic(AppUtils.class); - Mockito.when(AppUtils.getLookupList("FN_LU_STATE", "STATE_CD", "STATE", null, "STATE_CD")).thenReturn(new ArrayList<>()); - List expectedlist =profileController.getStates(); + Mockito.when(AppUtils.getLookupList("FN_LU_STATE", "STATE_CD", "STATE", null, "STATE_CD")) + .thenReturn(new ArrayList<>()); + List expectedlist = profileController.getStates(); assertEquals(actualList.size(), expectedlist.size()); } - + @Test - public void getSelfProfileTest() throws IOException{ + public void getSelfProfileTest() throws IOException { PowerMockito.mockStatic(AppUtils.class); PowerMockito.mockStatic(UserUtils.class); Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); - Mockito.when(AppUtils.getLookupList("FN_LU_STATE", "STATE_CD", "STATE", null, "STATE_CD")).thenReturn(new ArrayList<>()); + Mockito.when(AppUtils.getLookupList("FN_LU_STATE", "STATE_CD", "STATE", null, "STATE_CD")) + .thenReturn(new ArrayList<>()); StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); Mockito.when(mockedResponse.getWriter()).thenReturn(writer); profileController.getSelfProfile(mockedRequest, mockedResponse); } - + @Test - public void getSelfProfileExceptionTest(){ + public void getSelfProfileExceptionTest() { Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); profileController.getSelfProfile(mockedRequest, mockedResponse); } - + @Test - public void getUserTest() throws IOException{ + public void getUserTest() throws IOException { User user = new User(); user.setOrgUserId("test"); Long profileId = null; @@ -209,99 +216,100 @@ public class ProfileControllerTest { Mockito.when(mockedRequest.getRequestURI()).thenReturn("self_profile.htm"); Mockito.when(mockedRequest.getParameter("profile_id")).thenReturn("test"); Mockito.when(UserUtils.getUserSession(mockedRequest)).thenReturn(user); - Mockito.when(AppUtils.getLookupList("FN_LU_STATE", "STATE_CD", "STATE", null, "STATE_CD")).thenReturn(new ArrayList<>()); + Mockito.when(AppUtils.getLookupList("FN_LU_STATE", "STATE_CD", "STATE", null, "STATE_CD")) + .thenReturn(new ArrayList<>()); Mockito.when(userService.getUser(String.valueOf(profileId))).thenReturn(user); StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); Mockito.when(mockedResponse.getWriter()).thenReturn(writer); profileController.getUser(mockedRequest, mockedResponse); } - + @Test - public void getUserExceptionTest(){ + public void getUserExceptionTest() { profileController.getUser(mockedRequest, mockedResponse); } - - /*@Test - public void saveProfileTest() throws IOException{ - String json = "{\"role\":{\"id\":1,\"created\":null,\"modified\":null,\"createdId\":null,\"modifiedId\":null,\"rowNum\":null,\"auditUserId\":null,\"auditTrail\":null,\"name\":\"test1\",\"active\":false,\"priority\":\"1\",\"roleFunctions\":[],\"childRoles\":[],\"editUrl\":\"/role.htm?role_id=1\",\"toggleActiveImage\":\"/static/fusion/images/inactive.png\",\"toggleActiveAltText\":\"Click to Activate Role\"},\"childRoles\":[],\"roleFunctions\":[]}"; + + @Test + public void saveProfileTest() throws IOException { + String json = "{ \"profile\": {\"firstName\": \"Test\" }, \"selectedCountry\" : \"USA\", \"selectedState\" : \"DC\", \"selectedTimeZone\" : \"12345678920\", \"role\":{\"id\":1,\"created\":null,\"modified\":null,\"createdId\":null,\"modifiedId\":null,\"rowNum\":null,\"auditUserId\":null,\"auditTrail\":null,\"name\":\"test1\",\"active\":false,\"priority\":\"1\",\"roleFunctions\":[],\"childRoles\":[],\"editUrl\":\"/role.htm?role_id=1\",\"toggleActiveImage\":\"/static/fusion/images/inactive.png\",\"toggleActiveAltText\":\"Click to Activate Role\"},\"childRoles\":[],\"roleFunctions\":[]}"; Mockito.when(mockedRequest.getReader()).thenReturn(new BufferedReader(new StringReader(json))); StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); Mockito.when(mockedResponse.getWriter()).thenReturn(writer); + Mockito.when(mockedRequest.getParameter("profile_id")).thenReturn("123"); + Mockito.when(userService.getUser(String.valueOf("123"))).thenReturn(new User()); assertNull(profileController.saveProfile(mockedRequest, mockedResponse)); - }*/ - + } + @Test - public void saveProfilePrintWriterExceptionTest() throws IOException{ + public void saveProfilePrintWriterExceptionTest() throws IOException { StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); Mockito.when(mockedResponse.getWriter()).thenReturn(writer); assertNull(profileController.saveProfile(mockedRequest, mockedResponse)); } - - /*@SuppressWarnings("unchecked") + @Test - public void saveProfileExceptionTest() throws IOException{ - StringWriter sw = new StringWriter(); - PrintWriter writer = new PrintWriter(sw); - Mockito.when(mockedResponse.getWriter()).thenThrow(IOException.class); - profileController.saveProfile(mockedRequest, mockedResponse); - }*/ - - /*@Test - public void removeRoleTest() throws IOException{ + public void removeRoleTest() throws IOException { + String json = "{ \"profile\": {\"firstName\": \"Test\" }, \"selectedCountry\" : \"USA\", \"selectedState\" : \"DC\", \"selectedTimeZone\" : \"12345678920\", \"role\":{\"id\":1,\"created\":null,\"modified\":null,\"createdId\":null,\"modifiedId\":null,\"rowNum\":null,\"auditUserId\":null,\"auditTrail\":null,\"name\":\"test1\",\"active\":false,\"priority\":\"1\",\"roleFunctions\":[],\"childRoles\":[],\"editUrl\":\"/role.htm?role_id=1\",\"toggleActiveImage\":\"/static/fusion/images/inactive.png\",\"toggleActiveAltText\":\"Click to Activate Role\"},\"childRoles\":[],\"roleFunctions\":[]}"; + Mockito.when(mockedRequest.getReader()).thenReturn(new BufferedReader(new StringReader(json))); StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); Mockito.when(mockedResponse.getWriter()).thenReturn(writer); - profileController.removeRole(mockedRequest, mockedResponse); - }*/ - + Mockito.when(mockedRequest.getParameter("profile_id")).thenReturn("123"); + Mockito.when(userService.getUser(String.valueOf("123"))).thenReturn(new User()); + PowerMockito.mockStatic(SystemProperties.class); + Mockito.when(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID)).thenReturn("123"); + assertNull(profileController.removeRole(mockedRequest, mockedResponse)); + } + @Test - public void removeRolePrintWriterExceptionTest() throws IOException{ + public void removeRolePrintWriterExceptionTest() throws IOException { StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); Mockito.when(mockedResponse.getWriter()).thenReturn(writer); profileController.removeRole(mockedRequest, mockedResponse); } - - /*@SuppressWarnings("unchecked") + @Test - public void removeRoleExceptionTest() throws IOException{ - StringWriter sw = new StringWriter(); - PrintWriter writer = new PrintWriter(sw); - Mockito.when(mockedResponse.getWriter()).thenThrow(IOException.class); - profileController.removeRole(mockedRequest, mockedResponse); - }*/ - - /*@Test - public void addNewRoleTest() throws IOException{ + public void addNewRoleTest() throws IOException { + + String json = "{ \"profile\": {\"firstName\": \"Test\" }, \"selectedCountry\" : \"USA\", \"selectedState\" : \"DC\", \"selectedTimeZone\" : \"12345678920\", \"role\":{\"id\":1,\"created\":null,\"modified\":null,\"createdId\":null,\"modifiedId\":null,\"rowNum\":null,\"auditUserId\":null,\"auditTrail\":null,\"name\":\"test1\",\"active\":false,\"priority\":\"1\",\"roleFunctions\":[],\"childRoles\":[],\"editUrl\":\"/role.htm?role_id=1\",\"toggleActiveImage\":\"/static/fusion/images/inactive.png\",\"toggleActiveAltText\":\"Click to Activate Role\"},\"childRoles\":[],\"roleFunctions\":[]}"; + Mockito.when(mockedRequest.getReader()).thenReturn(new BufferedReader(new StringReader(json))); + + Mockito.when(mockedRequest.getParameter("profile_id")).thenReturn("123"); + Mockito.when(userService.getUser(String.valueOf("123"))).thenReturn(new User()); + + PowerMockito.mockStatic(SystemProperties.class); + Mockito.when(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID)).thenReturn("123"); + StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); Mockito.when(mockedResponse.getWriter()).thenReturn(writer); - profileController.addNewRole(mockedRequest, mockedResponse); - }*/ - + assertNull(profileController.addNewRole(mockedRequest, mockedResponse)); + } + @Test - public void addNewRoleExceptionTest() throws IOException{ + public void addNewRoleExceptionTest() throws IOException { StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); Mockito.when(mockedResponse.getWriter()).thenReturn(writer); profileController.addNewRole(mockedRequest, mockedResponse); } - + @Test - public void getViewNameTest(){ + public void getViewNameTest() { String actualResult = null; profileController.setViewName(null); String expectedResult = profileController.getViewName(); assertEquals(actualResult, expectedResult); } - + @SuppressWarnings({ "rawtypes", "null", "unchecked" }) @Test - public void getAvailableRolesTest() throws IOException{ - List actualList = null; + public void getAvailableRolesTest() throws IOException { + List actualList = null; List list = null; Mockito.when(roleService.getAvailableRoles(null)).thenReturn(list); List expectedList = profileController.getAvailableRoles(null); diff --git a/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/UsageListControllerTest.java b/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/UsageListControllerTest.java index 98a23e8f..06ba0626 100644 --- a/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/UsageListControllerTest.java +++ b/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/UsageListControllerTest.java @@ -37,33 +37,195 @@ */ package org.onap.portalapp.controller.core; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; -import org.junit.Before; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.onap.portalapp.framework.MockitoTestSuite; +import org.mockito.Mockito; +import org.onap.portalsdk.core.command.UserRowBean; import org.onap.portalsdk.core.service.ProfileService; +import org.onap.portalsdk.core.util.UsageUtils; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.web.servlet.ModelAndView; +@RunWith(PowerMockRunner.class) +@PrepareForTest({UsageUtils.class}) public class UsageListControllerTest { @InjectMocks - UsageListController usageListController = new UsageListController(); - + private UsageListController usageListController; + @Mock - ProfileService service; + private ProfileService service; + + @Test + public void usageListTest() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + HttpSession httpSession = Mockito.mock(HttpSession.class); + Mockito.when(request.getSession()).thenReturn(httpSession); + ServletContext context = Mockito.mock(ServletContext.class); - @Before - public void setup() { - MockitoAnnotations.initMocks(this); + Mockito.when(httpSession.getServletContext()).thenReturn(context); + Mockito.when(httpSession.getId()).thenReturn("123"); + HashMap activeUsers = new HashMap(); + Mockito.when(context.getAttribute("activeUsers")).thenReturn(activeUsers); + List<UserRowBean> rows = new ArrayList<>() ; + UserRowBean bean = new UserRowBean(); + bean.setSessionId("123"); + UserRowBean bean2 = new UserRowBean(); + bean2.setSessionId("124"); + rows.add(bean); + rows.add(bean2); + PowerMockito.mockStatic(UsageUtils.class); + Mockito.when(UsageUtils.getActiveUsers(activeUsers)).thenReturn(rows); + ModelAndView view = usageListController.usageList(request); + Assert.assertNotNull(view); } + + @Test + public void usageListExceptionTest() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + HttpSession httpSession = Mockito.mock(HttpSession.class); + Mockito.when(request.getSession()).thenReturn(httpSession); + ServletContext context = Mockito.mock(ServletContext.class); - HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); - HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); - NullPointerException nullPointerException = new NullPointerException(); + Mockito.when(httpSession.getServletContext()).thenReturn(context); + HashMap activeUsers = new HashMap(); + Mockito.when(context.getAttribute("activeUsers")).thenReturn(activeUsers); + List<UserRowBean> rows = new ArrayList<>() ; + UserRowBean bean = new UserRowBean(); + bean.setSessionId("123"); + UserRowBean bean2 = new UserRowBean(); + bean2.setSessionId("124"); + rows.add(bean); + rows.add(bean2); + PowerMockito.mockStatic(UsageUtils.class); + Mockito.when(UsageUtils.getActiveUsers(activeUsers)).thenReturn(rows); + ModelAndView view = usageListController.usageList(request); + Assert.assertNotNull(view); + } + + @Test + public void getUsageListTest() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + PrintWriter mockWriter = Mockito.mock(PrintWriter.class); + Mockito.when(response.getWriter()).thenReturn(mockWriter); + + HttpSession httpSession = Mockito.mock(HttpSession.class); + Mockito.when(request.getSession()).thenReturn(httpSession); + ServletContext context = Mockito.mock(ServletContext.class); + + Mockito.when(httpSession.getServletContext()).thenReturn(context); + Mockito.when(httpSession.getId()).thenReturn("123"); + HashMap activeUsers = new HashMap(); + Mockito.when(context.getAttribute("activeUsers")).thenReturn(activeUsers); + List<UserRowBean> rows = new ArrayList<>() ; + UserRowBean bean = new UserRowBean(); + bean.setSessionId("123"); + UserRowBean bean2 = new UserRowBean(); + bean2.setSessionId("124"); + rows.add(bean); + rows.add(bean2); + PowerMockito.mockStatic(UsageUtils.class); + Mockito.when(UsageUtils.getActiveUsers(activeUsers)).thenReturn(rows); + usageListController.getUsageList(request, response); + Assert.assertTrue(true); + } + @Test + public void getUsageListExceptionTest() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + + HttpSession httpSession = Mockito.mock(HttpSession.class); + Mockito.when(request.getSession()).thenReturn(httpSession); + ServletContext context = Mockito.mock(ServletContext.class); + + Mockito.when(httpSession.getServletContext()).thenReturn(context); + HashMap activeUsers = new HashMap(); + Mockito.when(context.getAttribute("activeUsers")).thenReturn(activeUsers); + List<UserRowBean> rows = new ArrayList<>() ; + UserRowBean bean = new UserRowBean(); + bean.setSessionId("123"); + UserRowBean bean2 = new UserRowBean(); + bean2.setSessionId("124"); + rows.add(bean); + rows.add(bean2); + PowerMockito.mockStatic(UsageUtils.class); + Mockito.when(UsageUtils.getActiveUsers(activeUsers)).thenReturn(rows); + usageListController.getUsageList(request, response); + Assert.assertTrue(true); + } + + @Test + public void removeSessionTest() throws Exception { + + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + PrintWriter mockWriter = Mockito.mock(PrintWriter.class); + Mockito.when(response.getWriter()).thenReturn(mockWriter); + + HttpSession httpSession = Mockito.mock(HttpSession.class); + Mockito.when(request.getSession()).thenReturn(httpSession); + ServletContext context = Mockito.mock(ServletContext.class); + + Mockito.when(httpSession.getServletContext()).thenReturn(context); + Mockito.when(httpSession.getId()).thenReturn("123"); + HashMap activeUsers = new HashMap(); + Mockito.when(context.getAttribute("activeUsers")).thenReturn(activeUsers); + List<UserRowBean> rows = new ArrayList<>() ; + UserRowBean bean = new UserRowBean(); + bean.setSessionId("123"); + UserRowBean bean2 = new UserRowBean(); + bean2.setSessionId("124"); + rows.add(bean); + rows.add(bean2); + PowerMockito.mockStatic(UsageUtils.class); + Mockito.when(UsageUtils.getActiveUsers(activeUsers)).thenReturn(rows); + usageListController.removeSession(request, response); + Assert.assertTrue(true); + } + + @Test + public void removeSessionExceptionTest() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + PrintWriter mockWriter = Mockito.mock(PrintWriter.class); + Mockito.when(response.getWriter()).thenReturn(mockWriter); + + HttpSession httpSession = Mockito.mock(HttpSession.class); + Mockito.when(request.getSession()).thenReturn(httpSession); + ServletContext context = Mockito.mock(ServletContext.class); + + Mockito.when(httpSession.getServletContext()).thenReturn(context); + HashMap activeUsers = new HashMap(); + Mockito.when(context.getAttribute("activeUsers")).thenReturn(activeUsers); + List<UserRowBean> rows = new ArrayList<>() ; + UserRowBean bean = new UserRowBean(); + bean.setSessionId("123"); + UserRowBean bean2 = new UserRowBean(); + bean2.setSessionId("124"); + rows.add(bean); + rows.add(bean2); + PowerMockito.mockStatic(UsageUtils.class); + Mockito.when(UsageUtils.getActiveUsers(activeUsers)).thenReturn(rows); + usageListController.removeSession(request, response); + Assert.assertTrue(true); + } } diff --git a/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/scheduler/LogJobTest.java b/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/scheduler/LogJobTest.java new file mode 100644 index 00000000..1dbf1ec2 --- /dev/null +++ b/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/scheduler/LogJobTest.java @@ -0,0 +1,51 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal SDK + * =================================================================== + * Copyright © 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.scheduler; + +import org.junit.Assert; +import org.junit.Test; + +public class LogJobTest { + + @Test + public void executeInternalTest() throws Exception { + LogJob logJob = new LogJob(); + logJob.executeInternal(null); + Assert.assertTrue(true); + } +} diff --git a/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/scheduler/LogRegistryTest.java b/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/scheduler/LogRegistryTest.java new file mode 100644 index 00000000..5c8749df --- /dev/null +++ b/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/scheduler/LogRegistryTest.java @@ -0,0 +1,73 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal SDK + * =================================================================== + * Copyright © 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.scheduler; + +import java.text.ParseException; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +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.scheduling.quartz.JobDetailFactoryBean; + + +@RunWith(PowerMockRunner.class) +@PrepareForTest({SystemProperties.class}) +public class LogRegistryTest { + + @InjectMocks + private LogRegistry logRegistry; + + @Test + public void jobDetailFactoryBeanTest() { + JobDetailFactoryBean jobDetailFactoryBean = logRegistry.jobDetailFactoryBean(); + Assert.assertNotNull(jobDetailFactoryBean); + } + + @Test(expected =ParseException.class) + public void cronTriggerFactoryBeanTest() throws Exception { + PowerMockito.mockStatic(SystemProperties.class); + Mockito.when(SystemProperties.getProperty(SystemProperties.LOG_CRON)).thenReturn("*/5 * * * *"); + logRegistry.cronTriggerFactoryBean(); + } +} diff --git a/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/service/OnBoardingApiServiceImplTest.java b/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/service/OnBoardingApiServiceImplTest.java new file mode 100644 index 00000000..39b61b40 --- /dev/null +++ b/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/service/OnBoardingApiServiceImplTest.java @@ -0,0 +1,451 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal SDK + * =================================================================== + * Copyright © 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.service; + +import java.io.IOException; +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 org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.portalsdk.core.auth.LoginStrategy; +import org.onap.portalsdk.core.domain.App; +import org.onap.portalsdk.core.domain.Role; +import org.onap.portalsdk.core.domain.User; +import org.onap.portalsdk.core.domain.UserApp; +import org.onap.portalsdk.core.onboarding.client.AppContextManager; +import org.onap.portalsdk.core.onboarding.exception.CipherUtilException; +import org.onap.portalsdk.core.onboarding.exception.PortalAPIException; +import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler; +import org.onap.portalsdk.core.onboarding.util.CipherUtil; +import org.onap.portalsdk.core.onboarding.util.PortalApiConstants; +import org.onap.portalsdk.core.onboarding.util.PortalApiProperties; +import org.onap.portalsdk.core.restful.domain.EcompRole; +import org.onap.portalsdk.core.restful.domain.EcompUser; +import org.onap.portalsdk.core.service.AppService; +import org.onap.portalsdk.core.service.RestApiRequestBuilder; +import org.onap.portalsdk.core.service.RoleService; +import org.onap.portalsdk.core.service.UserProfileService; +import org.onap.portalsdk.core.service.UserService; +import org.onap.portalsdk.core.service.WebServiceCallService; +import org.onap.portalsdk.core.util.JSONUtil; +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.context.ApplicationContext; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ AppContextManager.class, PortalApiProperties.class, JSONUtil.class, PortalTimeoutHandler.class, SystemProperties.class, CipherUtil.class }) +public class OnBoardingApiServiceImplTest { + + @Mock + private RoleService roleService; + @Mock + private UserProfileService userProfileService; + @Mock + private IAdminAuthExtension adminAuthExtensionServiceImpl; + + @Mock + private LoginStrategy loginStrategy; + @Mock + private UserService userService; + @Mock + private RestApiRequestBuilder restApiRequestBuilder; + @Mock + private AppService appServiceImpl; + + @Before + public void setup() { + + PowerMockito.mockStatic(AppContextManager.class); + ApplicationContext appContext = Mockito.mock(ApplicationContext.class); + Mockito.when(AppContextManager.getAppContext()).thenReturn(appContext); + PowerMockito.mockStatic(PortalApiProperties.class); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED)).thenReturn("remote"); + Mockito.when(appContext.getBean(RoleService.class)).thenReturn(roleService); + Mockito.when(appContext.getBean(UserProfileService.class)).thenReturn(userProfileService); + Mockito.when(appContext.getBean(LoginStrategy.class)).thenReturn(loginStrategy); + Mockito.when(appContext.getBean(IAdminAuthExtension.class)).thenReturn(adminAuthExtensionServiceImpl); + Mockito.when(appContext.getBean(UserService.class)).thenReturn(userService); + Mockito.when(appContext.getBean(RestApiRequestBuilder.class)).thenReturn(restApiRequestBuilder); + Mockito.when(appContext.getBean(AppService.class)).thenReturn(appServiceImpl); + + } + + @Test + public void pushUserTest() throws PortalAPIException { + PowerMockito.mockStatic(PortalApiProperties.class); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED)).thenReturn("remote"); + OnBoardingApiServiceImpl onBoardingApiServiceImpl = new OnBoardingApiServiceImpl(); + EcompUser userJson = new EcompUser(); + onBoardingApiServiceImpl.pushUser(userJson); + Assert.assertTrue(true); + } + + @Test(expected = PortalAPIException.class) + public void pushUserExceptionTest() throws Exception { + PowerMockito.mockStatic(PortalApiProperties.class); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED)).thenReturn("remote"); + OnBoardingApiServiceImpl onBoardingApiServiceImpl = new OnBoardingApiServiceImpl(); + EcompUser userJson = new EcompUser(); + PowerMockito.mockStatic(JSONUtil.class); + Mockito.when(JSONUtil.convertResponseToJSON(Mockito.anyString())).thenThrow(Exception.class); + onBoardingApiServiceImpl.pushUser(userJson); + } + + @Test + public void editUserTest() throws Exception { + PowerMockito.mockStatic(PortalApiProperties.class); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED)).thenReturn("remote"); + String loginId = "123"; + Mockito.when(userProfileService.getUserByLoginId(loginId)).thenReturn(new User()); + OnBoardingApiServiceImpl onBoardingApiServiceImpl = new OnBoardingApiServiceImpl(); + EcompUser userJson = new EcompUser(); + userJson.setOrgUserId(loginId); + onBoardingApiServiceImpl.editUser(loginId, userJson); + Assert.assertTrue(true); + } + + @Test(expected = PortalAPIException.class) + public void editUserExceptionTest() throws Exception { + PowerMockito.mockStatic(PortalApiProperties.class); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED)).thenReturn("remote"); + String loginId = "123"; + PowerMockito.mockStatic(JSONUtil.class); + Mockito.when(JSONUtil.convertResponseToJSON(Mockito.anyString())).thenThrow(Exception.class); + OnBoardingApiServiceImpl onBoardingApiServiceImpl = new OnBoardingApiServiceImpl(); + EcompUser userJson = new EcompUser(); + userJson.setOrgUserId(loginId); + onBoardingApiServiceImpl.editUser(loginId, userJson); + } + + @Test + public void getUserTest() throws Exception { + String loginId = "123"; + PowerMockito.mockStatic(PortalApiProperties.class); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED)).thenReturn("remote"); + + String responseString = "Response"; + Mockito.when(restApiRequestBuilder.getViaREST("/user/" + loginId, true, loginId)).thenReturn(responseString); + Mockito.when(userService.userMapper(responseString)).thenReturn(new User()); + + OnBoardingApiServiceImpl onBoardingApiServiceImpl = new OnBoardingApiServiceImpl(); + onBoardingApiServiceImpl.getUser(loginId); + Assert.assertTrue(true); + } + + @Test + public void getUserAsNullUsserTest() throws Exception { + String loginId = "123"; + PowerMockito.mockStatic(PortalApiProperties.class); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED)).thenReturn("local"); + String responseString = "Response"; + Mockito.when(restApiRequestBuilder.getViaREST("/user/" + loginId, true, loginId)).thenReturn(responseString); + Mockito.when(userService.userMapper(responseString)).thenReturn(null); + + OnBoardingApiServiceImpl onBoardingApiServiceImpl = new OnBoardingApiServiceImpl(); + onBoardingApiServiceImpl.getUser(loginId); + Assert.assertTrue(true); + } + + @Test + public void getUserExceptionTest() throws Exception { + String loginId = "123"; + PowerMockito.mockStatic(PortalApiProperties.class); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED)).thenReturn("local"); + String responseString = "Response"; + Mockito.when(restApiRequestBuilder.getViaREST("/user/" + loginId, true, loginId)).thenThrow(IOException.class); + Mockito.when(userService.userMapper(responseString)).thenReturn(null); + + OnBoardingApiServiceImpl onBoardingApiServiceImpl = new OnBoardingApiServiceImpl(); + onBoardingApiServiceImpl.getUser(loginId); + Assert.assertTrue(true); + } + + @Test + public void getUsersTest() throws Exception { + PowerMockito.mockStatic(PortalApiProperties.class); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED)).thenReturn("local"); + OnBoardingApiServiceImpl onBoardingApiServiceImpl = new OnBoardingApiServiceImpl(); + + String responseString = "[ {\"firstName\":\"Name\"}]"; + Mockito.when(restApiRequestBuilder.getViaREST("/users", true, null)).thenReturn(responseString); + List<EcompUser> users = onBoardingApiServiceImpl.getUsers(); + Assert.assertNotNull(users); + } + + @Test(expected = PortalAPIException.class) + public void getUsersExceptionTest() throws Exception { + PowerMockito.mockStatic(PortalApiProperties.class); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED)).thenReturn("local"); + OnBoardingApiServiceImpl onBoardingApiServiceImpl = new OnBoardingApiServiceImpl(); + + String responseString = " { [ {\"firstName\":\"Name\"} ] }"; + Mockito.when(restApiRequestBuilder.getViaREST("/users", true, null)).thenReturn(responseString); + onBoardingApiServiceImpl.getUsers(); + } + + @Test + public void getAvailableRolesTest() throws Exception { + String requestedLoginId = "123"; + Role role1 = new Role(); + role1.setId(123L); + Role role2 = new Role(); + role2.setId(124L); + List<Role> roles = new ArrayList<>(); + roles.add(role1); + Mockito.when(roleService.getActiveRoles(requestedLoginId)).thenReturn(roles); + OnBoardingApiServiceImpl onBoardingApiServiceImpl = new OnBoardingApiServiceImpl(); + List<EcompRole> ecompRoles = onBoardingApiServiceImpl.getAvailableRoles(requestedLoginId); + Assert.assertNotNull(ecompRoles); + } + + @Test(expected = PortalAPIException.class) + public void getAvailableRolesExceptionTest() throws Exception { + String requestedLoginId = "123"; + Role role1 = new Role(); + role1.setId(123L); + Role role2 = new Role(); + role2.setId(124L); + List<Role> roles = new ArrayList<>(); + roles.add(role1); + roles.add(null); + Mockito.when(roleService.getActiveRoles(requestedLoginId)).thenReturn(roles); + OnBoardingApiServiceImpl onBoardingApiServiceImpl = new OnBoardingApiServiceImpl(); + onBoardingApiServiceImpl.getAvailableRoles(requestedLoginId); + } + + @Test + public void pushUserRoleTest() throws Exception { + String loginId = "123"; + List<EcompRole> rolesJson = new ArrayList<>(); + EcompRole role1 = new EcompRole(); + role1.setId(123L); + rolesJson.add(role1); + Set<UserApp> userApps = new TreeSet<>(); + + UserApp userApp = new UserApp(); + Role role = new Role(); + role.setId(123L); + userApp.setRole(role); + + UserApp userApp2 = new UserApp(); + Role role2 = new Role(); + role2.setId(124L); + userApp2.setRole(role2); + + userApps.add(userApp); + userApps.add(userApp2); + User user = new User(); + user.setUserApps(userApps); + Mockito.when(userProfileService.getUserByLoginId(loginId)).thenReturn(user); + + Mockito.when(roleService.getRole(loginId, role1.getId())).thenReturn(role); + OnBoardingApiServiceImpl onBoardingApiServiceImpl = new OnBoardingApiServiceImpl(); + onBoardingApiServiceImpl.pushUserRole(loginId, rolesJson); + Assert.assertTrue(true); + } + + @Test(expected = PortalAPIException.class) + public void pushUserRoleExceptionTest() throws Exception { + String loginId = "123"; + List<EcompRole> rolesJson = new ArrayList<>(); + EcompRole role1 = new EcompRole(); + role1.setId(123L); + rolesJson.add(role1); + Set<UserApp> userApps = new TreeSet<>(); + + UserApp userApp = new UserApp(); + Role role = new Role(); + role.setId(123L); + + userApps.add(userApp); + User user = new User(); + user.setUserApps(userApps); + Mockito.when(userProfileService.getUserByLoginId(loginId)).thenReturn(user); + + Mockito.when(roleService.getRole(loginId, role1.getId())).thenReturn(role); + OnBoardingApiServiceImpl onBoardingApiServiceImpl = new OnBoardingApiServiceImpl(); + onBoardingApiServiceImpl.pushUserRole(loginId, rolesJson); + } + + @Test + public void getUserRolesTest() throws Exception { + String loginId = "123"; + String responseString = "Response"; + Mockito.when(restApiRequestBuilder.getViaREST("/user/" + loginId, true, loginId)).thenReturn(responseString); + User user = new User(); + SortedSet<Role> currentRoles = new TreeSet<>(); + Role role = new Role(); + role.setId(123L); + currentRoles.add(role); + user.setRoles(currentRoles); + Mockito.when(userService.userMapper(responseString)).thenReturn(user); + OnBoardingApiServiceImpl onBoardingApiServiceImpl = new OnBoardingApiServiceImpl(); + List<EcompRole> ecompRoles = onBoardingApiServiceImpl.getUserRoles(loginId); + Assert.assertNotNull(ecompRoles); + } + + @Test(expected = PortalAPIException.class) + public void getUserRolesExceptionTest() throws Exception { + String loginId = "123"; + Mockito.when(restApiRequestBuilder.getViaREST("/user/" + loginId, true, loginId)).thenThrow(IOException.class); + OnBoardingApiServiceImpl onBoardingApiServiceImpl = new OnBoardingApiServiceImpl(); + onBoardingApiServiceImpl.getUserRoles(loginId); + } + + @Test + public void isAppAuthenticatedTest() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String userName = "UserName"; + String password = "Password"; + Mockito.when(request.getHeader("username")).thenReturn(userName); + Mockito.when(request.getHeader("password")).thenReturn(password); + + ApplicationContext appContext = Mockito.mock(ApplicationContext.class); + Mockito.when(AppContextManager.getAppContext()).thenReturn(appContext); + WebServiceCallService webService = Mockito.mock(WebServiceCallService.class); + Mockito.when(appContext.getBean(WebServiceCallService.class)).thenReturn(webService); + Mockito.when(webService.verifyRESTCredential(null, userName, password)).thenReturn(true); + OnBoardingApiServiceImpl onBoardingApiServiceImpl = new OnBoardingApiServiceImpl(); + boolean status = onBoardingApiServiceImpl.isAppAuthenticated(request); + Assert.assertTrue(status); + } + + @Test(expected =PortalAPIException.class) + public void isAppAuthenticatedExceptionTest() throws Exception { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String userName = "UserName"; + String password = "Password"; + Mockito.when(request.getHeader("username")).thenReturn(userName); + Mockito.when(request.getHeader("password")).thenReturn(password); + + ApplicationContext appContext = Mockito.mock(ApplicationContext.class); + Mockito.when(AppContextManager.getAppContext()).thenReturn(appContext); + Mockito.when(appContext.getBean(WebServiceCallService.class)).thenReturn(null); + OnBoardingApiServiceImpl onBoardingApiServiceImpl = new OnBoardingApiServiceImpl(); + onBoardingApiServiceImpl.isAppAuthenticated(request); + } + + @Test + public void getSessionTimeOutsTEst() throws Exception { + String session ="Session"; + PowerMockito.mockStatic(PortalTimeoutHandler.class); + Mockito.when(PortalTimeoutHandler.gatherSessionExtensions()).thenReturn(session); + OnBoardingApiServiceImpl onBoardingApiServiceImpl = new OnBoardingApiServiceImpl(); + String response = onBoardingApiServiceImpl.getSessionTimeOuts(); + Assert.assertEquals(response, session); + } + + @Test + public void updateSessionTimeOutsTest() throws Exception { + String sessionMap ="Session"; + PowerMockito.mockStatic(PortalTimeoutHandler.class); + OnBoardingApiServiceImpl onBoardingApiServiceImpl = new OnBoardingApiServiceImpl(); + onBoardingApiServiceImpl.updateSessionTimeOuts(sessionMap); + Assert.assertTrue(true); + } + + @Test + public void getUserId() throws PortalAPIException { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String userId = "123"; + Mockito.when(loginStrategy.getUserId(request)).thenReturn(userId); + OnBoardingApiServiceImpl onBoardingApiServiceImpl = new OnBoardingApiServiceImpl(); + String response = onBoardingApiServiceImpl.getUserId(request); + Assert.assertEquals(response, userId); + } + + @Test + public void getAppCredentialsTest() throws Exception{ + App app =new App(); + app.setName("App"); + app.setUsername("User"); + app.setAppPassword("Password"); + + String key = "Key"; + + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(SystemProperties.getProperty(SystemProperties.Decryption_Key)).thenReturn(key); + Mockito.when(CipherUtil.decryptPKC(app.getAppPassword(), key)).thenReturn(app.getAppPassword()); + Mockito.when(appServiceImpl.getDefaultApp()).thenReturn(app); + OnBoardingApiServiceImpl onBoardingApiServiceImpl = new OnBoardingApiServiceImpl(); + Map<String, String> credentialsMap = onBoardingApiServiceImpl.getAppCredentials(); + Assert.assertNotNull(credentialsMap); + } + + @Test + public void getAppCredentialsAppNullTest() throws Exception{ + Mockito.when(appServiceImpl.getDefaultApp()).thenReturn(null); + OnBoardingApiServiceImpl onBoardingApiServiceImpl = new OnBoardingApiServiceImpl(); + Map<String, String> credentialsMap = onBoardingApiServiceImpl.getAppCredentials(); + Assert.assertNotNull(credentialsMap); + } + + @Test + public void getAppCredentialsExceptionTest() throws Exception{ + App app =new App(); + app.setName("App"); + app.setUsername("User"); + app.setAppPassword("Password"); + + String key = "Key"; + + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(SystemProperties.getProperty(SystemProperties.Decryption_Key)).thenReturn(key); + Mockito.when(CipherUtil.decryptPKC(app.getAppPassword(), key)).thenThrow(CipherUtilException.class); + Mockito.when(appServiceImpl.getDefaultApp()).thenReturn(app); + OnBoardingApiServiceImpl onBoardingApiServiceImpl = new OnBoardingApiServiceImpl(); + Map<String, String> credentialsMap = onBoardingApiServiceImpl.getAppCredentials(); + Assert.assertNotNull(credentialsMap); + } +} diff --git a/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/util/CustomLoggingFilterTest.java b/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/util/CustomLoggingFilterTest.java new file mode 100644 index 00000000..e959244b --- /dev/null +++ b/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/util/CustomLoggingFilterTest.java @@ -0,0 +1,81 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal SDK + * =================================================================== + * Copyright © 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.util; + +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.spi.FilterReply; + +public class CustomLoggingFilterTest { + + @Test + public void decideTest(){ + ILoggingEvent event = Mockito.mock(ILoggingEvent.class); + Mockito.when(event.getLevel()).thenReturn(Level.ERROR); + Mockito.when(event.getThreadName()).thenReturn("UEBConsumerThread"); + Mockito.when(event.getLoggerName()).thenReturn("org.onap.nsa"); + CustomLoggingFilter customLoggingFilter = new CustomLoggingFilter(); + FilterReply reply = customLoggingFilter.decide(event); + Assert.assertEquals( FilterReply.DENY, reply); + } + + @Test + public void decideNEUTRALTest(){ + ILoggingEvent event = Mockito.mock(ILoggingEvent.class); + Mockito.when(event.getLevel()).thenReturn(Level.ERROR); + Mockito.when(event.getThreadName()).thenReturn("UEBConsumerThread"); + Mockito.when(event.getLoggerName()).thenReturn("test"); + CustomLoggingFilter customLoggingFilter = new CustomLoggingFilter(); + FilterReply reply = customLoggingFilter.decide(event); + Assert.assertEquals( FilterReply.NEUTRAL, reply); + } + + @Test + public void decideExceptionTest(){ + ILoggingEvent event = Mockito.mock(ILoggingEvent.class); + Mockito.when(event.getLevel()).thenReturn(Level.ERROR); + Mockito.when(event.getThreadName()).thenReturn("UEBConsumerThread"); + CustomLoggingFilter customLoggingFilter = new CustomLoggingFilter(); + FilterReply reply = customLoggingFilter.decide(event); + Assert.assertEquals( FilterReply.NEUTRAL, reply); + } +} diff --git a/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/util/SecurityXssValidatorTest.java b/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/util/SecurityXssValidatorTest.java new file mode 100644 index 00000000..fa1af38c --- /dev/null +++ b/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/util/SecurityXssValidatorTest.java @@ -0,0 +1,110 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright © 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.util; + +import org.apache.commons.lang.StringUtils; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.onap.portalsdk.core.util.SystemProperties; +import org.owasp.esapi.ESAPI; +import org.owasp.esapi.Encoder; +import org.owasp.esapi.codecs.Codec; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ESAPI.class, SystemProperties.class}) +public class SecurityXssValidatorTest { + + @Test + public void stripXSSTest() { + String value ="Test"; + PowerMockito.mockStatic(ESAPI.class); + Encoder mockEncoder = Mockito.mock(Encoder.class); + Mockito.when(ESAPI.encoder()).thenReturn(mockEncoder); + Mockito.when(mockEncoder.canonicalize(value)).thenReturn(value); + SecurityXssValidator validator = SecurityXssValidator.getInstance(); + String reponse = validator.stripXSS(value); + Assert.assertEquals(value, reponse);; + } + + @Test + public void stripXSSExceptionTest() { + String value ="Test"; + SecurityXssValidator validator = SecurityXssValidator.getInstance(); + String reponse = validator.stripXSS(value); + Assert.assertEquals(value, reponse);; + } + + @Test + public void denyXSSTest() { + String value ="<script>Test</script>"; + PowerMockito.mockStatic(ESAPI.class); + Encoder mockEncoder = Mockito.mock(Encoder.class); + Mockito.when(ESAPI.encoder()).thenReturn(mockEncoder); + Mockito.when(mockEncoder.canonicalize(value)).thenReturn(value); + SecurityXssValidator validator = SecurityXssValidator.getInstance(); + Boolean flag = validator.denyXSS(value); + Assert.assertTrue(flag); + } + + @Test + public void denyXSSFalseTest() { + String value ="test"; + PowerMockito.mockStatic(ESAPI.class); + Encoder mockEncoder = Mockito.mock(Encoder.class); + Mockito.when(ESAPI.encoder()).thenReturn(mockEncoder); + Mockito.when(mockEncoder.canonicalize(value)).thenReturn(value); + SecurityXssValidator validator = SecurityXssValidator.getInstance(); + Boolean flag = validator.denyXSS(value); + Assert.assertFalse(flag); + } + + @Test + public void getCodecMySqlTest() { + PowerMockito.mockStatic(SystemProperties.class); + Mockito.when(SystemProperties.getProperty(SystemProperties.DB_DRIVER)).thenReturn("mysql"); + SecurityXssValidator validator = SecurityXssValidator.getInstance(); + Codec codec = validator.getCodec(); + Assert.assertNotNull(codec); + } + +} diff --git a/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalsdk/core/web/support/UserUtilsTest.java b/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalsdk/core/web/support/UserUtilsTest.java new file mode 100644 index 00000000..c5476210 --- /dev/null +++ b/ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalsdk/core/web/support/UserUtilsTest.java @@ -0,0 +1,283 @@ +/* + * ============LICENSE_START========================================== + * ONAP Portal SDK + * =================================================================== + * Copyright © 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.portalsdk.core.web.support; + +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.HashSet; +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.HttpSession; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.onap.portalsdk.core.domain.Role; +import org.onap.portalsdk.core.domain.RoleFunction; +import org.onap.portalsdk.core.domain.User; +import org.onap.portalsdk.core.exception.SessionExpiredException; +import org.onap.portalsdk.core.restful.domain.EcompUser; +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 com.google.common.collect.Iterators; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({AppUtils.class , SystemProperties.class}) +public class UserUtilsTest { + + @Test + public void setUserSessionTest() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + PowerMockito.mockStatic(AppUtils.class); + User user =new User(); + user.setFirstName("Fname"); + user.setLastName("LName"); + + Role role = new Role(); + role.setId(123L); + role.setActive(true); + + Role childRole = new Role(); + childRole.setId(124L); + childRole.setActive(true); + + SortedSet<Role> childRoles = new TreeSet<>(); + childRoles.add(childRole); + + RoleFunction function = new RoleFunction(); + function.setId(11L); + SortedSet<RoleFunction> roleFunctions = new TreeSet<>(); + roleFunctions.add(function); + role.setRoleFunctions(roleFunctions); + + SortedSet<Role> roles = new TreeSet<>(); + roles.add(role); + role.setChildRoles(childRoles); + user.setRoles(roles); + + Set applicationMenuData = new HashSet(); + Set businessDirectMenuData= new HashSet(); + String loginMethod = ""; + List<RoleFunction> roleFunctionList = new ArrayList<>(); + HttpSession session = Mockito.mock(HttpSession.class); + Mockito.when(request.getSession(true)).thenReturn(session); + Mockito.when(request.getSession()).thenReturn(session); + Mockito.when(AppUtils.getSession(request)).thenReturn(session); + PowerMockito.mockStatic(SystemProperties.class); + String roleFun = "RoleFunction"; + Mockito.when(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME)).thenReturn(roleFun); + Mockito.when(session.getAttribute(roleFun)).thenReturn(null); + String roleAttr = "RoleAttr"; + Mockito.when(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME)).thenReturn(roleAttr); + Mockito.when(session.getAttribute(roleAttr)).thenReturn(null); + String userValue = "user"; + Mockito.when(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)).thenReturn(userValue); + Mockito.when(session.getAttribute(userValue)).thenReturn(user); + + UserUtils.setUserSession(request, user, applicationMenuData, businessDirectMenuData, loginMethod, roleFunctionList); + Assert.assertTrue(true); + } + + @Test + public void hasRoleTest() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String roleKey = "123"; + Map roles = new HashMap(); + roles.put(123L, "Role"); + + PowerMockito.mockStatic(AppUtils.class); + HttpSession session = Mockito.mock(HttpSession.class); + Mockito.when(AppUtils.getSession(request)).thenReturn(session); + PowerMockito.mockStatic(SystemProperties.class); + Mockito.when(SystemProperties.getProperty(SystemProperties.ROLES_ATTRIBUTE_NAME)).thenReturn("Attr"); + Mockito.when(session.getAttribute(Mockito.anyString())).thenReturn(roles); + + boolean status = UserUtils.hasRole(request, roleKey); + Assert.assertTrue(status); + } + + @Test + public void hasRoleAllUserRolesTest() { + User user = new User(); + + Role role = new Role(); + role.setId(123L); + role.setActive(true); + + SortedSet<Role> roles = new TreeSet<>(); + roles.add(role); + user.setRoles(roles); + String roleKey = "123"; + boolean status = UserUtils.hasRole(user, roleKey); + Assert.assertTrue(status); + } + + @Test + public void isAccessibleTest() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + String functionKey ="123"; + HashSet roleFunctions = new HashSet(); + roleFunctions.add(functionKey); + + HttpSession session = Mockito.mock(HttpSession.class); + Mockito.when(request.getSession()).thenReturn(session); + PowerMockito.mockStatic(SystemProperties.class); + Mockito.when(SystemProperties.getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME)).thenReturn("Attr"); + Mockito.when(session.getAttribute(Mockito.anyString())).thenReturn(roleFunctions); + + boolean status = UserUtils.isAccessible(request, functionKey); + Assert.assertTrue(status); + } + + @Test(expected = SessionExpiredException.class) + public void getLoginMethodExceptionTest() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + UserUtils.getLoginMethod(request); + } + + @Test + public void getLoginMethodTest() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + PowerMockito.mockStatic(AppUtils.class); + HttpSession session = Mockito.mock(HttpSession.class); + Mockito.when(AppUtils.getSession(request)).thenReturn(session); + PowerMockito.mockStatic(SystemProperties.class); + String loginMethod ="loginMethod"; + Mockito.when(SystemProperties.getProperty(SystemProperties.LOGIN_METHOD_ATTRIBUTE_NAME)).thenReturn(loginMethod); + Mockito.when(session.getAttribute(loginMethod)).thenReturn(loginMethod); + String returnValue = UserUtils.getLoginMethod(request); + Assert.assertEquals(returnValue, loginMethod); + } + + @Test + public void getUserIdTest() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + PowerMockito.mockStatic(AppUtils.class); + HttpSession session = Mockito.mock(HttpSession.class); + Mockito.when(AppUtils.getSession(request)).thenReturn(session); + String userkey ="user"; + User user = new User(); + user.setId(123L); + PowerMockito.mockStatic(SystemProperties.class); + Mockito.when(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)).thenReturn(userkey); + Mockito.when(SystemProperties.getProperty(SystemProperties.APPLICATION_USER_ID)).thenReturn("123"); + Mockito.when(session.getAttribute(userkey)).thenReturn(user); + Long userId = UserUtils.getUserIdAsLong(request); + Assert.assertEquals(userId, user.getId()); + } + + @Test + public void getStackTraceTest(){ + String exceptionMsg = "Dummy Exception"; + Throwable throwable = new Throwable(exceptionMsg); + String response = UserUtils.getStackTrace(throwable); + Assert.assertTrue(response.contains(exceptionMsg)); + } + + @Test + public void getFullURLTest() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + StringBuffer requestURL = new StringBuffer("Test/URL"); + Mockito.when(request.getRequestURL()).thenReturn(requestURL); + String response = UserUtils.getFullURL(request); + Assert.assertEquals(requestURL.toString(), response); + } + + @Test + public void getFullURLQueryTest() { + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + StringBuffer requestURL = new StringBuffer("Test/URL"); + Mockito.when(request.getRequestURL()).thenReturn(requestURL); + Mockito.when(request.getQueryString()).thenReturn("Query"); + String response = UserUtils.getFullURL(request); + Assert.assertTrue(response.contains(requestURL.toString())); + } + + @Test + public void getFullURLNullTest() { + String response = UserUtils.getFullURL(null); + Assert.assertEquals(response, ""); + } + + @Test + public void getRequestIdTest() { + Set<String> elements = new HashSet<>(); + elements.add(SystemProperties.ECOMP_REQUEST_ID); + Enumeration<String> headerNames = Iterators.asEnumeration(elements.iterator()); + String reqId ="123"; + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + Mockito.when(request.getHeaderNames()).thenReturn(headerNames); + Mockito.when(request.getHeader(SystemProperties.ECOMP_REQUEST_ID)).thenReturn(reqId); + String response = UserUtils.getRequestId(request); + Assert.assertEquals(response, reqId); + } + + @Test + public void getRequestIdEmptyTest() { + Set<String> elements = new HashSet<>(); + Enumeration<String> headerNames = Iterators.asEnumeration(elements.iterator()); + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + Mockito.when(request.getHeaderNames()).thenReturn(headerNames); + String response = UserUtils.getRequestId(request); + Assert.assertNotNull(response); + } + + @Test + public void convertToEcompUserTest() { + User user = new User(); + Role role = new Role(); + role.setId(123L); + role.setName("Role"); + SortedSet roles = new TreeSet(); + roles.add(role); + user.setLoginId("123"); + user.setRoles(roles); + EcompUser ecompUser = UserUtils.convertToEcompUser(user); + Assert.assertNotNull(ecompUser); + } +} |