From 724ff8f8b22d6503ce5070ebc13f6f5fbc48c8cf Mon Sep 17 00:00:00 2001 From: st782s Date: Tue, 20 Feb 2018 12:00:10 -0500 Subject: Increase JUNIT Coverage Issue-ID: PORTAL-136 Change-Id: I2223003924f36043753bef401ed1d8ee87f4a65e Signed-off-by: st782s --- .../controller/ElasticSearchControllerTest.java | 68 ++-- .../controller/core/AdminControllerTest.java | 63 +++ .../controller/core/CacheAdminControllerTest.java | 54 +++ .../controller/core/FavoritesControllerTest.java | 175 ++++++++ .../controller/core/FnMenuControllerTest.java | 33 ++ .../controller/core/ManifestControllerTest.java | 76 ++++ .../controller/core/PostSearchControllerTest.java | 156 +++++++ .../controller/core/ProfileControllerTest.java | 180 ++++---- .../controller/core/UsageListControllerTest.java | 188 ++++++++- .../org/onap/portalapp/scheduler/LogJobTest.java | 51 +++ .../onap/portalapp/scheduler/LogRegistryTest.java | 73 ++++ .../service/OnBoardingApiServiceImplTest.java | 451 +++++++++++++++++++++ .../portalapp/util/CustomLoggingFilterTest.java | 81 ++++ .../portalapp/util/SecurityXssValidatorTest.java | 110 +++++ .../portalsdk/core/web/support/UserUtilsTest.java | 283 +++++++++++++ .../core/objectcache/jcs/JCSCacheEventHandler.java | 2 +- .../portalsdk/core/command/PostSearchBeanTest.java | 97 ++++- .../controller/RestrictedBaseControllerTest.java | 81 ++++ .../RestrictedRESTfulBaseControllerTest.java | 72 ++++ .../controller/UnRestrictedBaseControllerTest.java | 68 ++++ .../portalsdk/core/dao/ProfileDaoImplTest.java | 90 ++++ .../portalsdk/core/dao/support/FusionDaoTest.java | 63 +++ .../core/drools/DroolsRuleServiceImplTest.java | 79 ++++ .../exception/FusionExceptionResolverTest.java | 75 ++++ .../core/interceptor/ResourceInterceptorTest.java | 171 ++++++++ .../interceptor/SessionTimeoutInterceptorTest.java | 147 +++++++ .../CollaborateListBindingListenerTest.java | 74 ++++ .../core/listener/UserSessionListenerTest.java | 79 ++++ .../core/logging/aspect/EELFLoggerAdviceTest.java | 92 +++++ .../core/logging/aspect/EELFLoggerAspectTest.java | 162 ++++++++ .../core/logging/logic/EELFLoggerDelegateTest.java | 320 +++++++++++++++ .../onap/portalsdk/core/menu/MenuBuilderTest.java | 173 ++++++++ .../portalsdk/core/menu/MenuPropertiesTest.java | 74 ++++ .../objectcache/jcs/JCSCacheEventHandlerTest.java | 120 ++++++ .../restful/client/HttpStatusAndResponseTest.java | 62 +++ .../restful/client/PortalRestClientBaseTest.java | 209 ++++++++++ .../client/SharedContextRestClientTest.java | 307 ++++++++++++++ .../portalsdk/core/scheduler/CoreRegisterTest.java | 52 +++ .../core/service/AccessConfigurationTest.java | 95 +++++ .../core/service/CentralAccessConditionTest.java | 79 ++++ .../core/service/UserProfileServiceImplTest.java | 14 +- .../service/UserServiceCentalizedImplTest.java | 84 ++++ .../core/service/UserServiceImplTest.java | 68 ++++ .../service/WebServiceCallServiceImplTest.java | 127 ++++++ .../service/support/ServiceLocatorImplTest.java | 60 +++ .../org/onap/portalsdk/core/util/JSONUtilTest.java | 76 ++++ .../portalsdk/core/util/SecurityCodecUtilTest.java | 79 ++++ .../portalsdk/core/util/SystemPropertiesTest.java | 72 ++++ .../onap/portalsdk/core/util/UsageUtilsTest.java | 114 ++++++ .../core/web/socket/PeerBroadcastSocketTest.java | 82 ++++ .../core/web/socket/WebRTCSocketTest.java | 79 ++++ .../core/web/support/FeedbackMessageTest.java | 70 ++++ .../core/web/support/JsonMessageTest.java | 69 ++++ .../core/web/support/MessagesListTest.java | 73 ++++ .../crossapi/PortalRestAPIProxyTest.java | 43 ++ .../fw/test/PortalTimeoutHandlerTest.java | 3 +- .../onap/portalapp/framework/MockitoTestSuite.java | 89 ++++ .../controller/NotebookControllerTest.java | 66 +++ .../controller/NotebookTestControllerTest.java | 66 +++ .../controller/RNoteBookControllerTest.java | 100 +++++ .../controller/RNoteBookFEControllerTest.java | 187 +++++++++ .../domain/RNoteBookCredentialsTest.java | 85 ++++ .../RNoteBookIntegrationServiceImplTest.java | 141 +++++++ .../controllers/WorkflowControllerTest.java | 193 +++++++++ .../workflow/dao/WorkflowDAOImplTest.java | 168 ++++++++ .../workflow/domain/WorkflowScheduleTest.java | 87 ++++ .../workflow/models/WorkflowLiteTest.java | 110 +++++ .../portalsdk/workflow/models/WorkflowTest.java | 110 +++++ .../scheduler/WorkFlowScheduleJobTest.java | 63 +++ .../scheduler/WorkFlowScheduleRegistryTest.java | 99 +++++ .../services/WorkflowScheduleServiceImplTest.java | 115 ++++++ .../workflow/services/WorkflowServiceImplTest.java | 92 +++++ ecomp-sdk/pom.xml | 4 +- version.properties | 4 +- 74 files changed, 7627 insertions(+), 150 deletions(-) create mode 100644 ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/AdminControllerTest.java create mode 100644 ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/CacheAdminControllerTest.java create mode 100644 ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/FavoritesControllerTest.java create mode 100644 ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/ManifestControllerTest.java create mode 100644 ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/controller/core/PostSearchControllerTest.java create mode 100644 ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/scheduler/LogJobTest.java create mode 100644 ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/scheduler/LogRegistryTest.java create mode 100644 ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/service/OnBoardingApiServiceImplTest.java create mode 100644 ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/util/CustomLoggingFilterTest.java create mode 100644 ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalapp/util/SecurityXssValidatorTest.java create mode 100644 ecomp-sdk/epsdk-app-common/src/test/java/org/onap/portalsdk/core/web/support/UserUtilsTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/controller/RestrictedBaseControllerTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/controller/RestrictedRESTfulBaseControllerTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/controller/UnRestrictedBaseControllerTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/dao/ProfileDaoImplTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/dao/support/FusionDaoTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/drools/DroolsRuleServiceImplTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/exception/FusionExceptionResolverTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/interceptor/ResourceInterceptorTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/interceptor/SessionTimeoutInterceptorTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/listener/CollaborateListBindingListenerTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/listener/UserSessionListenerTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/logging/aspect/EELFLoggerAdviceTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/logging/aspect/EELFLoggerAspectTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/logging/logic/EELFLoggerDelegateTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/menu/MenuBuilderTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/menu/MenuPropertiesTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/objectcache/jcs/JCSCacheEventHandlerTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/restful/client/HttpStatusAndResponseTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/restful/client/PortalRestClientBaseTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/restful/client/SharedContextRestClientTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/scheduler/CoreRegisterTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/service/AccessConfigurationTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/service/CentralAccessConditionTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/service/UserServiceCentalizedImplTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/service/UserServiceImplTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/service/WebServiceCallServiceImplTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/service/support/ServiceLocatorImplTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/util/JSONUtilTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/util/SecurityCodecUtilTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/util/SystemPropertiesTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/util/UsageUtilsTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/web/socket/PeerBroadcastSocketTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/web/socket/WebRTCSocketTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/web/support/FeedbackMessageTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/web/support/JsonMessageTest.java create mode 100644 ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/web/support/MessagesListTest.java create mode 100644 ecomp-sdk/epsdk-fw/src/test/java/org/onap/portalsdk/core/onboarding/crossapi/PortalRestAPIProxyTest.java create mode 100644 ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalapp/framework/MockitoTestSuite.java create mode 100644 ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/rnotebookintegration/controller/NotebookControllerTest.java create mode 100644 ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/rnotebookintegration/controller/NotebookTestControllerTest.java create mode 100644 ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/rnotebookintegration/controller/RNoteBookControllerTest.java create mode 100644 ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/rnotebookintegration/controller/RNoteBookFEControllerTest.java create mode 100644 ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/rnotebookintegration/domain/RNoteBookCredentialsTest.java create mode 100644 ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/rnotebookintegration/service/RNoteBookIntegrationServiceImplTest.java create mode 100644 ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/controllers/WorkflowControllerTest.java create mode 100644 ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/dao/WorkflowDAOImplTest.java create mode 100644 ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/domain/WorkflowScheduleTest.java create mode 100644 ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/models/WorkflowLiteTest.java create mode 100644 ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/models/WorkflowTest.java create mode 100644 ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/scheduler/WorkFlowScheduleJobTest.java create mode 100644 ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/scheduler/WorkFlowScheduleRegistryTest.java create mode 100644 ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/services/WorkflowScheduleServiceImplTest.java create mode 100644 ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/services/WorkflowServiceImplTest.java 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 = 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 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 response = manifestController.getManifest(); + Assert.assertNotNull(response); + + } + + @Test + public void getManifestExceptionTest(){ + Map 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 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 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 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 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 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 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 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 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 roles = new ArrayList<>(); + roles.add(role1); + Mockito.when(roleService.getActiveRoles(requestedLoginId)).thenReturn(roles); + OnBoardingApiServiceImpl onBoardingApiServiceImpl = new OnBoardingApiServiceImpl(); + List 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 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 rolesJson = new ArrayList<>(); + EcompRole role1 = new EcompRole(); + role1.setId(123L); + rolesJson.add(role1); + Set 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 rolesJson = new ArrayList<>(); + EcompRole role1 = new EcompRole(); + role1.setId(123L); + rolesJson.add(role1); + Set 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 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 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 credentialsMap = onBoardingApiServiceImpl.getAppCredentials(); + Assert.assertNotNull(credentialsMap); + } + + @Test + public void getAppCredentialsAppNullTest() throws Exception{ + Mockito.when(appServiceImpl.getDefaultApp()).thenReturn(null); + OnBoardingApiServiceImpl onBoardingApiServiceImpl = new OnBoardingApiServiceImpl(); + Map 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 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 =""; + 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 childRoles = new TreeSet<>(); + childRoles.add(childRole); + + RoleFunction function = new RoleFunction(); + function.setId(11L); + SortedSet roleFunctions = new TreeSet<>(); + roleFunctions.add(function); + role.setRoleFunctions(roleFunctions); + + SortedSet roles = new TreeSet<>(); + roles.add(role); + role.setChildRoles(childRoles); + user.setRoles(roles); + + Set applicationMenuData = new HashSet(); + Set businessDirectMenuData= new HashSet(); + String loginMethod = ""; + List 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 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 elements = new HashSet<>(); + elements.add(SystemProperties.ECOMP_REQUEST_ID); + Enumeration 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 elements = new HashSet<>(); + Enumeration 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); + } +} diff --git a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/objectcache/jcs/JCSCacheEventHandler.java b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/objectcache/jcs/JCSCacheEventHandler.java index 71357f34..532bf706 100644 --- a/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/objectcache/jcs/JCSCacheEventHandler.java +++ b/ecomp-sdk/epsdk-core/src/main/java/org/onap/portalsdk/core/objectcache/jcs/JCSCacheEventHandler.java @@ -34,7 +34,7 @@ * ============LICENSE_END============================================ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ +*/ package org.onap.portalsdk.core.objectcache.jcs; import org.apache.jcs.engine.control.event.behavior.IElementEvent; diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/command/PostSearchBeanTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/command/PostSearchBeanTest.java index b5bc3477..905f1b93 100644 --- a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/command/PostSearchBeanTest.java +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/command/PostSearchBeanTest.java @@ -37,12 +37,16 @@ */ package org.onap.portalsdk.core.command; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; import org.junit.Test; +import junit.framework.Assert; + public class PostSearchBeanTest { + PostSearchBean postSearchBean= new PostSearchBean(); public PostSearchBean mockPostSearchBean() { @@ -92,6 +96,24 @@ public class PostSearchBeanTest { postSearchBean.setEmailOrig("testEmailOrig"); postSearchBean.setOrgManagerUserIdOrig("testOrgManagerUserIdOrig"); + postSearchBean.setSortBy1(null); + postSearchBean.setSortBy2(null); + postSearchBean.setSortBy3(null); + postSearchBean.setSortBy1Orig(null); + postSearchBean.setSortBy2Orig(null); + postSearchBean.setSortBy3Orig(null); + postSearchBean.setAccessType(null); + postSearchBean.setSubmitAction(null); + postSearchBean.setMasterId(null); + postSearchBean.setDetailId(null); + postSearchBean.setShowResult(null); + postSearchBean.setSearchResult(null); + postSearchBean.setSortByModifier1(null); + postSearchBean.setSortByModifier1Orig(null); + postSearchBean.setSortByModifier2(null); + postSearchBean.setSortByModifier2Orig(null); + postSearchBean.setSortByModifier3(null); + postSearchBean.setSortByModifier3Orig(null); return postSearchBean; } @@ -145,6 +167,26 @@ public class PostSearchBeanTest { postSearchBean.setOrgCodeOrig("testOrgCodeOrig"); postSearchBean.setEmailOrig("testEmailOrig"); postSearchBean.setOrgManagerUserIdOrig("testOrgManagerUserIdOrig"); + + postSearchBean.setSortBy1(null); + postSearchBean.setSortBy2(null); + postSearchBean.setSortBy3(null); + postSearchBean.setSortBy1Orig(null); + postSearchBean.setSortBy2Orig(null); + postSearchBean.setSortBy3Orig(null); + postSearchBean.setAccessType(null); + postSearchBean.setSubmitAction(null); + postSearchBean.setMasterId(null); + postSearchBean.setDetailId(null); + postSearchBean.setShowResult(null); + postSearchBean.setSearchResult(null); + postSearchBean.setSortByModifier1(null); + postSearchBean.setSortByModifier1Orig(null); + postSearchBean.setSortByModifier2(null); + postSearchBean.setSortByModifier2Orig(null); + postSearchBean.setSortByModifier3(null); + postSearchBean.setSortByModifier3Orig(null); + assertNull(postSearchBean.getUser().getCity()); assertNull(postSearchBean.getUserOrig().getCity()); assertEquals(postSearchBean.getSelected().length, mockPostSearchBean.getSelected().length); @@ -189,5 +231,58 @@ public class PostSearchBeanTest { assertEquals(postSearchBean.getEmailOrig(),mockPostSearchBean.getEmailOrig()); assertEquals(postSearchBean.getOrgManagerUserIdOrig(),mockPostSearchBean.getOrgManagerUserIdOrig()); + assertEquals(postSearchBean.getSortBy1(),mockPostSearchBean.getSortBy1()); + assertEquals(postSearchBean.getSortBy2(),mockPostSearchBean.getSortBy2()); + assertEquals(postSearchBean.getSortBy3(),mockPostSearchBean.getSortBy3()); + assertEquals(postSearchBean.getSortBy1Orig(),mockPostSearchBean.getSortBy1Orig()); + assertEquals(postSearchBean.getSortBy2Orig(),mockPostSearchBean.getSortBy2Orig()); + assertEquals(postSearchBean.getSortBy3Orig(),mockPostSearchBean.getSortBy3Orig()); + assertEquals(postSearchBean.getAccessType(),mockPostSearchBean.getAccessType()); + assertEquals(postSearchBean.getSubmitAction(),mockPostSearchBean.getSubmitAction()); + assertEquals(postSearchBean.getMasterId(),mockPostSearchBean.getMasterId()); + assertEquals(postSearchBean.getDetailId(),mockPostSearchBean.getDetailId()); + assertEquals(postSearchBean.getShowResult(),mockPostSearchBean.getShowResult()); + assertEquals(postSearchBean.getSearchResult(),mockPostSearchBean.getSearchResult()); + assertEquals(postSearchBean.getSortByModifier1(),mockPostSearchBean.getSortByModifier1()); + assertEquals(postSearchBean.getSortByModifier1Orig(),mockPostSearchBean.getSortByModifier1Orig()); + assertEquals(postSearchBean.getSortByModifier2(),mockPostSearchBean.getSortByModifier2()); + assertEquals(postSearchBean.getSortByModifier2Orig(),mockPostSearchBean.getSortByModifier2Orig()); + assertEquals(postSearchBean.getSortByModifier3(),mockPostSearchBean.getSortByModifier3()); + assertEquals(postSearchBean.getSortByModifier3Orig(),mockPostSearchBean.getSortByModifier3Orig()); + } + + @Test + public void getPageNoTest(){ + postSearchBean.setPageNo(1); + postSearchBean.getPageNo(); + } + + @Test + public void getPageSizeTest(){ + postSearchBean.setPageSize(1); + postSearchBean.getPageSize(); + } + + @Test + public void getDataSizeTest(){ + postSearchBean.setDataSize(1); + postSearchBean.getDataSize(); + } + + @Test + public void getNewDataSizeTest(){ + postSearchBean.getNewDataSize(); } + + @SuppressWarnings("deprecation") + @Test + public void isSortingUpdatedTest(){ + Assert.assertEquals(false, postSearchBean.isSortingUpdated()); + } + + @Test + public void resetSearchTest(){ + postSearchBean.resetSearch(); + } + } diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/controller/RestrictedBaseControllerTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/controller/RestrictedBaseControllerTest.java new file mode 100644 index 00000000..a8f0ba92 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/controller/RestrictedBaseControllerTest.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.portalsdk.core.controller; + +import org.junit.Assert; +import org.junit.Test; + +public class RestrictedBaseControllerTest { + + public RestrictedBaseController mockRestrictedBaseController() throws Exception{ + RestrictedBaseController restrictedBaseController = new RestrictedBaseController(); + + restrictedBaseController.setViewName("test"); + restrictedBaseController.setExceptionView("runtime_error_handler"); + restrictedBaseController.setDataAccessService(null); + restrictedBaseController.setMenu(null); + restrictedBaseController.setMenuBuilder(null); + + return restrictedBaseController; + } + + @Test + public void restrictedBaseControllerTest() throws Exception{ + RestrictedBaseController restrictedBaseController1 = mockRestrictedBaseController(); + + RestrictedBaseController restrictedBaseController = new RestrictedBaseController(); + restrictedBaseController.setViewName("test"); + restrictedBaseController.setExceptionView("runtime_error_handler"); + restrictedBaseController.setDataAccessService(null); + restrictedBaseController.setMenu(null); + restrictedBaseController.setMenuBuilder(null); + + Assert.assertEquals(restrictedBaseController1.getExceptionView(), restrictedBaseController.getExceptionView()); + Assert.assertEquals(restrictedBaseController1.getViewName(), restrictedBaseController.getViewName()); + Assert.assertEquals(restrictedBaseController1.getDataAccessService(), restrictedBaseController.getDataAccessService()); + Assert.assertEquals(restrictedBaseController1.getMenu(null), restrictedBaseController.getMenu(null)); + Assert.assertEquals(restrictedBaseController1.getMenuBuilder(), restrictedBaseController.getMenuBuilder()); + } + + @Test + public void isAccessibleTest(){ + RestrictedBaseController restrictedBaseController = new RestrictedBaseController(); + Assert.assertEquals(false, restrictedBaseController.isAccessible()); + Assert.assertEquals(false, restrictedBaseController.isRESTfulCall()); + } +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/controller/RestrictedRESTfulBaseControllerTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/controller/RestrictedRESTfulBaseControllerTest.java new file mode 100644 index 00000000..4070a44a --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/controller/RestrictedRESTfulBaseControllerTest.java @@ -0,0 +1,72 @@ +/* + * ============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.controller; + +import org.junit.Assert; +import org.junit.Test; + +public class RestrictedRESTfulBaseControllerTest { + + public RestrictedRESTfulBaseController mockRestrictedRESTfulBaseController(){ + RestrictedRESTfulBaseController restrictedRESTfulBaseController = new RestrictedRESTfulBaseController(); + + restrictedRESTfulBaseController.setViewName("test"); + restrictedRESTfulBaseController.setExceptionView("runtime_error_handler"); + + return restrictedRESTfulBaseController; + } + + @Test + public void RestrictedRESTfulBaseControllerTest(){ + RestrictedRESTfulBaseController restrictedRESTfulBaseController1 = mockRestrictedRESTfulBaseController(); + + RestrictedRESTfulBaseController restrictedRESTfulBaseController = new RestrictedRESTfulBaseController(); + restrictedRESTfulBaseController.setViewName("test"); + restrictedRESTfulBaseController.setExceptionView("runtime_error_handler"); + + Assert.assertEquals(restrictedRESTfulBaseController1.getExceptionView(), restrictedRESTfulBaseController.getExceptionView()); + Assert.assertEquals(restrictedRESTfulBaseController1.getViewName(), restrictedRESTfulBaseController.getViewName()); + } + + @Test + public void isAccessibleTest(){ + RestrictedRESTfulBaseController restrictedRESTfulBaseController = new RestrictedRESTfulBaseController(); + Assert.assertEquals(false, restrictedRESTfulBaseController.isAccessible()); + Assert.assertEquals(true, restrictedRESTfulBaseController.isRESTfulCall()); + } +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/controller/UnRestrictedBaseControllerTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/controller/UnRestrictedBaseControllerTest.java new file mode 100644 index 00000000..9b291514 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/controller/UnRestrictedBaseControllerTest.java @@ -0,0 +1,68 @@ +/* + * ============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.controller; + +import org.junit.Assert; +import org.junit.Test; + +public class UnRestrictedBaseControllerTest { + + public UnRestrictedBaseController mockUnRestrictedBaseController(){ + UnRestrictedBaseController unRestrictedBaseController = new UnRestrictedBaseController(); + + unRestrictedBaseController.setViewName("test"); + return unRestrictedBaseController; + } + + @Test + public void unRestrictedBaseControllerTest(){ + UnRestrictedBaseController unRestrictedBaseController1 = mockUnRestrictedBaseController(); + + UnRestrictedBaseController unRestrictedBaseController = new UnRestrictedBaseController(); + unRestrictedBaseController.setViewName("test"); + + Assert.assertEquals(unRestrictedBaseController1.getViewName(), unRestrictedBaseController.getViewName()); + } + + @Test + public void isAccessibleTest(){ + UnRestrictedBaseController unRestrictedBaseController = new UnRestrictedBaseController(); + Assert.assertEquals(true, unRestrictedBaseController.isAccessible()); + Assert.assertEquals(false, unRestrictedBaseController.isRESTfulCall()); + } +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/dao/ProfileDaoImplTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/dao/ProfileDaoImplTest.java new file mode 100644 index 00000000..3de08cb4 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/dao/ProfileDaoImplTest.java @@ -0,0 +1,90 @@ +/* + * ============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.dao; + +import java.util.ArrayList; +import java.util.List; + +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.criterion.Restrictions; +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.Profile; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +public class ProfileDaoImplTest { + + @InjectMocks + private ProfileDaoImpl profileDaoImpl; + + @Mock + private SessionFactory sessionFactory; + + @Test + public void findAllTest() { + Session session = Mockito.mock(Session.class); + Mockito.when(sessionFactory.getCurrentSession()).thenReturn(session); + Criteria crit = Mockito.mock(Criteria.class); + Mockito.when(session.createCriteria(Profile.class)).thenReturn(crit); + List list = new ArrayList<>(); + Profile profile = new Profile(); + list.add(profile); + Mockito.when(crit.list()).thenReturn(list); + List returnList = profileDaoImpl.findAll(); + Assert.assertTrue(returnList.size() > 0); + } + + @Test + public void getProfileTest() { + Session session = Mockito.mock(Session.class); + Mockito.when(sessionFactory.getCurrentSession()).thenReturn(session); + Criteria crit = Mockito.mock(Criteria.class); + Mockito.when(session.createCriteria(Profile.class)).thenReturn(crit); + Mockito.when(crit.uniqueResult()).thenReturn(new Profile()); + Profile profile = profileDaoImpl.getProfile(123); + Assert.assertNotNull(profile); + } + +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/dao/support/FusionDaoTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/dao/support/FusionDaoTest.java new file mode 100644 index 00000000..4bae6af5 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/dao/support/FusionDaoTest.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.portalsdk.core.dao.support; + +import org.junit.Test; + +import junit.framework.Assert; + +public class FusionDaoTest { + + public FusionDao mockFusionDao(){ + FusionDao fusionDao = new FusionDao(); + + fusionDao.setSessionFactory(null); + return fusionDao; + } + + @SuppressWarnings("deprecation") + @Test + public void fusionDaoTest(){ + FusionDao fusionDao = mockFusionDao(); + + FusionDao fusionDao1 = new FusionDao(); + fusionDao.setSessionFactory(null); + + Assert.assertEquals(fusionDao1.getSessionFactory(), fusionDao1.getSessionFactory());; + } +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/drools/DroolsRuleServiceImplTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/drools/DroolsRuleServiceImplTest.java new file mode 100644 index 00000000..1ab907c5 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/drools/DroolsRuleServiceImplTest.java @@ -0,0 +1,79 @@ +/* + * ============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.drools; + +import static org.junit.Assert.*; + +import org.junit.Test; + +import junit.framework.Assert; + +public class DroolsRuleServiceImplTest { + + public DroolsRuleServiceImpl mockDroolsRuleServiceImpl(){ + DroolsRuleServiceImpl droolsRuleServiceImpl = new DroolsRuleServiceImpl(); + + droolsRuleServiceImpl.setResultsString("test"); + + return droolsRuleServiceImpl; + } + + @SuppressWarnings("deprecation") + @Test + public void droolsRuleServiceImplTest(){ + DroolsRuleServiceImpl droolsRuleServiceImpl1 = mockDroolsRuleServiceImpl(); + + DroolsRuleServiceImpl droolsRuleServiceImpl = new DroolsRuleServiceImpl(); + droolsRuleServiceImpl.setResultsString("test"); + + Assert.assertEquals(droolsRuleServiceImpl1.getResultsString(), droolsRuleServiceImpl.getResultsString()); + } + + @Test + public void getStateTest(){ + DroolsRuleServiceImpl droolsRuleServiceImpl = new DroolsRuleServiceImpl(); + assertNull(droolsRuleServiceImpl.getState()); + } + + @SuppressWarnings("deprecation") + @Test + public void accessLabelTest(){ + DroolsRuleServiceImpl droolsRuleServiceImpl = new DroolsRuleServiceImpl(); + Assert.assertEquals("Drools POC Test", droolsRuleServiceImpl.accessLabel()); + } +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/exception/FusionExceptionResolverTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/exception/FusionExceptionResolverTest.java new file mode 100644 index 00000000..03bb8448 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/exception/FusionExceptionResolverTest.java @@ -0,0 +1,75 @@ +/* + * ============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.exception; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.web.servlet.ModelAndView; + +@RunWith(PowerMockRunner.class) +public class FusionExceptionResolverTest { + + @InjectMocks + FusionExceptionResolver fusionExceptionResolver; + + Exception exception = new Exception(); + UrlAccessRestrictedException urlAccessRestrictedException = new UrlAccessRestrictedException(); + SessionExpiredException sessionExpiredException = new SessionExpiredException(); + + @Test + public void handleUrlAccessExceptionTest() throws Exception{ + ModelAndView expectedModelAndView = fusionExceptionResolver.handleUrlAccessException(urlAccessRestrictedException); + Assert.assertNotNull(expectedModelAndView); + } + + @Test + public void handleSessionExceptionTest() throws Exception{ + ModelAndView expectedModelAndView = fusionExceptionResolver.handleSessionException(new SessionExpiredException()); + Assert.assertNotNull(expectedModelAndView); + } + + @Test + public void handleAllExceptionTest() throws Exception{ + ModelAndView expectedModelAndView = fusionExceptionResolver.handleAllException(exception); + Assert.assertNotNull(expectedModelAndView); + } + +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/interceptor/ResourceInterceptorTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/interceptor/ResourceInterceptorTest.java new file mode 100644 index 00000000..ddd465cf --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/interceptor/ResourceInterceptorTest.java @@ -0,0 +1,171 @@ +/* + * ============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.interceptor; + +import java.util.ArrayList; +import java.util.List; + +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.controller.FusionBaseController; +import org.onap.portalsdk.core.domain.App; +import org.onap.portalsdk.core.exception.UrlAccessRestrictedException; +import org.onap.portalsdk.core.objectcache.AbstractCacheManager; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.service.LoginService; +import org.onap.portalsdk.core.service.UrlAccessService; +import org.onap.portalsdk.core.service.WebServiceCallService; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.web.method.HandlerMethod; + +@RunWith(PowerMockRunner.class) +public class ResourceInterceptorTest { + + @InjectMocks + private ResourceInterceptor resourceInterceptor; + + @Mock + private DataAccessService dataAccessService; + @Mock + private LoginService loginService; + @Mock + private WebServiceCallService webServiceCallService; + @Mock + private AbstractCacheManager cacheManager; + @Mock + private UrlAccessService urlAccessService; + + @Test + public void preHandleFalseTest() throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest(); + HttpServletResponse response = new MockHttpServletResponse(); + + request.setRequestURI("xyz/resource"); + HandlerMethod handler = PowerMockito.mock(HandlerMethod.class); + FusionBaseController controller = PowerMockito.mock(FusionBaseController.class); + + Mockito.when(handler.getBean()).thenReturn(controller); + Mockito.when(controller.isAccessible()).thenReturn(false); + Mockito.when(controller.isRESTfulCall()).thenReturn(true); + Mockito.when(webServiceCallService.verifyRESTCredential(Mockito.anyString(), Mockito.anyString(), + Mockito.anyString())).thenReturn(false); + + boolean status = resourceInterceptor.preHandle(request, response, handler); + Assert.assertFalse(status); + } + + @Test(expected = UrlAccessRestrictedException.class) + public void preHandleExceptionTest() throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest(); + HttpServletResponse response = new MockHttpServletResponse(); + + request.setRequestURI("xyz/resource"); + HandlerMethod handler = PowerMockito.mock(HandlerMethod.class); + FusionBaseController controller = PowerMockito.mock(FusionBaseController.class); + + Mockito.when(handler.getBean()).thenReturn(controller); + Mockito.when(controller.isAccessible()).thenReturn(false); + Mockito.when(controller.isRESTfulCall()).thenReturn(false); + Mockito.when(urlAccessService.isUrlAccessible(Mockito.any(), Mockito.anyString())).thenReturn(false); + resourceInterceptor.preHandle(request, response, handler); + } + + @Test + public void preHandleTrueTest() throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest(); + HttpServletResponse response = new MockHttpServletResponse(); + + request.setRequestURI("xyz/resource"); + HandlerMethod handler = PowerMockito.mock(HandlerMethod.class); + FusionBaseController controller = PowerMockito.mock(FusionBaseController.class); + + App app = new App(); + app.setUsername("USER"); + Mockito.when(cacheManager.getObject("APP.METADATA")).thenReturn(app); + + Mockito.when(handler.getBean()).thenReturn(controller); + Mockito.when(controller.isAccessible()).thenReturn(true); + boolean status = resourceInterceptor.preHandle(request, response, handler); + Assert.assertTrue(status); + } + + @Test + public void preHandleTrueWithoutAppTest() throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest(); + HttpServletResponse response = new MockHttpServletResponse(); + + request.setRequestURI("xyz/resource"); + HandlerMethod handler = PowerMockito.mock(HandlerMethod.class); + FusionBaseController controller = PowerMockito.mock(FusionBaseController.class); + + App app = new App(); + app.setUsername("USER"); + + List list = new ArrayList<>(); + list.add(app); + StringBuilder criteria = new StringBuilder(); + criteria.append(" where id = 1"); + Mockito.when(dataAccessService.getList(App.class, criteria.toString(), null, null)).thenReturn(list); + + Mockito.when(handler.getBean()).thenReturn(controller); + Mockito.when(controller.isAccessible()).thenReturn(true); + boolean status = resourceInterceptor.preHandle(request, response, handler); + Assert.assertTrue(status); + } + + @Test + public void findAppTest() { + List list = new ArrayList<>(); + App app = new App(); + list.add(app); + StringBuilder criteria = new StringBuilder(); + criteria.append(" where id = 1"); + Mockito.when(dataAccessService.getList(App.class, criteria.toString(), null, null)).thenReturn(list); + App returnApp = resourceInterceptor.findApp(); + Assert.assertNotNull(returnApp); + } +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/interceptor/SessionTimeoutInterceptorTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/interceptor/SessionTimeoutInterceptorTest.java new file mode 100644 index 00000000..d92f10bb --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/interceptor/SessionTimeoutInterceptorTest.java @@ -0,0 +1,147 @@ +/* + * ============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.interceptor; + +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.Mockito; +import org.onap.portalsdk.core.controller.FusionBaseController; +import org.onap.portalsdk.core.domain.User; +import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.portalsdk.core.web.support.AppUtils; +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 org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.web.method.HandlerMethod; + + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ AppUtils.class, UserUtils.class, SystemProperties.class }) +public class SessionTimeoutInterceptorTest { + + @InjectMocks + private SessionTimeoutInterceptor sessionTimeoutInterceptor; + + @Test + public void preHandleTest() throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest(); + HttpServletResponse response = new MockHttpServletResponse(); + + request.setRequestURI("xyz/resource"); + HandlerMethod handler = PowerMockito.mock(HandlerMethod.class); + FusionBaseController controller = PowerMockito.mock(FusionBaseController.class); + + Mockito.when(handler.getBean()).thenReturn(controller); + Mockito.when(controller.isAccessible()).thenReturn(false); + Mockito.when(controller.isRESTfulCall()).thenReturn(false); + + PowerMockito.mockStatic(AppUtils.class); + PowerMockito.mockStatic(UserUtils.class); + HttpSession session = PowerMockito.mock(HttpSession.class); + Mockito.when(AppUtils.getSession(request)).thenReturn(session); + Mockito.when(UserUtils.getUserSession(request)).thenReturn(new User()); + + boolean status = sessionTimeoutInterceptor.preHandle(request, response, handler); + Assert.assertTrue(status); + } + + @Test + public void preHandleSecurityExceptionTest() throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest(); + HttpServletResponse response = new MockHttpServletResponse(); + + request.setRequestURI("xyz/resource/logout.htm"); + HandlerMethod handler = PowerMockito.mock(HandlerMethod.class); + FusionBaseController controller = PowerMockito.mock(FusionBaseController.class); + + Mockito.when(handler.getBean()).thenReturn(controller); + Mockito.when(controller.isAccessible()).thenReturn(false); + Mockito.when(controller.isRESTfulCall()).thenReturn(false); + + PowerMockito.mockStatic(AppUtils.class); + PowerMockito.mockStatic(UserUtils.class); + HttpSession session = PowerMockito.mock(HttpSession.class); + Mockito.when(AppUtils.getSession(request)).thenReturn(session); + Mockito.when(UserUtils.getUserSession(request)).thenReturn(new User()); + + boolean status = sessionTimeoutInterceptor.preHandle(request, response, handler); + Assert.assertFalse(status); + } + + @Test + public void preHandleExceptionTest() throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest(); + HttpServletResponse response = new MockHttpServletResponse(); + + request.setRequestURI("xyz/resource"); + HandlerMethod handler = PowerMockito.mock(HandlerMethod.class); + FusionBaseController controller = PowerMockito.mock(FusionBaseController.class); + + Mockito.when(handler.getBean()).thenReturn(controller); + Mockito.when(controller.isAccessible()).thenReturn(false); + Mockito.when(controller.isRESTfulCall()).thenReturn(false); + + PowerMockito.mockStatic(AppUtils.class); + PowerMockito.mockStatic(UserUtils.class); + HttpSession session = PowerMockito.mock(HttpSession.class); + Mockito.when(AppUtils.getSession(request)).thenReturn(session); + Mockito.when(UserUtils.getUserSession(request)).thenReturn(null); + + boolean status = sessionTimeoutInterceptor.preHandle(request, response, handler); + Assert.assertFalse(status); + } + + @Test(expected = SecurityException.class) + public void validateDomainTest() throws Exception { + String relativePath = "testUrl"; + String redirectUrl = "http://www.xyz.com/" + relativePath; + + PowerMockito.mockStatic(SystemProperties.class); + Mockito.when(SystemProperties.getProperty(SystemProperties.COOKIE_DOMAIN)).thenReturn(relativePath); + + sessionTimeoutInterceptor.validateDomain(redirectUrl); + } +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/listener/CollaborateListBindingListenerTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/listener/CollaborateListBindingListenerTest.java new file mode 100644 index 00000000..3e0d045f --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/listener/CollaborateListBindingListenerTest.java @@ -0,0 +1,74 @@ +/* + * ============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.listener; + +import javax.servlet.http.HttpSessionBindingEvent; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +public class CollaborateListBindingListenerTest { + + @InjectMocks + private CollaborateListBindingListener collabBindingListener; + + @Test + public void valueBoundTest() { + HttpSessionBindingEvent event = Mockito.mock(HttpSessionBindingEvent.class); + CollaborateListBindingListener mock = new CollaborateListBindingListener("Test"); + mock.setUserName("Test"); + Mockito.when(event.getValue()).thenReturn(mock); + collabBindingListener.valueBound(event); + Assert.assertTrue(true); + } + + @Test + public void valueUnboundTest() { + HttpSessionBindingEvent event = Mockito.mock(HttpSessionBindingEvent.class); + CollaborateListBindingListener mock = new CollaborateListBindingListener("Test"); + mock.setUserName("Test"); + Mockito.when(event.getValue()).thenReturn(mock); + collabBindingListener.valueUnbound(event); + Assert.assertTrue(true); + } +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/listener/UserSessionListenerTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/listener/UserSessionListenerTest.java new file mode 100644 index 00000000..e8d93b6f --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/listener/UserSessionListenerTest.java @@ -0,0 +1,79 @@ +/* + * ============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.listener; + +import javax.servlet.http.HttpSession; +import javax.servlet.http.HttpSessionEvent; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.powermock.modules.junit4.PowerMockRunner; + + +@RunWith(PowerMockRunner.class) +public class UserSessionListenerTest { + + @InjectMocks + private UserSessionListener userSessionListener; + + @Test + public void sessionCreatedTest() { + HttpSessionEvent event = Mockito.mock(HttpSessionEvent.class); + userSessionListener.sessionCreated(event); + Assert.assertTrue(true); + } + + @Test + public void sessionDestroyedTest() { + HttpSessionEvent event = Mockito.mock(HttpSessionEvent.class); + HttpSession sesion = Mockito.mock(HttpSession.class); + Mockito.when(event.getSession()).thenReturn(sesion); + userSessionListener.sessionDestroyed(event); + Assert.assertTrue(true); + } + + @Test + public void sessionDestroyedExceptionTest() { + HttpSessionEvent event = Mockito.mock(HttpSessionEvent.class); + userSessionListener.sessionDestroyed(event); + Assert.assertTrue(true); + } +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/logging/aspect/EELFLoggerAdviceTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/logging/aspect/EELFLoggerAdviceTest.java new file mode 100644 index 00000000..324910e4 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/logging/aspect/EELFLoggerAdviceTest.java @@ -0,0 +1,92 @@ +/* + * ============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.logging.aspect; + +import javax.servlet.http.HttpServletRequest; + +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.service.AppService; +import org.onap.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +public class EELFLoggerAdviceTest { + + @InjectMocks + private EELFLoggerAdvice eelFLoggerAdvice; + + @Mock + private AppService appService; + + @Test + public void getCurrentDateTimeUTCTest(){ + String timeAsString = eelFLoggerAdvice.getCurrentDateTimeUTC(); + Assert.assertNotNull(timeAsString); + } + + @Test + public void beforeTest() { + SecurityEventTypeEnum securityEventType = SecurityEventTypeEnum.INCOMING_REST_MESSAGE; + Object[] args = new Object[2]; + Object[] passOnArgs = new Object[2]; + HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); + passOnArgs[0] = "ClassName"; + passOnArgs[1] = "MethodName"; + args[0] = mockReq; + eelFLoggerAdvice.before(securityEventType, args, passOnArgs); + Assert.assertTrue(true); + } + + @Test + public void afterTest() { + SecurityEventTypeEnum securityEventType = SecurityEventTypeEnum.INCOMING_REST_MESSAGE; + Object[] args = new Object[2]; + Object[] passOnArgs = new Object[2]; + HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class); + passOnArgs[0] = "ClassName"; + passOnArgs[1] = "MethodName"; + args[0] = mockReq; + eelFLoggerAdvice.after(securityEventType, "Result", args, null, passOnArgs); + Assert.assertTrue(true); + } +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/logging/aspect/EELFLoggerAspectTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/logging/aspect/EELFLoggerAspectTest.java new file mode 100644 index 00000000..ea0b42fb --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/logging/aspect/EELFLoggerAspectTest.java @@ -0,0 +1,162 @@ +/* + * ============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.logging.aspect; + +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.Signature; +import org.aspectj.lang.annotation.Around; +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 EELFLoggerAspectTest { + + @InjectMocks + private EELFLoggerAspect eelFLoggerAspect; + + @Mock + private EELFLoggerAdvice advice; + + @Test + public void incomingAuditMessagesTest() { + eelFLoggerAspect.incomingAuditMessages(); + Assert.assertTrue(true); + } + + @Test + public void logAuditMethodAroundTest() throws Throwable { + ProceedingJoinPoint joinPoint = Mockito.mock(ProceedingJoinPoint.class); + AuditLog mockLog = Mockito.mock(AuditLog.class); + Signature sign = Mockito.mock(Signature.class); + + Mockito.when(joinPoint.getSignature()).thenReturn(sign); + Mockito.when(sign.getDeclaringType()).thenReturn(getClass()); + Mockito.when(sign.getName()).thenReturn("MethodName"); + + eelFLoggerAspect.logAuditMethodAround(joinPoint, mockLog); + Assert.assertTrue(true); + } + + @Test + public void logAuditMethodClassAroundTest() throws Throwable { + + ProceedingJoinPoint joinPoint = Mockito.mock(ProceedingJoinPoint.class); + AuditLog mockLog = Mockito.mock(AuditLog.class); + Signature sign = Mockito.mock(Signature.class); + + Mockito.when(joinPoint.getSignature()).thenReturn(sign); + Mockito.when(sign.getDeclaringType()).thenReturn(getClass()); + Mockito.when(sign.getName()).thenReturn("MethodName"); + + eelFLoggerAspect.logAuditMethodClassAround(joinPoint, mockLog); + Assert.assertTrue(true); + } + + @Test + public void publicMethodTst(){ + eelFLoggerAspect.publicMethod(); + Assert.assertTrue(true); + } + + @Test + public void logMetricsClassAroundTest() throws Throwable { + ProceedingJoinPoint joinPoint = Mockito.mock(ProceedingJoinPoint.class); + MetricsLog mockLog = Mockito.mock(MetricsLog.class); + Signature sign = Mockito.mock(Signature.class); + + Mockito.when(joinPoint.getSignature()).thenReturn(sign); + Mockito.when(sign.getDeclaringType()).thenReturn(getClass()); + Mockito.when(sign.getName()).thenReturn("MethodName"); + + eelFLoggerAspect.logMetricsClassAround(joinPoint, mockLog); + Assert.assertTrue(true); + } + + @Test + public void logMetricsMethodAroundTest() throws Throwable { + ProceedingJoinPoint joinPoint = Mockito.mock(ProceedingJoinPoint.class); + MetricsLog mockLog = Mockito.mock(MetricsLog.class); + Signature sign = Mockito.mock(Signature.class); + + Mockito.when(joinPoint.getSignature()).thenReturn(sign); + Mockito.when(sign.getDeclaringType()).thenReturn(getClass()); + Mockito.when(sign.getName()).thenReturn("MethodName"); + + eelFLoggerAspect.logMetricsMethodAround(joinPoint, mockLog); + Assert.assertTrue(true); + } + + @Test + public void performMetricsLoggingTest() { + eelFLoggerAspect.performMetricsLogging(); + Assert.assertTrue(true); + } + + @Test + public void metricsLoggingAroundClassTest() throws Throwable { + ProceedingJoinPoint joinPoint = Mockito.mock(ProceedingJoinPoint.class); + MetricsLog mockLog = Mockito.mock(MetricsLog.class); + Signature sign = Mockito.mock(Signature.class); + + Mockito.when(joinPoint.getSignature()).thenReturn(sign); + Mockito.when(sign.getDeclaringType()).thenReturn(getClass()); + Mockito.when(sign.getName()).thenReturn("MethodName"); + + eelFLoggerAspect.metricsLoggingAroundClass(joinPoint, mockLog); + Assert.assertTrue(true); + } + + @Test + public void metricsLoggingAroundMethodTest() throws Throwable { + ProceedingJoinPoint joinPoint = Mockito.mock(ProceedingJoinPoint.class); + MetricsLog mockLog = Mockito.mock(MetricsLog.class); + Signature sign = Mockito.mock(Signature.class); + + Mockito.when(joinPoint.getSignature()).thenReturn(sign); + Mockito.when(sign.getDeclaringType()).thenReturn(getClass()); + Mockito.when(sign.getName()).thenReturn("MethodName"); + + eelFLoggerAspect.metricsLoggingAroundMethod(joinPoint, mockLog); + Assert.assertTrue(true); + } +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/logging/logic/EELFLoggerDelegateTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/logging/logic/EELFLoggerDelegateTest.java new file mode 100644 index 00000000..cf0b5124 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/logging/logic/EELFLoggerDelegateTest.java @@ -0,0 +1,320 @@ +/* + * ============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.logging.logic; + +import javax.servlet.http.HttpServletRequest; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.onap.portalsdk.core.domain.User; +import org.onap.portalsdk.core.logging.format.AlarmSeverityEnum; +import org.onap.portalsdk.core.logging.format.AppMessagesEnum; +import org.onap.portalsdk.core.util.SystemProperties; +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.slf4j.MDC; + +import com.att.eelf.configuration.EELFLogger; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({UserUtils.class}) +public class EELFLoggerDelegateTest { + + @Test + public void getLoogerTest() { + EELFLoggerDelegate eelFLoggerDelegate = new EELFLoggerDelegate(getClass().getName()); + EELFLoggerDelegate logger = eelFLoggerDelegate.getLogger(""); + logger = eelFLoggerDelegate.getLogger(getClass()); + Assert.assertNotNull(logger); + } + + @Test + public void traceTest() { + EELFLoggerDelegate eelFLoggerDelegate = new EELFLoggerDelegate(getClass().getName()); + + EELFLogger logger = Mockito.mock(EELFLogger.class); + Mockito.when(logger.isTraceEnabled()).thenReturn(true); + String msg = "test"; + eelFLoggerDelegate.trace(logger, msg); + Assert.assertTrue(true); + } + + @Test + public void traceArgsTest() { + EELFLoggerDelegate eelFLoggerDelegate = new EELFLoggerDelegate(getClass().getName()); + + EELFLogger logger = Mockito.mock(EELFLogger.class); + Mockito.when(logger.isTraceEnabled()).thenReturn(true); + String msg = "test"; + Object[] args = new Object[2]; + eelFLoggerDelegate.trace(logger, msg, args); + Assert.assertTrue(true); + } + + @Test + public void traceExceptionTest() { + EELFLoggerDelegate eelFLoggerDelegate = new EELFLoggerDelegate(getClass().getName()); + + EELFLogger logger = Mockito.mock(EELFLogger.class); + Mockito.when(logger.isTraceEnabled()).thenReturn(true); + String msg = "test"; + eelFLoggerDelegate.trace(logger, msg, new Exception()); + Assert.assertTrue(true); + } + + @Test + public void debugTest() { + EELFLoggerDelegate eelFLoggerDelegate = new EELFLoggerDelegate(getClass().getName()); + + EELFLogger logger = Mockito.mock(EELFLogger.class); + Mockito.when(logger.isDebugEnabled()).thenReturn(true); + String msg = "test"; + eelFLoggerDelegate.debug(logger, msg); + Assert.assertTrue(true); + } + + @Test + public void debugArgsTest() { + EELFLoggerDelegate eelFLoggerDelegate = new EELFLoggerDelegate(getClass().getName()); + + EELFLogger logger = Mockito.mock(EELFLogger.class); + Mockito.when(logger.isDebugEnabled()).thenReturn(true); + String msg = "test"; + Object[] args = new Object[2]; + eelFLoggerDelegate.debug(logger, msg, args); + Assert.assertTrue(true); + } + + @Test + public void debugExceptionTest() { + EELFLoggerDelegate eelFLoggerDelegate = new EELFLoggerDelegate(getClass().getName()); + + EELFLogger logger = Mockito.mock(EELFLogger.class); + Mockito.when(logger.isDebugEnabled()).thenReturn(true); + String msg = "test"; + eelFLoggerDelegate.debug(logger, msg, new Exception()); + Assert.assertTrue(true); + } + + @Test + public void infoTest() { + EELFLoggerDelegate eelFLoggerDelegate = new EELFLoggerDelegate(getClass().getName()); + + EELFLogger logger = Mockito.mock(EELFLogger.class); + String msg = "test"; + eelFLoggerDelegate.info(logger, msg); + Assert.assertTrue(true); + } + + @Test + public void infoArgsTest() { + EELFLoggerDelegate eelFLoggerDelegate = new EELFLoggerDelegate(getClass().getName()); + + EELFLogger logger = Mockito.mock(EELFLogger.class); + String msg = "test"; + Object[] args = new Object[2]; + eelFLoggerDelegate.info(logger, msg, args); + Assert.assertTrue(true); + } + + @Test + public void infoExceptionTest() { + EELFLoggerDelegate eelFLoggerDelegate = new EELFLoggerDelegate(getClass().getName()); + + EELFLogger logger = Mockito.mock(EELFLogger.class); + String msg = "test"; + eelFLoggerDelegate.info(logger, msg, new Exception()); + Assert.assertTrue(true); + } + + @Test + public void warnTest() { + EELFLoggerDelegate eelFLoggerDelegate = new EELFLoggerDelegate(getClass().getName()); + + EELFLogger logger = Mockito.mock(EELFLogger.class); + String msg = "test"; + eelFLoggerDelegate.warn(logger, msg); + Assert.assertTrue(true); + } + + @Test + public void warnArgsTest() { + EELFLoggerDelegate eelFLoggerDelegate = new EELFLoggerDelegate(getClass().getName()); + + EELFLogger logger = Mockito.mock(EELFLogger.class); + String msg = "test"; + Object[] args = new Object[2]; + eelFLoggerDelegate.warn(logger, msg, args); + Assert.assertTrue(true); + } + + @Test + public void warnExceptionTest() { + EELFLoggerDelegate eelFLoggerDelegate = new EELFLoggerDelegate(getClass().getName()); + + EELFLogger logger = Mockito.mock(EELFLogger.class); + String msg = "test"; + eelFLoggerDelegate.warn(logger, msg, new Exception()); + Assert.assertTrue(true); + } + + @Test + public void errorTest() { + EELFLoggerDelegate eelFLoggerDelegate = new EELFLoggerDelegate(getClass().getName()); + + EELFLogger logger = Mockito.mock(EELFLogger.class); + String msg = "test"; + eelFLoggerDelegate.error(logger, msg); + Assert.assertTrue(true); + } + + @Test + public void errorArgsTest() { + EELFLoggerDelegate eelFLoggerDelegate = new EELFLoggerDelegate(getClass().getName()); + + EELFLogger logger = Mockito.mock(EELFLogger.class); + String msg = "test"; + Object[] args = new Object[2]; + eelFLoggerDelegate.error(logger, msg, args); + Assert.assertTrue(true); + } + + @Test + public void errorExceptionTest() { + EELFLoggerDelegate eelFLoggerDelegate = new EELFLoggerDelegate(getClass().getName()); + + EELFLogger logger = Mockito.mock(EELFLogger.class); + String msg = "test"; + eelFLoggerDelegate.error(logger, msg, new Exception()); + Assert.assertTrue(true); + } + @Test + public void errorEnumTest() { + EELFLoggerDelegate eelFLoggerDelegate = new EELFLoggerDelegate(getClass().getName()); + + EELFLogger logger = Mockito.mock(EELFLogger.class); + String msg = "test"; + eelFLoggerDelegate.error(logger, msg, AlarmSeverityEnum.MINOR); + Assert.assertTrue(true); + } + + @Test + public void initTest(){ + EELFLoggerDelegate eelFLoggerDelegate = new EELFLoggerDelegate(getClass().getName()); + eelFLoggerDelegate.init(); + Assert.assertTrue(true); + } + + @Test + public void logEcompErrorTest() { + AppMessagesEnum epMessageEnum = AppMessagesEnum.BeDaoCloseSessionError; + EELFLoggerDelegate eelFLoggerDelegate = new EELFLoggerDelegate(getClass().getName()); + String[] param= new String[2]; + eelFLoggerDelegate.logEcompError(epMessageEnum, param); + Assert.assertTrue(true); + } + + @Test + public void logEcompErrorInfoTest() { + AppMessagesEnum epMessageEnum = AppMessagesEnum.InternalUnexpectedInfo; + EELFLoggerDelegate eelFLoggerDelegate = new EELFLoggerDelegate(getClass().getName()); + String[] param= new String[2]; + eelFLoggerDelegate.logEcompError(epMessageEnum, param); + Assert.assertTrue(true); + } + @Test + public void logEcompErrorWarnTest() { + AppMessagesEnum epMessageEnum = AppMessagesEnum.InternalUnexpectedWarning; + EELFLoggerDelegate eelFLoggerDelegate = new EELFLoggerDelegate(getClass().getName()); + eelFLoggerDelegate.logEcompError(epMessageEnum, null); + Assert.assertTrue(true); + } + + @Test + public void logEcompErrorNullTest() { + AppMessagesEnum epMessageEnum = null; + EELFLoggerDelegate eelFLoggerDelegate = new EELFLoggerDelegate(getClass().getName()); + String[] param= new String[2]; + eelFLoggerDelegate.logEcompError(epMessageEnum, param); + Assert.assertTrue(true); + } + + @Test + public void mdcPutTest() { + String key = "Key"; + String value = "Value"; + EELFLoggerDelegate.mdcPut(key, value); + Assert.assertTrue(true); + } + + @Test + public void mdcGetTest() { + String key = "Key"; + EELFLoggerDelegate.mdcGet(key); + Assert.assertTrue(true); + } + + @Test + public void mdcRemoveTest() { + String key = "Key"; + EELFLoggerDelegate.mdcRemove(key); + Assert.assertTrue(true); + MDC.remove(key); + } + + @Test + public void setRequestBasedDefaultsIntoGlobalLoggingContextTest() { + HttpServletRequest req = Mockito.mock(HttpServletRequest.class); + String appName = "Test App"; + Mockito.when(req.getHeader(SystemProperties.USERAGENT_NAME)).thenReturn("ChromeTest"); + + PowerMockito.mockStatic(UserUtils.class); + User user = new User(); + user.setLoginId("123"); + Mockito.when(UserUtils.getUserSession(req)).thenReturn(user); + Mockito.when(UserUtils.getRequestId(req)).thenReturn("https://xyb/resource"); + Mockito.when(UserUtils.getFullURL(req)).thenReturn("https://xyb/resource"); + EELFLoggerDelegate eelFLoggerDelegate = new EELFLoggerDelegate(getClass().getName()); + eelFLoggerDelegate.setRequestBasedDefaultsIntoGlobalLoggingContext(req, appName); + } + +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/menu/MenuBuilderTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/menu/MenuBuilderTest.java new file mode 100644 index 00000000..d3789490 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/menu/MenuBuilderTest.java @@ -0,0 +1,173 @@ +/* + * ============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.menu; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + +import javax.servlet.http.HttpServletRequest; + +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.MenuData; +import org.onap.portalsdk.core.service.DataAccessService; +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; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ UserUtils.class }) +public class MenuBuilderTest { + + @InjectMocks + private MenuBuilder menuBuilder; + + @Mock + private DataAccessService dataAccessService; + + @Test + public void getMenuTest() { + String menuSetName = "Root Meunu"; + + MenuData menuData = new MenuData(); + Set childMenus = new TreeSet(); + menuData.setChildMenus(childMenus); + List menuItems = new ArrayList(); + menuItems.add(menuData); + Mockito.when(dataAccessService.executeNamedQuery(Mockito.anyString(), Mockito.anyMap(), Mockito.anyMap())) + .thenReturn(menuItems); + Set menu = menuBuilder.getMenu(menuSetName, dataAccessService); + Assert.assertNotNull(menu); + } + + @Test + public void getMenuWithDaoTest() { + String menuSetName = "Root Meunu"; + + MenuData menuData = new MenuData(); + Set childMenus = new TreeSet(); + menuData.setChildMenus(childMenus); + List menuItems = new ArrayList(); + menuItems.add(menuData); + Mockito.when(dataAccessService.executeNamedQuery(Mockito.anyString(), Mockito.anyMap(), Mockito.anyMap())) + .thenReturn(menuItems); + Set menu = menuBuilder.getMenu(menuSetName); + Assert.assertNotNull(menu); + } + + @Test + public void filterMenuTrueTest() { + MenuData menu = new MenuData(); + MenuData childMenu = new MenuData(); + Set childMenus = new TreeSet(); + childMenus.add(childMenu); + menu.setChildMenus(childMenus); + Set menus = new TreeSet(); + menus.add(menu); + + PowerMockito.mockStatic(UserUtils.class); + Mockito.when(UserUtils.isAccessible(Mockito.any(), Mockito.any())).thenReturn(true); + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + menuBuilder.filterMenu(menus, request); + Assert.assertTrue(true); + } + + @Test + public void filterMenuFalseest() { + MenuData menu = new MenuData(); + MenuData childMenu = new MenuData(); + Set childMenus = new TreeSet(); + childMenus.add(childMenu); + menu.setChildMenus(childMenus); + Set menus = new TreeSet(); + menus.add(menu); + + PowerMockito.mockStatic(UserUtils.class); + Mockito.when(UserUtils.isAccessible(Mockito.any(), Mockito.any())).thenReturn(false); + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + menuBuilder.filterMenu(menus, request); + Assert.assertTrue(true); + } + + @Test + public void getUrlHtmlExternalTest() { + MenuData menuData = new MenuData(); + menuData.setExternalUrl("External"); + String htmlString = menuBuilder.getUrlHtml(menuData); + Assert.assertTrue(true); + } + + @Test + public void getUrlHtmlServletTest() { + MenuData menuData = new MenuData(); + menuData.setServlet("Servlet"); + String htmlString = menuBuilder.getUrlHtml(menuData); + Assert.assertTrue(true); + } + + @Test + public void getUrlHtmlActionTest() { + MenuData menuData = new MenuData(); + menuData.setAction("Action"); + String htmlString = menuBuilder.getUrlHtml(menuData); + Assert.assertNotNull(htmlString); + } + + @Test + public void getTargetHtmlTest() { + MenuData menuData = new MenuData(); + menuData.setTarget("Sub system"); + String html = menuBuilder.getTargetHtml(menuData); + Assert.assertNotNull(html); + } + + @Test + public void getQueryStringHtmlTest() { + MenuData menuData = new MenuData(); + menuData.setQueryString("Sub system"); + String html = menuBuilder.getQueryStringHtml(menuData); + Assert.assertNotNull(html); + } +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/menu/MenuPropertiesTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/menu/MenuPropertiesTest.java new file mode 100644 index 00000000..71857545 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/menu/MenuPropertiesTest.java @@ -0,0 +1,74 @@ +/* + * ============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.menu; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; + +import javax.servlet.ServletContext; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +public class MenuPropertiesTest { + + @InjectMocks + private MenuProperties menuProperties; + + @Test + public void loadFromFile() throws Exception { + ServletContext servletContext = Mockito.mock(ServletContext.class); + String filename = ""; + String menuSetName =""; + String content = "key=value"; + InputStream is = new ByteArrayInputStream(content.getBytes()); + Mockito.when(servletContext.getResourceAsStream(Mockito.anyString())).thenReturn(is); + menuProperties.loadFromFile(servletContext, filename, menuSetName); + Assert.assertTrue(true); + String key ="key"; + menuProperties.getProperty(key); + Assert.assertTrue(true); + } + + +} \ No newline at end of file diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/objectcache/jcs/JCSCacheEventHandlerTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/objectcache/jcs/JCSCacheEventHandlerTest.java new file mode 100644 index 00000000..830af118 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/objectcache/jcs/JCSCacheEventHandlerTest.java @@ -0,0 +1,120 @@ +/* + * ============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.objectcache.jcs; + +import org.apache.jcs.engine.control.event.behavior.IElementEvent; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +public class JCSCacheEventHandlerTest { + + @InjectMocks + private JCSCacheEventHandler jcsCacheEventHandler; + + @Test + public void handleElementEventBackgroundTest() { + IElementEvent event = Mockito.mock(IElementEvent.class); + Mockito.when(event.getElementEvent()) + .thenReturn(jcsCacheEventHandler.ELEMENT_EVENT_EXCEEDED_MAXLIFE_BACKGROUND); + jcsCacheEventHandler.handleElementEvent(event); + Assert.assertTrue(true); + } + + @Test + public void handleElementEventMaxLifeTest() { + IElementEvent event = Mockito.mock(IElementEvent.class); + Mockito.when(event.getElementEvent()).thenReturn(jcsCacheEventHandler.ELEMENT_EVENT_EXCEEDED_MAXLIFE_ONREQUEST); + jcsCacheEventHandler.handleElementEvent(event); + Assert.assertTrue(true); + } + + @Test + public void handleElementEventIdlyBackgroundTest() { + IElementEvent event = Mockito.mock(IElementEvent.class); + Mockito.when(event.getElementEvent()) + .thenReturn(jcsCacheEventHandler.ELEMENT_EVENT_EXCEEDED_IDLETIME_BACKGROUND); + jcsCacheEventHandler.handleElementEvent(event); + Assert.assertTrue(true); + } + + @Test + public void handleElementEventOnReqTest() { + IElementEvent event = Mockito.mock(IElementEvent.class); + Mockito.when(event.getElementEvent()) + .thenReturn(jcsCacheEventHandler.ELEMENT_EVENT_EXCEEDED_IDLETIME_ONREQUEST); + jcsCacheEventHandler.handleElementEvent(event); + Assert.assertTrue(true); + } + + @Test + public void handleElementEventAvaliTest() { + IElementEvent event = Mockito.mock(IElementEvent.class); + Mockito.when(event.getElementEvent()).thenReturn(jcsCacheEventHandler.ELEMENT_EVENT_SPOOLED_DISK_AVAILABLE); + jcsCacheEventHandler.handleElementEvent(event); + Assert.assertTrue(true); + } + + @Test + public void handleElementEventNotAvaliTest() { + IElementEvent event = Mockito.mock(IElementEvent.class); + Mockito.when(event.getElementEvent()).thenReturn(jcsCacheEventHandler.ELEMENT_EVENT_SPOOLED_DISK_NOT_AVAILABLE); + jcsCacheEventHandler.handleElementEvent(event); + Assert.assertTrue(true); + } + + @Test + public void handleElementEventNotAllowedTest() { + IElementEvent event = Mockito.mock(IElementEvent.class); + Mockito.when(event.getElementEvent()).thenReturn(jcsCacheEventHandler.ELEMENT_EVENT_SPOOLED_NOT_ALLOWED); + jcsCacheEventHandler.handleElementEvent(event); + Assert.assertTrue(true); + } + + @Test + public void handleElementEventDefaultTest() { + IElementEvent event = Mockito.mock(IElementEvent.class); + Mockito.when(event.getElementEvent()).thenReturn(100); + jcsCacheEventHandler.handleElementEvent(event); + Assert.assertTrue(true); + } +} \ No newline at end of file diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/restful/client/HttpStatusAndResponseTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/restful/client/HttpStatusAndResponseTest.java new file mode 100644 index 00000000..ecf2d255 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/restful/client/HttpStatusAndResponseTest.java @@ -0,0 +1,62 @@ +/* + * ============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.restful.client; + +import org.junit.Test; + +import junit.framework.Assert; + +public class HttpStatusAndResponseTest { + + public HttpStatusAndResponse mockHttpStatusAndResponse(){ + HttpStatusAndResponse httpStatusAndResponse = new HttpStatusAndResponse(0, null); + + return httpStatusAndResponse; + } + + @SuppressWarnings("deprecation") + @Test + public void httpStatusAndResponseTest(){ + HttpStatusAndResponse httpStatusAndResponse1 = mockHttpStatusAndResponse(); + + HttpStatusAndResponse httpStatusAndResponse = new HttpStatusAndResponse(0, null); + + Assert.assertEquals(httpStatusAndResponse.getResponse(), httpStatusAndResponse1.getResponse()); + Assert.assertEquals(httpStatusAndResponse.getStatusCode(), httpStatusAndResponse1.getStatusCode()); + } +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/restful/client/PortalRestClientBaseTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/restful/client/PortalRestClientBaseTest.java new file mode 100644 index 00000000..056a1190 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/restful/client/PortalRestClientBaseTest.java @@ -0,0 +1,209 @@ +/* + * ============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.restful.client; + +import java.net.URI; + +import org.apache.http.HttpEntity; +import org.apache.http.StatusLine; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +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.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.client.PortalRestClientBase; +import org.onap.portalsdk.core.service.AppService; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ PortalApiProperties.class, CipherUtil.class, HttpClients.class}) +public class PortalRestClientBaseTest { + + @InjectMocks + private PortalRestClientBase portalRestClientBase; + + @Mock + private AppService appService; + + @Test(expected = IllegalArgumentException.class) + public void getRestWithCredentialsExceptionTest() throws Exception { + URI uri = PowerMockito.mock(URI.class); + portalRestClientBase.getRestWithCredentials(uri); + Assert.assertTrue(true); + } + + @Test + public void getRestWithCredentialsTest() throws Exception { + URI uri = PowerMockito.mock(URI.class); + + App app = new App(); + app.setUsername("User"); + String password = "Password"; + app.setAppPassword(password); + Mockito.when(appService.getDefaultApp()).thenReturn(app); + + PowerMockito.mockStatic(PortalApiProperties.class); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY)).thenReturn("Key"); + + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(CipherUtil.decryptPKC(app.getAppPassword())).thenReturn(password); + + CloseableHttpClient httpClient = PowerMockito.mock(CloseableHttpClient.class); + CloseableHttpResponse response = PowerMockito.mock(CloseableHttpResponse.class); + + PowerMockito.mockStatic(HttpClients.class); + Mockito.when(HttpClients.createDefault()).thenReturn(httpClient); + Mockito.when(httpClient.execute(Mockito.any())).thenReturn(response); + HttpEntity entity = PowerMockito.mock(HttpEntity.class); + Mockito.when(response.getEntity()).thenReturn(entity); + StatusLine statusLine = Mockito.mock(StatusLine.class); + Mockito.when(response.getStatusLine()).thenReturn(statusLine); + + portalRestClientBase.getRestWithCredentials(uri); + Assert.assertTrue(true); + } + + @Test + public void getRestWithCredentialsEntityNullTest() throws Exception { + URI uri = PowerMockito.mock(URI.class); + + App app = new App(); + app.setUsername("User"); + String password = "Password"; + app.setAppPassword(password); + Mockito.when(appService.getDefaultApp()).thenReturn(app); + + PowerMockito.mockStatic(PortalApiProperties.class); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY)).thenReturn("Key"); + + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(CipherUtil.decryptPKC(app.getAppPassword())).thenReturn(password); + + CloseableHttpClient httpClient = PowerMockito.mock(CloseableHttpClient.class); + CloseableHttpResponse response = PowerMockito.mock(CloseableHttpResponse.class); + + PowerMockito.mockStatic(HttpClients.class); + Mockito.when(HttpClients.createDefault()).thenReturn(httpClient); + Mockito.when(httpClient.execute(Mockito.any())).thenReturn(response); + StatusLine statusLine = Mockito.mock(StatusLine.class); + Mockito.when(response.getStatusLine()).thenReturn(statusLine); + + portalRestClientBase.getRestWithCredentials(uri); + Assert.assertTrue(true); + } + + @Test(expected = IllegalArgumentException.class) + public void postRestWithCredentialsExceptionTest() throws Exception { + URI uri = PowerMockito.mock(URI.class); + String json = ""; + portalRestClientBase.postRestWithCredentials(uri,json); + Assert.assertTrue(true); + } + + @Test + public void postRestWithCredentialsWithEntityTest() throws Exception { + URI uri = PowerMockito.mock(URI.class); + + App app = new App(); + app.setUsername("User"); + String password = "Password"; + app.setAppPassword(password); + Mockito.when(appService.getDefaultApp()).thenReturn(app); + + PowerMockito.mockStatic(PortalApiProperties.class); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY)).thenReturn("Key"); + + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(CipherUtil.decryptPKC(app.getAppPassword())).thenReturn(password); + + CloseableHttpClient httpClient = PowerMockito.mock(CloseableHttpClient.class); + CloseableHttpResponse response = PowerMockito.mock(CloseableHttpResponse.class); + + PowerMockito.mockStatic(HttpClients.class); + Mockito.when(HttpClients.createDefault()).thenReturn(httpClient); + Mockito.when(httpClient.execute(Mockito.any())).thenReturn(response); + HttpEntity entity = PowerMockito.mock(HttpEntity.class); + Mockito.when(response.getEntity()).thenReturn(entity); + StatusLine statusLine = Mockito.mock(StatusLine.class); + Mockito.when(response.getStatusLine()).thenReturn(statusLine); + + String json = "JSON"; + portalRestClientBase.postRestWithCredentials(uri, json); + Assert.assertTrue(true); + } + + @Test + public void postRestWithCredentialsNullEntityTest() throws Exception { + URI uri = PowerMockito.mock(URI.class); + + App app = new App(); + app.setUsername("User"); + String password = "Password"; + app.setAppPassword(password); + Mockito.when(appService.getDefaultApp()).thenReturn(app); + + PowerMockito.mockStatic(PortalApiProperties.class); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY)).thenReturn("Key"); + + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(CipherUtil.decryptPKC(app.getAppPassword())).thenReturn(password); + + CloseableHttpClient httpClient = PowerMockito.mock(CloseableHttpClient.class); + CloseableHttpResponse response = PowerMockito.mock(CloseableHttpResponse.class); + + PowerMockito.mockStatic(HttpClients.class); + Mockito.when(HttpClients.createDefault()).thenReturn(httpClient); + Mockito.when(httpClient.execute(Mockito.any())).thenReturn(response); + StatusLine statusLine = Mockito.mock(StatusLine.class); + Mockito.when(response.getStatusLine()).thenReturn(statusLine); + + String json = "JSON"; + portalRestClientBase.postRestWithCredentials(uri, json); + Assert.assertTrue(true); + } +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/restful/client/SharedContextRestClientTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/restful/client/SharedContextRestClientTest.java new file mode 100644 index 00000000..db6cde7c --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/restful/client/SharedContextRestClientTest.java @@ -0,0 +1,307 @@ +/* + * ============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.restful.client; + +import java.util.List; + +import org.apache.http.HttpEntity; +import org.apache.http.StatusLine; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; +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.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.SharedContext; +import org.onap.portalsdk.core.scheduler.CoreRegister; +import org.onap.portalsdk.core.service.AppService; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({PortalApiProperties.class, CipherUtil.class, HttpClients.class, EntityUtils.class}) +public class SharedContextRestClientTest { + + @InjectMocks + private SharedContextRestClient sharedContextRestClient; + + @Mock + private AppService appService; + + @Test(expected = IllegalArgumentException.class) + public void getContextValueExceptionTest() throws Exception { + String contextId= "\123"; + String key = "key"; + sharedContextRestClient.getContextValue(contextId, key); + } + + @Test + public void getContextValueTest() throws Exception { + String contextId= "\123"; + String key = "key"; + + PowerMockito.mockStatic(PortalApiProperties.class); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL)).thenReturn("ResetURL/"); + + App app = new App(); + app.setUsername("User"); + String password = "Password"; + app.setAppPassword(password); + Mockito.when(appService.getDefaultApp()).thenReturn(app); + + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY)).thenReturn("Key"); + + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(CipherUtil.decryptPKC(app.getAppPassword())).thenReturn(password); + + CloseableHttpClient httpClient = PowerMockito.mock(CloseableHttpClient.class); + CloseableHttpResponse response = PowerMockito.mock(CloseableHttpResponse.class); + + PowerMockito.mockStatic(HttpClients.class); + Mockito.when(HttpClients.createDefault()).thenReturn(httpClient); + + Mockito.when(httpClient.execute(Mockito.any())).thenReturn(response); + HttpEntity entity = PowerMockito.mock(HttpEntity.class); + Mockito.when(response.getEntity()).thenReturn(entity); + + PowerMockito.mockStatic(EntityUtils.class); + String responseJson = " { \"response\": \"Success\", \"context_id\": \"200\"}"; + Mockito.when(EntityUtils.toString(entity)).thenReturn(responseJson); + StatusLine statusLine = Mockito.mock(StatusLine.class); + Mockito.when(response.getStatusLine()).thenReturn(statusLine); + SharedContext context = sharedContextRestClient.getContextValue(contextId, key); + Assert.assertNull(context); + } + + @Test + public void getUserContextTest() throws Exception { + String contextId = "234"; + + PowerMockito.mockStatic(PortalApiProperties.class); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL)).thenReturn("ResetURL/"); + + App app = new App(); + app.setUsername("User"); + String password = "Password"; + app.setAppPassword(password); + Mockito.when(appService.getDefaultApp()).thenReturn(app); + + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY)).thenReturn("Key"); + + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(CipherUtil.decryptPKC(app.getAppPassword())).thenReturn(password); + + CloseableHttpClient httpClient = PowerMockito.mock(CloseableHttpClient.class); + CloseableHttpResponse response = PowerMockito.mock(CloseableHttpResponse.class); + + PowerMockito.mockStatic(HttpClients.class); + Mockito.when(HttpClients.createDefault()).thenReturn(httpClient); + + Mockito.when(httpClient.execute(Mockito.any())).thenReturn(response); + HttpEntity entity = PowerMockito.mock(HttpEntity.class); + Mockito.when(response.getEntity()).thenReturn(entity); + + PowerMockito.mockStatic(EntityUtils.class); + String responseJson = " [ { \"response\": \"Success\", \"context_id\": \"200\"} ]"; + Mockito.when(EntityUtils.toString(entity)).thenReturn(responseJson); + StatusLine statusLine = Mockito.mock(StatusLine.class); + Mockito.when(response.getStatusLine()).thenReturn(statusLine); + + List contextList = sharedContextRestClient.getUserContext(contextId); + Assert.assertNotNull(contextList); + } + + @Test + public void checkSharedContextTest() throws Exception { + String contextId ="Context"; + String key = "Key"; + + App app = new App(); + app.setUsername("User"); + String password = "Password"; + app.setAppPassword(password); + Mockito.when(appService.getDefaultApp()).thenReturn(app); + + PowerMockito.mockStatic(PortalApiProperties.class); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL)).thenReturn("ResetURL/"); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY)).thenReturn("Key"); + + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(CipherUtil.decryptPKC(app.getAppPassword())).thenReturn(password); + + CloseableHttpClient httpClient = PowerMockito.mock(CloseableHttpClient.class); + CloseableHttpResponse response = PowerMockito.mock(CloseableHttpResponse.class); + + PowerMockito.mockStatic(HttpClients.class); + Mockito.when(HttpClients.createDefault()).thenReturn(httpClient); + + Mockito.when(httpClient.execute(Mockito.any())).thenReturn(response); + HttpEntity entity = PowerMockito.mock(HttpEntity.class); + Mockito.when(response.getEntity()).thenReturn(entity); + + PowerMockito.mockStatic(EntityUtils.class); + String responseJson = " { \"response\": \"exists\", \"context_id\": \"200\"} "; + Mockito.when(EntityUtils.toString(entity)).thenReturn(responseJson); + StatusLine statusLine = Mockito.mock(StatusLine.class); + Mockito.when(response.getStatusLine()).thenReturn(statusLine); + boolean status = sharedContextRestClient.checkSharedContext(contextId, key); + Assert.assertTrue(status); + } + + @Test + public void removeSharedContextTest() throws Exception { + String contextId ="Context"; + String key = "Key"; + + App app = new App(); + app.setUsername("User"); + String password = "Password"; + app.setAppPassword(password); + Mockito.when(appService.getDefaultApp()).thenReturn(app); + + PowerMockito.mockStatic(PortalApiProperties.class); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL)).thenReturn("ResetURL/"); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY)).thenReturn("Key"); + + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(CipherUtil.decryptPKC(app.getAppPassword())).thenReturn(password); + + CloseableHttpClient httpClient = PowerMockito.mock(CloseableHttpClient.class); + CloseableHttpResponse response = PowerMockito.mock(CloseableHttpResponse.class); + + PowerMockito.mockStatic(HttpClients.class); + Mockito.when(HttpClients.createDefault()).thenReturn(httpClient); + + Mockito.when(httpClient.execute(Mockito.any())).thenReturn(response); + HttpEntity entity = PowerMockito.mock(HttpEntity.class); + Mockito.when(response.getEntity()).thenReturn(entity); + + PowerMockito.mockStatic(EntityUtils.class); + String responseJson = " { \"response\": \"removed\", \"context_id\": \"200\"} "; + Mockito.when(EntityUtils.toString(entity)).thenReturn(responseJson); + StatusLine statusLine = Mockito.mock(StatusLine.class); + Mockito.when(response.getStatusLine()).thenReturn(statusLine); + boolean status = sharedContextRestClient.removeSharedContext(contextId, key); + Assert.assertTrue(status); + } + + @Test + public void clearSharedContextTest() throws Exception { + String contextId ="Context"; + + App app = new App(); + app.setUsername("User"); + String password = "Password"; + app.setAppPassword(password); + Mockito.when(appService.getDefaultApp()).thenReturn(app); + + PowerMockito.mockStatic(PortalApiProperties.class); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL)).thenReturn("ResetURL/"); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY)).thenReturn("Key"); + + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(CipherUtil.decryptPKC(app.getAppPassword())).thenReturn(password); + + CloseableHttpClient httpClient = PowerMockito.mock(CloseableHttpClient.class); + CloseableHttpResponse response = PowerMockito.mock(CloseableHttpResponse.class); + + PowerMockito.mockStatic(HttpClients.class); + Mockito.when(HttpClients.createDefault()).thenReturn(httpClient); + + Mockito.when(httpClient.execute(Mockito.any())).thenReturn(response); + HttpEntity entity = PowerMockito.mock(HttpEntity.class); + Mockito.when(response.getEntity()).thenReturn(entity); + + PowerMockito.mockStatic(EntityUtils.class); + int number = 123; + String responseJson = " { \"response\": " + number + " , \"context_id\": \"200\"} "; + Mockito.when(EntityUtils.toString(entity)).thenReturn(responseJson); + StatusLine statusLine = Mockito.mock(StatusLine.class); + Mockito.when(response.getStatusLine()).thenReturn(statusLine); + int status = sharedContextRestClient.clearSharedContext(contextId); + Assert.assertTrue(status == number); + } + + @Test + public void setSharedContextTest() throws Exception { + String contextId ="Context"; + String key ="Key"; + String value = "Value"; + + App app = new App(); + app.setUsername("User"); + String password = "Password"; + app.setAppPassword(password); + Mockito.when(appService.getDefaultApp()).thenReturn(app); + + PowerMockito.mockStatic(PortalApiProperties.class); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REST_URL)).thenReturn("ResetURL/"); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY)).thenReturn("Key"); + + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(CipherUtil.decryptPKC(app.getAppPassword())).thenReturn(password); + + CloseableHttpClient httpClient = PowerMockito.mock(CloseableHttpClient.class); + CloseableHttpResponse response = PowerMockito.mock(CloseableHttpResponse.class); + + PowerMockito.mockStatic(HttpClients.class); + Mockito.when(HttpClients.createDefault()).thenReturn(httpClient); + + Mockito.when(httpClient.execute(Mockito.any())).thenReturn(response); + HttpEntity entity = PowerMockito.mock(HttpEntity.class); + Mockito.when(response.getEntity()).thenReturn(entity); + + PowerMockito.mockStatic(EntityUtils.class); + String responseJson = " { \"response\": \"replaced\", \"context_id\": \"200\"} "; + Mockito.when(EntityUtils.toString(entity)).thenReturn(responseJson); + StatusLine statusLine = Mockito.mock(StatusLine.class); + Mockito.when(response.getStatusLine()).thenReturn(statusLine); + boolean status = sharedContextRestClient.setSharedContext(contextId, key, value); + Assert.assertTrue(status); + } + +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/scheduler/CoreRegisterTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/scheduler/CoreRegisterTest.java new file mode 100644 index 00000000..7959ae81 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/scheduler/CoreRegisterTest.java @@ -0,0 +1,52 @@ +/* + * ============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.scheduler; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class CoreRegisterTest { + + @Test + public void getScheduleTriggersTest(){ + CoreRegister coreRegister = new CoreRegister(); + coreRegister.setScheduleTriggers(null); + assertNull(coreRegister.getScheduleTriggers()); + } +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/service/AccessConfigurationTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/service/AccessConfigurationTest.java new file mode 100644 index 00000000..efdc3d0d --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/service/AccessConfigurationTest.java @@ -0,0 +1,95 @@ +/* + * ============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.service; + +import org.junit.Test; + +public class AccessConfigurationTest { + + AccessConfiguration accessConfiguration = new AccessConfiguration(); + + @Test + public void roleServiceImplTest(){ + accessConfiguration.roleServiceImpl(); + } + + @Test + public void roleServiceCentralizedAccessTest(){ + accessConfiguration.roleServiceCentralizedAccess(); + } + + @Test + public void loginServiceImplTest(){ + accessConfiguration.loginServiceImpl(); + } + + @Test + public void loginServiceCEntralizedImplTest(){ + accessConfiguration.loginServiceCEntralizedImpl(); + } + + @Test + public void userServiceImplTest(){ + accessConfiguration.userServiceImpl(); + } + + @Test + public void profileServiceImplTest(){ + accessConfiguration.profileServiceImpl(); + } + + @Test + public void profileServiceCentralizedImplTest(){ + accessConfiguration.profileServiceCentralizedImpl(); + } + + @Test + public void restApiRequestBuilderTest(){ + accessConfiguration.restApiRequestBuilder(); + } + + @Test + public void functionalMenuListServiceTest(){ + accessConfiguration.functionalMenuListService(); + } + + @Test + public void functionalMenuListServiceCentralizedImplTest(){ + accessConfiguration.functionalMenuListServiceCentralizedImpl(); + } +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/service/CentralAccessConditionTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/service/CentralAccessConditionTest.java new file mode 100644 index 00000000..a328033b --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/service/CentralAccessConditionTest.java @@ -0,0 +1,79 @@ +/* + * ============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.service; + +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.onboarding.util.PortalApiConstants; +import org.onap.portalsdk.core.onboarding.util.PortalApiProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.context.annotation.ConditionContext; +import org.springframework.core.type.AnnotatedTypeMetadata; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({PortalApiProperties.class}) +public class CentralAccessConditionTest { + + @InjectMocks + private CentralAccessCondition cntrlAccessCondition; + + @Test + public void matchesFalseTest() { + ConditionContext context = Mockito.mock(ConditionContext.class); + AnnotatedTypeMetadata metadata = Mockito.mock(AnnotatedTypeMetadata.class); + PowerMockito.mockStatic(PortalApiProperties.class); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED)).thenReturn(null); + boolean isRemote = cntrlAccessCondition.matches(context, metadata); + Assert.assertFalse(isRemote); + } + + @Test + public void matchesTrueTest() { + ConditionContext context = Mockito.mock(ConditionContext.class); + AnnotatedTypeMetadata metadata = Mockito.mock(AnnotatedTypeMetadata.class); + PowerMockito.mockStatic(PortalApiProperties.class); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.ROLE_ACCESS_CENTRALIZED)).thenReturn("remote"); + boolean isRemote = cntrlAccessCondition.matches(context, metadata); + Assert.assertTrue(isRemote); + } +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/service/UserProfileServiceImplTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/service/UserProfileServiceImplTest.java index f7bb3108..565142d0 100644 --- a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/service/UserProfileServiceImplTest.java +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/service/UserProfileServiceImplTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START========================================== * ONAP Portal SDK * =================================================================== - * Copyright © 2017 AT&T Intellectual Property. All rights reserved. + * Copyright © 2017 AT&T Intellectual Property. All rights reserved. * =================================================================== * * Unless otherwise specified, all software contained herein is licensed @@ -68,7 +68,15 @@ public class UserProfileServiceImplTest { Assert.assertTrue(true); } - + /*public void getUserByLoginId(){ + String loginId = "123"; + List users = new ArrayList<>(); + User user = new User(); + users.add(user); + Mockito.when(dataAccessService.getList(Mockito.any(), Mockito.any(), Mockito.anyList(), Mockito.any())).thenReturn(users); + User retrunUser = userProfileServiceImpl.getUserByLoginId(loginId); + Assert.assertNotNull(retrunUser); + }*/ @Test public void saveUserTest(){ @@ -88,4 +96,4 @@ public class UserProfileServiceImplTest { Mockito.when(mockClass.getAllUserName()).thenReturn(onlineUsers); userProfileServiceImpl.findAllUserWithOnOffline(originOrgUserId); }*/ -} +} \ No newline at end of file diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/service/UserServiceCentalizedImplTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/service/UserServiceCentalizedImplTest.java new file mode 100644 index 00000000..82b4a6e0 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/service/UserServiceCentalizedImplTest.java @@ -0,0 +1,84 @@ +/* + * ============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.service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +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.User; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +public class UserServiceCentalizedImplTest { + + @InjectMocks + private UserServiceCentalizedImpl userServiceCentalizedImpl; + + @Mock + private RestApiRequestBuilder restApiRequestBuilder; + + @Mock + private DataAccessService dataAccessService; + + @Test + public void getUserTest() throws Exception { + String id = "123"; + + String orgUserId = "123"; + List orgUsreIds = new ArrayList<>(); + orgUsreIds.add(orgUserId); + + Map params = new HashMap<>(); + params.put("user_id", new Long(id)); + Mockito.when(dataAccessService.executeNamedQuery("getUserByProfileId", params, null)).thenReturn(orgUsreIds); + String responseString = " { \"id\": 2, \"userApps\":[{\"app\":{\"id\":1},\"role\":{\"active\":true, \"roleFunctions\":[{\"id\":1}] } } ] }"; + Mockito.when(restApiRequestBuilder.getViaREST("/user/" + orgUserId, true, id)).thenReturn(responseString); + + User user = userServiceCentalizedImpl.getUser(id); + Assert.assertNotNull(user); + } + +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/service/UserServiceImplTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/service/UserServiceImplTest.java new file mode 100644 index 00000000..0cb7ac6c --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/service/UserServiceImplTest.java @@ -0,0 +1,68 @@ +/* + * ============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.service; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +public class UserServiceImplTest { + + @InjectMocks + private UserServiceImpl userServiceImpl; + + @Mock + private DataAccessService dataAccessService; + + @Test + public void getUserTest() { + String id = "123"; + userServiceImpl.getUser(id); + Assert.assertTrue(true); + } + + @Test(expected = UnsupportedOperationException.class) + public void userMapperTest() { + String response = "Dummy Response"; + userServiceImpl.userMapper(response); + } +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/service/WebServiceCallServiceImplTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/service/WebServiceCallServiceImplTest.java new file mode 100644 index 00000000..03eeea77 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/service/WebServiceCallServiceImplTest.java @@ -0,0 +1,127 @@ +/* + * ============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.service; + +import java.util.ArrayList; +import java.util.List; + +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.onboarding.util.CipherUtil; +import org.onap.portalsdk.core.util.SystemProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({CipherUtil.class, SystemProperties.class}) +public class WebServiceCallServiceImplTest { + + @InjectMocks + private WebServiceCallServiceImpl webServiceCallServiceImpl; + + @Mock + private DataAccessService dataAccessService; + + @Mock + private AppService appService; + + + @Test + public void verifyRESTCredentialTrueTest() throws Exception { + String secretKey = "Key"; + String requestAppName = "App"; + String requestPassword = "Password"; + App app = new App(); + app.setAppPassword(requestPassword); + app.setUsername(requestAppName); + Mockito.when(appService.getDefaultApp()).thenReturn(app); + PowerMockito.mockStatic(CipherUtil.class); + PowerMockito.mockStatic(SystemProperties.class); + Mockito.when(SystemProperties.getProperty(SystemProperties.Decryption_Key)).thenReturn(secretKey); + Mockito.when(CipherUtil.decryptPKC(Mockito.anyString(), Mockito.anyString())).thenReturn(requestPassword); + webServiceCallServiceImpl.verifyRESTCredential(secretKey, requestAppName, requestPassword); + Assert.assertTrue(true); + } + + @Test + public void verifyRESTCredentialFalseTest() throws Exception { + String secretKey = "Key"; + String requestAppName = "App"; + String requestPassword = "Password"; + App app = new App(); + app.setAppPassword("Password"); + app.setUsername("USER"); + Mockito.when(appService.getDefaultApp()).thenReturn(app); + PowerMockito.mockStatic(CipherUtil.class); + PowerMockito.mockStatic(SystemProperties.class); + Mockito.when(SystemProperties.getProperty(SystemProperties.Decryption_Key)).thenReturn("Key"); + Mockito.when(CipherUtil.decryptPKC(Mockito.anyString(), Mockito.anyString())).thenReturn("Key"); + webServiceCallServiceImpl.verifyRESTCredential(secretKey, requestAppName, requestPassword); + Assert.assertFalse(false); + } + + @Test + public void findAppWithNullTest() { + App app = webServiceCallServiceImpl.findApp(); + Assert.assertNull(app); + } + + @Test + public void findAppWithEmptyTest() { + Mockito.when(dataAccessService.getList(App.class, " where id = 1", null, null)).thenReturn(new ArrayList()); + App app = webServiceCallServiceImpl.findApp(); + Assert.assertNull(app); + } + + @Test + public void findAppTest() { + List list = new ArrayList(); + App app = new App(); + list.add(app); + Mockito.when(dataAccessService.getList(App.class, " where id = 1", null, null)).thenReturn(list); + App returnApp = webServiceCallServiceImpl.findApp(); + Assert.assertNotNull(returnApp); + } + +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/service/support/ServiceLocatorImplTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/service/support/ServiceLocatorImplTest.java new file mode 100644 index 00000000..53664c64 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/service/support/ServiceLocatorImplTest.java @@ -0,0 +1,60 @@ +/* + * ============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.service.support; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +public class ServiceLocatorImplTest { + + @InjectMocks + private ServiceLocatorImpl serviceLocatorImpl; + + @Test + public void getDirContextTest() { + String initialContextFactory ="Initial Context"; + String providerUrl = "URL"; + String securityPrincipal ="Security"; + serviceLocatorImpl.getDirContext(initialContextFactory, providerUrl, securityPrincipal); + Assert.assertTrue(true); + } +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/util/JSONUtilTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/util/JSONUtilTest.java new file mode 100644 index 00000000..a580b21d --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/util/JSONUtilTest.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.portalsdk.core.util; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.portalsdk.core.domain.User; + +import com.fasterxml.jackson.core.JsonProcessingException; + +public class JSONUtilTest { + + @Test + public void convertResponseToJSONTest() throws JsonProcessingException { + String response = "Response"; + String json = JSONUtil.convertResponseToJSON(response); + Assert.assertNotNull(json); + } + + @Test + public void mapToDomainUserTest() { + User editUser = new User(); + User domainUser = new User(); + editUser.setOrgId(123L); + editUser.setManagerId(123L); + editUser.setFirstName("FName"); + editUser.setMiddleInitial("FName"); + editUser.setLastName("FName"); + editUser.setPhone("FName"); + editUser.setEmail("FName"); + editUser.setHrid("FName"); + editUser.setOrgUserId("FName"); + editUser.setOrgCode("FName"); + editUser.setOrgManagerUserId("FName"); + editUser.setJobTitle("FName"); + editUser.setLoginId("FName"); + editUser.setActive(true); + domainUser = JSONUtil.mapToDomainUser(domainUser, editUser); + Assert.assertNotNull(domainUser); + } +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/util/SecurityCodecUtilTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/util/SecurityCodecUtilTest.java new file mode 100644 index 00000000..01885ce8 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/util/SecurityCodecUtilTest.java @@ -0,0 +1,79 @@ +/* + * ============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.util; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +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({SystemProperties.class}) +public class SecurityCodecUtilTest { + + @Test + public void getCodecMySqlTest() { + PowerMockito.mockStatic(SystemProperties.class); + Mockito.when(SystemProperties.getProperty(SystemProperties.DB_DRIVER)).thenReturn("mysql"); + Codec codec = SecurityCodecUtil.getCodec(); + Assert.assertNotNull(codec); + + } + + @Test + public void getCodecMariaDbTest() { + PowerMockito.mockStatic(SystemProperties.class); + Mockito.when(SystemProperties.getProperty(SystemProperties.DB_DRIVER)).thenReturn("mariadb"); + Codec codec = SecurityCodecUtil.getCodec(); + Assert.assertNotNull(codec); + + } + + @Test + public void getCodecOracleTest() { + PowerMockito.mockStatic(SystemProperties.class); + Mockito.when(SystemProperties.getProperty(SystemProperties.DB_DRIVER)).thenReturn("oracle"); + Codec codec = SecurityCodecUtil.getCodec(); + Assert.assertNotNull(codec); + + } +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/util/SystemPropertiesTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/util/SystemPropertiesTest.java new file mode 100644 index 00000000..0493c3c2 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/util/SystemPropertiesTest.java @@ -0,0 +1,72 @@ +/* + * ============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.util; + +import static org.junit.Assert.assertEquals; + +import javax.servlet.ServletContext; + +import org.junit.Test; + +public class SystemPropertiesTest { + + @Test + public void getApplicationNameTest(){ + String actualResult = ""; + SystemProperties systemProperties = new SystemProperties(); + String expectedResult = systemProperties.getApplicationName(); + assertEquals(actualResult, expectedResult); + } + + @Test + public void getAppDisplayNameTest(){ + String actualResult = ""; + SystemProperties systemProperties = new SystemProperties(); + String expectedResult = systemProperties.getAppDisplayName(); + assertEquals(actualResult, expectedResult); + } + + @Test + public void getServletContextTest(){ + ServletContext actualResult = null; + SystemProperties systemProperties = new SystemProperties(); + systemProperties.setServletContext(actualResult); + ServletContext expectedResult = systemProperties.getServletContext(); + assertEquals(actualResult, expectedResult); + } +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/util/UsageUtilsTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/util/UsageUtilsTest.java new file mode 100644 index 00000000..8fcb7123 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/util/UsageUtilsTest.java @@ -0,0 +1,114 @@ +/* + * ============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.util; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +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.command.UserRowBean; +import org.onap.portalsdk.core.domain.User; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +public class UsageUtilsTest { + + @Test + public void getActiveUsersTest() { + HttpSession mock1 = Mockito.mock(HttpSession.class); + HttpSession mock2 = Mockito.mock(HttpSession.class); + Mockito.when(mock1.getAttribute("user")).thenReturn(null); + + User user = new User(); + user.setFirstName("FName"); + user.setLastName("Lname"); + user.setId(123L); + user.setEmail("Xyz@xyz.com"); + user.setLastLoginDate(new Date()); + + Mockito.when(mock2.getCreationTime()).thenReturn(new Date().getTime()); + Mockito.when(mock2.getLastAccessedTime()).thenReturn(new Date().getTime()); + Mockito.when(mock2.getMaxInactiveInterval()).thenReturn(1000); + + Mockito.when(mock2.getAttribute("user")).thenReturn(user); + Map activeUsers = new HashMap<>(); + activeUsers.put("1", mock1); + activeUsers.put("2", mock2); + List beans = UsageUtils.getActiveUsers(activeUsers); + Assert.assertTrue(beans.size() > 0); + } + + @Test + public void getActiveUsersAfterDeleteTest(){ + + HttpSession mock1 = Mockito.mock(HttpSession.class); + HttpSession mock2 = Mockito.mock(HttpSession.class); + Mockito.when(mock1.getAttribute("user")).thenReturn(null); + + User user = new User(); + user.setFirstName("FName"); + user.setLastName("Lname"); + user.setId(123L); + user.setEmail("Xyz@xyz.com"); + user.setLastLoginDate(new Date()); + + Mockito.when(mock2.getCreationTime()).thenReturn(new Date().getTime()); + Mockito.when(mock2.getLastAccessedTime()).thenReturn(new Date().getTime()); + Mockito.when(mock2.getMaxInactiveInterval()).thenReturn(1000); + + Mockito.when(mock2.getAttribute("user")).thenReturn(user); + Map activeUsers = new HashMap<>(); + activeUsers.put("1", mock1); + activeUsers.put("2", mock2); + + UserRowBean bean = new UserRowBean(); + String beanSessionId = "1122"; + bean.setSessionId(beanSessionId); + HttpSession mock3 = Mockito.mock(HttpSession.class); + activeUsers.put(beanSessionId, mock3); + List beans = UsageUtils.getActiveUsersAfterDelete(activeUsers, bean); + Assert.assertTrue(beans.size() > 0); + } +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/web/socket/PeerBroadcastSocketTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/web/socket/PeerBroadcastSocketTest.java new file mode 100644 index 00000000..8e49ed90 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/web/socket/PeerBroadcastSocketTest.java @@ -0,0 +1,82 @@ +/* + * ============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.socket; + +import javax.websocket.RemoteEndpoint.Basic; +import javax.websocket.Session; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +public class PeerBroadcastSocketTest { + + @InjectMocks + private PeerBroadcastSocket peerBroadcastSocket; + + @Test + public void messageTest() { + String message = "{\"from\": \"to\", \"to\": \"to\"}"; + Session session = Mockito.mock(Session.class); + Basic basic = Mockito.mock(Basic.class); + Mockito.when(session.getBasicRemote()).thenReturn(basic); + Mockito.when(session.getId()).thenReturn("123"); + peerBroadcastSocket.message(message, session); + peerBroadcastSocket.close(session); + Assert.assertTrue(true); + } + + @Test + public void messageExceptionTest() { + String message = "{\"from\": \"to\", \"to\": \"to\"}"; + Session session = Mockito.mock(Session.class); + peerBroadcastSocket.message(message, session); + Assert.assertTrue(true); + } + + @Test + public void openTest() { + Session session = Mockito.mock(Session.class); + peerBroadcastSocket.open(session); + Assert.assertTrue(true); + } +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/web/socket/WebRTCSocketTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/web/socket/WebRTCSocketTest.java new file mode 100644 index 00000000..98bbdb85 --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/web/socket/WebRTCSocketTest.java @@ -0,0 +1,79 @@ +/* + * ============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.socket; + +import javax.websocket.Session; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +public class WebRTCSocketTest { + + @InjectMocks + private WebRTCSocket webRTCSocket; + + @Test + public void messageTest(){ + String message = " { \"open\": true , \"channel\": \"123\" , \"data\" : { \"sessionid\": \"123\" } }"; + Session session =Mockito.mock(Session.class); + webRTCSocket.message(message, session); + Assert.assertTrue(true); + } + + @Test + public void openTest() { + Session session =Mockito.mock(Session.class); + webRTCSocket.open(session); + Assert.assertTrue(true); + } + + @Test + public void closeTest(){ + String message = " { \"open\": true , \"channel\": \"123\" , \"data\" : { \"sessionid\": \"123\" } }"; + Session session =Mockito.mock(Session.class); + Mockito.when(session.getId()).thenReturn("1234"); + webRTCSocket.message(message, session); + webRTCSocket.close(session); + Assert.assertTrue(true); + } +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/web/support/FeedbackMessageTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/web/support/FeedbackMessageTest.java new file mode 100644 index 00000000..a5a24dec --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/web/support/FeedbackMessageTest.java @@ -0,0 +1,70 @@ +/* + * ============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 static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class FeedbackMessageTest { + + public FeedbackMessage mockFeedbackMessage(){ + FeedbackMessage feedbackMessage = new FeedbackMessage(); + + feedbackMessage.setKeyed(false); + feedbackMessage.setMessage("test"); + feedbackMessage.setMessageType(1); + + return feedbackMessage; + } + + @Test + public void feedbackMessageTest(){ + FeedbackMessage feedbackMessage1 = mockFeedbackMessage(); + + FeedbackMessage feedbackMessage = new FeedbackMessage(); + feedbackMessage.setKeyed(false); + feedbackMessage.setMessage("test"); + feedbackMessage.setMessageType(1); + + assertEquals(feedbackMessage.isKeyed(), feedbackMessage1.isKeyed()); + assertEquals(feedbackMessage.getMessage(), feedbackMessage1.getMessage()); + assertEquals(feedbackMessage.getMessageType(), feedbackMessage1.getMessageType()); + + } +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/web/support/JsonMessageTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/web/support/JsonMessageTest.java new file mode 100644 index 00000000..2600025e --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/web/support/JsonMessageTest.java @@ -0,0 +1,69 @@ +/* + * ============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 static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class JsonMessageTest { + + public JsonMessage mockJsonMessage(){ + JsonMessage jsonMessage = new JsonMessage("test", "test", "test"); + + jsonMessage.setData("test"); + jsonMessage.setData2("test"); + jsonMessage.setData3("test"); + + return jsonMessage; + } + + @Test + public void jsonMessageTest(){ + JsonMessage jsonMessage1 = new JsonMessage("test", "test", "test"); + + JsonMessage jsonMessage = new JsonMessage("test", "test", "test"); + jsonMessage.setData("test"); + jsonMessage.setData2("test"); + jsonMessage.setData3("test"); + + assertEquals(jsonMessage.getData(), jsonMessage1.getData()); + assertEquals(jsonMessage.getData2(), jsonMessage1.getData2()); + assertEquals(jsonMessage.getData3(), jsonMessage1.getData3()); + } +} diff --git a/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/web/support/MessagesListTest.java b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/web/support/MessagesListTest.java new file mode 100644 index 00000000..d0812e8c --- /dev/null +++ b/ecomp-sdk/epsdk-core/src/test/java/org/onap/portalsdk/core/web/support/MessagesListTest.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.portalsdk.core.web.support; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class MessagesListTest { + + public MessagesList mockMessagesList (){ + MessagesList messagesList = new MessagesList(); + + messagesList.setExceptionMessages(null); + messagesList.setIncludeCauseInCustomExceptions(false); + messagesList.setSuccessMessageDisplayed(false); + messagesList.setSuccessMessages(null); + + return messagesList; + } + + @Test + public void messagesListTest(){ + MessagesList messagesList1 = mockMessagesList(); + + MessagesList messagesList = new MessagesList(); + messagesList.setExceptionMessages(null); + messagesList.setIncludeCauseInCustomExceptions(false); + messagesList.setSuccessMessageDisplayed(false); + messagesList.setSuccessMessages(null); + + assertEquals(messagesList.getExceptionMessages(), messagesList1.getExceptionMessages()); + assertEquals(messagesList.getSuccessMessages(), messagesList1.getSuccessMessages()); + assertEquals(messagesList.isIncludeCauseInCustomExceptions(), messagesList1.isIncludeCauseInCustomExceptions()); + assertEquals(messagesList.isSuccessMessageDisplayed(), messagesList1.isSuccessMessageDisplayed()); + + } +} diff --git a/ecomp-sdk/epsdk-fw/src/test/java/org/onap/portalsdk/core/onboarding/crossapi/PortalRestAPIProxyTest.java b/ecomp-sdk/epsdk-fw/src/test/java/org/onap/portalsdk/core/onboarding/crossapi/PortalRestAPIProxyTest.java new file mode 100644 index 00000000..90c84032 --- /dev/null +++ b/ecomp-sdk/epsdk-fw/src/test/java/org/onap/portalsdk/core/onboarding/crossapi/PortalRestAPIProxyTest.java @@ -0,0 +1,43 @@ +/* + * ============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.onboarding.crossapi; + +//@RunWith(PowerMockRunner.class) +public class PortalRestAPIProxyTest { + +} diff --git a/ecomp-sdk/epsdk-fw/src/test/java/org/onap/portalsdk/fw/test/PortalTimeoutHandlerTest.java b/ecomp-sdk/epsdk-fw/src/test/java/org/onap/portalsdk/fw/test/PortalTimeoutHandlerTest.java index 8826237d..c10940bd 100644 --- a/ecomp-sdk/epsdk-fw/src/test/java/org/onap/portalsdk/fw/test/PortalTimeoutHandlerTest.java +++ b/ecomp-sdk/epsdk-fw/src/test/java/org/onap/portalsdk/fw/test/PortalTimeoutHandlerTest.java @@ -34,7 +34,7 @@ * ============LICENSE_END============================================ * * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ + package org.onap.portalsdk.fw.test; @@ -98,3 +98,4 @@ public class PortalTimeoutHandlerTest extends AbstractModelTest { PortalTimeoutHandler.gatherSessionExtensions(); } } +*/ \ No newline at end of file diff --git a/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalapp/framework/MockitoTestSuite.java b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalapp/framework/MockitoTestSuite.java new file mode 100644 index 00000000..baac323e --- /dev/null +++ b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalapp/framework/MockitoTestSuite.java @@ -0,0 +1,89 @@ +/*- + * ============LICENSE_START========================================== + * ONAP Portal + * =================================================================== + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * =================================================================== + * + * Unless otherwise specified, all software contained herein is licensed + * under the Apache License, Version 2.0 (the "License"); + * you may not use this software except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Unless otherwise specified, all documentation contained herein is licensed + * under the Creative Commons License, Attribution 4.0 Intl. (the "License"); + * you may not use this documentation except in compliance with the License. + * You may obtain a copy of the License at + * + * https://creativecommons.org/licenses/by/4.0/ + * + * Unless required by applicable law or agreed to in writing, documentation + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ============LICENSE_END============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.framework; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.runners.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class MockitoTestSuite { + + + public MockHttpServletRequestWrapper mockedRequest = new MockHttpServletRequestWrapper( + Mockito.mock(HttpServletRequest.class)); + public HttpServletResponse mockedResponse = Mockito.mock(HttpServletResponse.class); + + public MockHttpServletRequestWrapper getMockedRequest() { + return mockedRequest; + } + + public HttpServletResponse getMockedResponse() { + return mockedResponse; + } + + public class MockHttpServletRequestWrapper extends HttpServletRequestWrapper { + + HttpSession session = Mockito.mock(HttpSession.class); + + public MockHttpServletRequestWrapper(HttpServletRequest request) { + super(request); + + } + + @Override + public HttpSession getSession() { + + return session; + } + + @Override + public HttpSession getSession(boolean create) { + + return session; + } + + } + +} diff --git a/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/rnotebookintegration/controller/NotebookControllerTest.java b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/rnotebookintegration/controller/NotebookControllerTest.java new file mode 100644 index 00000000..bd70a321 --- /dev/null +++ b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/rnotebookintegration/controller/NotebookControllerTest.java @@ -0,0 +1,66 @@ +/* + * ============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.rnotebookintegration.controller; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.MockitoAnnotations; +import org.springframework.web.servlet.ModelAndView; + +public class NotebookControllerTest { + + @InjectMocks + NotebookController notebookController = new NotebookController(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + NullPointerException nullPointerException = new NullPointerException(); + + @Test + public void noteBookTest(){ + ModelAndView actualModelAndView = new ModelAndView(); + ModelAndView expectedModelAndView = notebookController.noteBook(); + assertEquals(expectedModelAndView.getViewName(), actualModelAndView.getViewName()); + } +} diff --git a/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/rnotebookintegration/controller/NotebookTestControllerTest.java b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/rnotebookintegration/controller/NotebookTestControllerTest.java new file mode 100644 index 00000000..6045ec75 --- /dev/null +++ b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/rnotebookintegration/controller/NotebookTestControllerTest.java @@ -0,0 +1,66 @@ +/* + * ============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.rnotebookintegration.controller; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.MockitoAnnotations; +import org.springframework.web.servlet.ModelAndView; + +public class NotebookTestControllerTest { + + @InjectMocks + NotebookTestController notebookTestController = new NotebookTestController(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + NullPointerException nullPointerException = new NullPointerException(); + + @Test + public void noteBookTest(){ + ModelAndView actualModelAndView = new ModelAndView(); + ModelAndView expectedModelAndView = notebookTestController.noteBook(); + assertEquals(expectedModelAndView.getViewName(), actualModelAndView.getViewName()); + } +} diff --git a/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/rnotebookintegration/controller/RNoteBookControllerTest.java b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/rnotebookintegration/controller/RNoteBookControllerTest.java new file mode 100644 index 00000000..62051457 --- /dev/null +++ b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/rnotebookintegration/controller/RNoteBookControllerTest.java @@ -0,0 +1,100 @@ +/* + * ============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.rnotebookintegration.controller; + +import static org.junit.Assert.*; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalsdk.rnotebookintegration.exception.RNotebookIntegrationException; +import org.onap.portalsdk.rnotebookintegration.service.RNoteBookIntegrationService; + +public class RNoteBookControllerTest { + + @InjectMocks + RNoteBookController rNoteBookController = new RNoteBookController(); + + @Mock + private RNoteBookIntegrationService rNoteBookIntegrationService; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + NullPointerException nullPointerException = new NullPointerException(); + + @Test + public void getrNoteBookIntegrationServiceTest(){ + RNoteBookIntegrationService actualRNoteBookIntegrationService = rNoteBookIntegrationService; + RNoteBookIntegrationService expectedRNoteBookIntegrationService = rNoteBookController.getrNoteBookIntegrationService(); + rNoteBookController.setrNoteBookIntegrationService(null); + assertEquals(actualRNoteBookIntegrationService, expectedRNoteBookIntegrationService); + } + + @Test + public void getRNotebookCredentialsTokenTest(){ + rNoteBookController.getRNotebookCredentials(null); + } + + @Test + public void getRNotebookCredentialsExceptionTest() throws RNotebookIntegrationException{ + Mockito.when(rNoteBookIntegrationService.getRNotebookCredentials(null)); + rNoteBookController.getRNotebookCredentials(null); + } + + @Test + public void getRNotebookCredentialsNotebookExceptionTest() throws RNotebookIntegrationException{ + RNotebookIntegrationException excp = new RNotebookIntegrationException(RNotebookIntegrationException.ERROR_CODE_TOKEN_EXPIRED); + Mockito.when(rNoteBookIntegrationService.getRNotebookCredentials("test")).thenThrow(excp); + rNoteBookController.getRNotebookCredentials("test"); + assertTrue(true); + } + + @Test + public void getRNotebookCredentialsNotebookExceptionWithoutCodeTest() throws RNotebookIntegrationException{ + RNotebookIntegrationException excp = new RNotebookIntegrationException("Test"); + Mockito.when(rNoteBookIntegrationService.getRNotebookCredentials("test")).thenThrow(excp); + rNoteBookController.getRNotebookCredentials("test"); + assertTrue(true); + } +} diff --git a/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/rnotebookintegration/controller/RNoteBookFEControllerTest.java b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/rnotebookintegration/controller/RNoteBookFEControllerTest.java new file mode 100644 index 00000000..611f41f1 --- /dev/null +++ b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/rnotebookintegration/controller/RNoteBookFEControllerTest.java @@ -0,0 +1,187 @@ +/* + * ============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.rnotebookintegration.controller; + +import static org.junit.Assert.assertEquals; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.hibernate.SessionFactory; +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; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.framework.MockitoTestSuite; +import org.onap.portalsdk.core.domain.User; +import org.onap.portalsdk.core.restful.domain.EcompUser; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.service.DataAccessServiceImpl; +import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.portalsdk.core.web.support.UserUtils; +import org.onap.portalsdk.rnotebookintegration.exception.RNotebookIntegrationException; +import org.onap.portalsdk.rnotebookintegration.service.RNoteBookIntegrationService; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.mock.web.MockHttpServletResponse; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({UserUtils.class, SystemProperties.class}) +public class RNoteBookFEControllerTest { + + @InjectMocks + RNoteBookFEController rNoteBookFEController = new RNoteBookFEController(); + + @Mock + private RNoteBookIntegrationService rNoteBookIntegrationService; + + @Mock + private SessionFactory sessionFactory; + @InjectMocks + private DataAccessServiceImpl dataAccessServiceImpl; + + @Mock + private DataAccessService dataAccessService; + + @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 getrNoteBookIntegrationServiceTest() { + RNoteBookIntegrationService actualRNoteBookIntegrationService = rNoteBookIntegrationService; + RNoteBookIntegrationService expectedRNoteBookIntegrationService = rNoteBookFEController + .getrNoteBookIntegrationService(); + rNoteBookFEController.setrNoteBookIntegrationService(null); + assertEquals(actualRNoteBookIntegrationService, expectedRNoteBookIntegrationService); + } + + @Test + public void saveRNotebookCredentialsExceptionTest() { + + String notebookId = "123"; + HttpServletRequest request = PowerMockito.mock(HttpServletRequest.class); + String value = " { \"key\" : \"value\" }" ; + + Mockito.when(request.getParameter("qparams")).thenReturn(value); + + HttpServletResponse response = new MockHttpServletResponse(); + + PowerMockito.mockStatic(UserUtils.class); + User user = new User(); + Mockito.when(UserUtils.getUserSession(request)).thenReturn(user); + Mockito.when(dataAccessService.getDomainObject(User.class, user.getId(), null)).thenReturn(user); + EcompUser ecUser = new EcompUser(); + Mockito.when(UserUtils.convertToEcompUser(user)).thenReturn(ecUser); + + PowerMockito.mockStatic(SystemProperties.class); + Mockito.when(SystemProperties.containsProperty(Mockito.anyString())).thenReturn(false); + + rNoteBookFEController.saveRNotebookCredentials(notebookId, request, response); + Assert.assertTrue(true); + } + + @Test + public void saveRNotebookCredentialsTest() { + + String notebookId = "123"; + HttpServletRequest request = PowerMockito.mock(HttpServletRequest.class); + String value = " { \"key\" : \"value\" }" ; + + Mockito.when(request.getParameter("qparams")).thenReturn(value); + + HttpServletResponse response = new MockHttpServletResponse(); + + PowerMockito.mockStatic(UserUtils.class); + User user = new User(); + Mockito.when(UserUtils.getUserSession(request)).thenReturn(user); + Mockito.when(dataAccessService.getDomainObject(User.class, user.getId(), null)).thenReturn(user); + EcompUser ecUser = new EcompUser(); + Mockito.when(UserUtils.convertToEcompUser(user)).thenReturn(ecUser); + + PowerMockito.mockStatic(SystemProperties.class); + Mockito.when(SystemProperties.containsProperty(Mockito.anyString())).thenReturn(true); + + rNoteBookFEController.saveRNotebookCredentials(notebookId, request, response); + Assert.assertTrue(true); + } + + @Test + public void saveRNotebookCredentialsCustExceptionTest() { + + String notebookId = "123"; + HttpServletRequest request = PowerMockito.mock(HttpServletRequest.class); + String value = " { \"key\" : \"value\" }" ; + + Mockito.when(request.getParameter("qparams")).thenReturn(value); + + HttpServletResponse response = new MockHttpServletResponse(); + + PowerMockito.mockStatic(UserUtils.class); + User user = new User(); + Mockito.when(UserUtils.getUserSession(request)).thenThrow(RNotebookIntegrationException.class); + Mockito.when(dataAccessService.getDomainObject(User.class, user.getId(), null)).thenReturn(user); + EcompUser ecUser = new EcompUser(); + Mockito.when(UserUtils.convertToEcompUser(user)).thenReturn(ecUser); + + PowerMockito.mockStatic(SystemProperties.class); + Mockito.when(SystemProperties.containsProperty(Mockito.anyString())).thenReturn(true); + + rNoteBookFEController.saveRNotebookCredentials(notebookId, request, response); + Assert.assertTrue(true); + } + +} diff --git a/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/rnotebookintegration/domain/RNoteBookCredentialsTest.java b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/rnotebookintegration/domain/RNoteBookCredentialsTest.java new file mode 100644 index 00000000..12dc1e69 --- /dev/null +++ b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/rnotebookintegration/domain/RNoteBookCredentialsTest.java @@ -0,0 +1,85 @@ +/* + * ============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.rnotebookintegration.domain; + +import org.junit.Assert; +import org.junit.Test; + +public class RNoteBookCredentialsTest { + + public RNoteBookCredentials mockRNoteBookCredentials(){ + RNoteBookCredentials rNoteBookCredentials = new RNoteBookCredentials(); + + rNoteBookCredentials.setUserInfo(null); + rNoteBookCredentials.setToken("test"); + rNoteBookCredentials.setCreated(null); + rNoteBookCredentials.setCreatedDate(null); + rNoteBookCredentials.setNotebookID("test"); + rNoteBookCredentials.setParameters(null); + rNoteBookCredentials.setTokenReadDate(null); + rNoteBookCredentials.setUserString("test"); + rNoteBookCredentials.setParametersString("test"); + + return rNoteBookCredentials; + } + + @Test + public void rNoteBookCredentialsTest(){ + RNoteBookCredentials rNoteBookCredentials1 = mockRNoteBookCredentials(); + + RNoteBookCredentials rNoteBookCredentials = new RNoteBookCredentials(); + rNoteBookCredentials.setUserInfo(null); + rNoteBookCredentials.setToken("test"); + rNoteBookCredentials.setCreated(null); + rNoteBookCredentials.setNotebookID("test"); + rNoteBookCredentials.setParameters(null); + rNoteBookCredentials.setTokenReadDate(null); + rNoteBookCredentials.setUserString("test"); + rNoteBookCredentials.setParametersString("test"); + + Assert.assertEquals(rNoteBookCredentials.getUserInfo(), rNoteBookCredentials1.getUserInfo()); + Assert.assertEquals(rNoteBookCredentials.getToken(), rNoteBookCredentials1.getToken()); + Assert.assertEquals(rNoteBookCredentials.getCreated(), rNoteBookCredentials1.getCreated()); + Assert.assertEquals(rNoteBookCredentials.getCreatedDate(), rNoteBookCredentials1.getCreatedDate()); + Assert.assertEquals(rNoteBookCredentials.getNotebookID(), rNoteBookCredentials1.getNotebookID()); + Assert.assertEquals(rNoteBookCredentials.getParameters(), rNoteBookCredentials1.getParameters()); + Assert.assertEquals(rNoteBookCredentials.getTokenReadDate(), rNoteBookCredentials1.getTokenReadDate()); + Assert.assertEquals(rNoteBookCredentials.getUserString(), rNoteBookCredentials1.getUserString()); + Assert.assertEquals(rNoteBookCredentials.getParametersString(), rNoteBookCredentials1.getParametersString()); + } +} diff --git a/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/rnotebookintegration/service/RNoteBookIntegrationServiceImplTest.java b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/rnotebookintegration/service/RNoteBookIntegrationServiceImplTest.java new file mode 100644 index 00000000..2a2cfed0 --- /dev/null +++ b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/rnotebookintegration/service/RNoteBookIntegrationServiceImplTest.java @@ -0,0 +1,141 @@ +/* + * ============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.rnotebookintegration.service; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +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.restful.domain.EcompUser; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.rnotebookintegration.domain.RNoteBookCredentials; +import org.onap.portalsdk.rnotebookintegration.exception.RNotebookIntegrationException; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +public class RNoteBookIntegrationServiceImplTest { + + @InjectMocks + private RNoteBookIntegrationServiceImpl rnoteBookIntgrServiceImpl; + + @Mock + private DataAccessService dataAccessService; + + @Test(expected = RNotebookIntegrationException.class) + public void getRNotebookCredentialsNullTokenTest() throws Exception { + String token = "Token"; + RNoteBookCredentials rnoteBookCredentials = new RNoteBookCredentials(); + Mockito.when(dataAccessService.getDomainObject(RNoteBookCredentials.class, token, new HashMap())).thenReturn(rnoteBookCredentials); + rnoteBookIntgrServiceImpl.getRNotebookCredentials(token); + } + + @Test(expected = RNotebookIntegrationException.class) + public void getRNotebookCredentialsEmptyTokenTest() throws Exception { + String token = "Token"; + RNoteBookCredentials rnoteBookCredentials = new RNoteBookCredentials(); + rnoteBookCredentials.setToken(""); + Mockito.when(dataAccessService.getDomainObject(RNoteBookCredentials.class, token, new HashMap())).thenReturn(rnoteBookCredentials); + rnoteBookIntgrServiceImpl.getRNotebookCredentials(token); + } + + @Test(expected = RNotebookIntegrationException.class) + public void getRNotebookCredentialsDateTest() throws Exception { + String token = "Token"; + RNoteBookCredentials rnoteBookCredentials = new RNoteBookCredentials(); + rnoteBookCredentials.setToken("123"); + rnoteBookCredentials.setCreatedDate(new Date()); + rnoteBookCredentials.setTokenReadDate(new Date()); + Mockito.when(dataAccessService.getDomainObject(RNoteBookCredentials.class, token, new HashMap())).thenReturn(rnoteBookCredentials); + rnoteBookIntgrServiceImpl.getRNotebookCredentials(token); + } + + @Test + public void getRNotebookCredentialsTest() throws Exception { + String token = "Token"; + RNoteBookCredentials rnoteBookCredentials = new RNoteBookCredentials(); + String json = " { \"managerId\": \"123\", \"firstName\": \"FNAME\" }"; + rnoteBookCredentials.setToken("123"); + rnoteBookCredentials.setCreatedDate(new Date()); + rnoteBookCredentials.setUserString(json); + + String mapJson = " { \"managerId\": \"123\", \"firstName\": \"FNAME\" }"; + rnoteBookCredentials.setParametersString(mapJson); + Mockito.when(dataAccessService.getDomainObject(RNoteBookCredentials.class, token, new HashMap())).thenReturn(rnoteBookCredentials); + String response = rnoteBookIntgrServiceImpl.getRNotebookCredentials(token); + Assert.assertNotNull(response); + } + + @Test + public void getRNotebookCredentialsJsonTest() throws Exception { + String token = "Token"; + RNoteBookCredentials rnoteBookCredentials = new RNoteBookCredentials(); + String json = " { \"managerId\": \"123\", test }"; + rnoteBookCredentials.setToken("123"); + rnoteBookCredentials.setCreatedDate(new Date()); + rnoteBookCredentials.setUserString(json); + + rnoteBookCredentials.setParametersString(json); + Mockito.when(dataAccessService.getDomainObject(RNoteBookCredentials.class, token, new HashMap())).thenReturn(rnoteBookCredentials); + String response = rnoteBookIntgrServiceImpl.getRNotebookCredentials(token); + Assert.assertNotNull(response); + } + + @Test(expected = RNotebookIntegrationException.class) + public void getRNotebookCredentialsExpTest() throws Exception { + String token = "Token"; + Mockito.when(dataAccessService.getDomainObject(RNoteBookCredentials.class, token, new HashMap())).thenReturn(null); + rnoteBookIntgrServiceImpl.getRNotebookCredentials(token); + } + + @Test + public void saveRNotebookCredentialsTest() throws Exception { + String notebookId = "123"; + EcompUser user = new EcompUser(); + Map params = new HashMap<>(); + params.put("Key","VALUE"); + String token = rnoteBookIntgrServiceImpl.saveRNotebookCredentials(notebookId, user, params); + Assert.assertNotNull(token); + } + +} diff --git a/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/controllers/WorkflowControllerTest.java b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/controllers/WorkflowControllerTest.java new file mode 100644 index 00000000..65b2554b --- /dev/null +++ b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/controllers/WorkflowControllerTest.java @@ -0,0 +1,193 @@ +/* + * ============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.workflow.controllers; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +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.User; +import org.onap.portalsdk.workflow.models.Workflow; +import org.onap.portalsdk.workflow.models.WorkflowLite; +import org.onap.portalsdk.workflow.services.WorkflowService; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +@RunWith(PowerMockRunner.class) +public class WorkflowControllerTest { + + @InjectMocks + private WorkflowController workflowController; + + @Mock + private WorkflowService workflowService; + + @Test + public void saveCronJob() throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest(); + + HttpServletResponse response = new MockHttpServletResponse(); + + workflowController.saveCronJob(request, response); + Assert.assertTrue(true); + } + + @Test + public void getWorkflowListTest() { + + List workflows = new ArrayList<>(); + Workflow wfl = new Workflow(); + + wfl.setId(123L); + wfl.setName("Test"); + wfl.setDescription("Testing"); + wfl.setActive(Boolean.TRUE); + wfl.setCreated(new Date()); + User user = new User(); + user.setFirstName("FNAME"); + user.setLastName("LNAME"); + + wfl.setCreatedBy(user); + wfl.setModifiedBy(user); + wfl.setLastUpdated(new Date()); + wfl.setWorkflowKey("KEY"); + wfl.setRunLink("RLINK"); + wfl.setSuspendLink("SLINK"); + + workflows.add(wfl); + Mockito.when(workflowService.getAllWorkflows()).thenReturn(workflows); + + String respone = workflowController.getWorkflowList(); + Assert.assertNotNull(respone); + } + + @Test + public void getWorkflowListEmptyTest() { + + List workflows = new ArrayList<>(); + Workflow wfl = new Workflow(); + + wfl.setId(123L); + wfl.setName("Test"); + wfl.setDescription("Testing"); + wfl.setActive(Boolean.TRUE); + wfl.setCreated(new Date()); + + wfl.setCreatedBy(null); + wfl.setModifiedBy(null); + wfl.setLastUpdated(null); + wfl.setWorkflowKey("KEY"); + wfl.setRunLink("RLINK"); + wfl.setSuspendLink("SLINK"); + + workflows.add(wfl); + Mockito.when(workflowService.getAllWorkflows()).thenReturn(workflows); + + String respone = workflowController.getWorkflowList(); + Assert.assertNotNull(respone); + } + + @Test + public void getWorkflowListNullTest() { + Mockito.when(workflowService.getAllWorkflows()).thenReturn(null); + String respone = workflowController.getWorkflowList(); + Assert.assertNotNull(respone); + } + + @Test + public void addWorkflowTest() { + Workflow workflow = new Workflow(); + HttpServletRequest request = PowerMockito.mock(HttpServletRequest.class); + HttpSession mockSession = PowerMockito.mock(HttpSession.class); + Mockito.when(request.getSession()).thenReturn(mockSession); + + User user = new User(); + user.setLoginId("123"); + Mockito.when(mockSession.getAttribute("user")).thenReturn(user); + + workflowController.addWorkflow(workflow, request); + Assert.assertTrue(true); + } + + @Test + public void editWorkflowTest() { + WorkflowLite workflow = new WorkflowLite(); + HttpServletRequest request = PowerMockito.mock(HttpServletRequest.class); + HttpSession mockSession = PowerMockito.mock(HttpSession.class); + Mockito.when(request.getSession()).thenReturn(mockSession); + + User user = new User(); + user.setLoginId("123"); + Mockito.when(mockSession.getAttribute("user")).thenReturn(user); + + workflowController.editWorkflow(workflow, request); + Assert.assertTrue(true); + } + + @Test + public void removeWorkflowTest() { + Long workflowId = 123L; + HttpServletRequest request = new MockHttpServletRequest(); + HttpServletResponse response = new MockHttpServletResponse(); + workflowController.removeWorkflow(workflowId, request, response); + Assert.assertTrue(true); + } + + @Test(expected = UnsupportedOperationException.class) + public void removeAllWorkflows() { + workflowController.removeAllWorkflows(); + } + + @Test + public void getWorkflowPartialPageTest(){ + workflowController.getWorkflowPartialPage(); + Assert.assertTrue(true); + } +} diff --git a/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/dao/WorkflowDAOImplTest.java b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/dao/WorkflowDAOImplTest.java new file mode 100644 index 00000000..2dfa14c2 --- /dev/null +++ b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/dao/WorkflowDAOImplTest.java @@ -0,0 +1,168 @@ +/* + * ============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.workflow.dao; + +import java.util.ArrayList; +import java.util.List; + +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +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.User; +import org.onap.portalsdk.workflow.models.Workflow; +import org.onap.portalsdk.workflow.models.WorkflowLite; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +public class WorkflowDAOImplTest { + + @InjectMocks + private WorkflowDAOImpl workflowDAOImpl; + + @Mock + private SessionFactory sessionFactory; + + @Test + public void saveTest() { + Workflow workflow = new Workflow(); + String creatorId = "123"; + Session session = PowerMockito.mock(Session.class); + Mockito.when(sessionFactory.openSession()).thenReturn(session); + Transaction tx = PowerMockito.mock(Transaction.class); + Mockito.when(session.beginTransaction()).thenReturn(tx); + + Query query = PowerMockito.mock(Query.class); + Mockito.when(session.createQuery("from User where loginId =:loginId")).thenReturn(query); + User user = new User(); + List list = new ArrayList<>(); + list.add(user); + Mockito.when(query.list()).thenReturn(list); + + Mockito.when(session.save(workflow)).thenReturn(1L); + Mockito.when(session.get(Workflow.class, 1l)).thenReturn(workflow); + + Workflow savedWorkflow = workflowDAOImpl.save(workflow, creatorId); + + Assert.assertNotNull(savedWorkflow); + } + + @Test + public void saveTestException() { + Workflow workflow = new Workflow(); + String creatorId = "123"; + Session session = PowerMockito.mock(Session.class); + Mockito.when(sessionFactory.openSession()).thenReturn(session); + Transaction tx = PowerMockito.mock(Transaction.class); + Mockito.when(session.beginTransaction()).thenReturn(tx); + + Query query = PowerMockito.mock(Query.class); + Mockito.when(session.createQuery("from User where loginId =:loginId")).thenReturn(query); + List list = new ArrayList<>(); + Mockito.when(query.list()).thenReturn(list); + + Mockito.when(session.save(workflow)).thenReturn(1L); + Mockito.when(session.get(Workflow.class, 1l)).thenReturn(workflow); + + Workflow savedWorkflow = workflowDAOImpl.save(workflow, creatorId); + + Assert.assertNotNull(savedWorkflow); + } + + @Test + public void getWorkflowsTest() { + + Session session = PowerMockito.mock(Session.class); + Mockito.when(sessionFactory.openSession()).thenReturn(session); + + List workflows = new ArrayList<>(); + Workflow workflow = new Workflow(); + workflow.setId(1L); + workflows.add(workflow); + + Query query = PowerMockito.mock(Query.class); + Mockito.when(session.createQuery("from Workflow")).thenReturn(query); + Mockito.when(query.list()).thenReturn(workflows); + + List list = workflowDAOImpl.getWorkflows(); + Assert.assertTrue(!list.isEmpty()); + } + + @Test + public void deleteTest() { + Long workflowId = 1L; + Session session = PowerMockito.mock(Session.class); + Mockito.when(sessionFactory.openSession()).thenReturn(session); + Transaction tx = PowerMockito.mock(Transaction.class); + Mockito.when(session.beginTransaction()).thenReturn(tx); + Query query = PowerMockito.mock(Query.class); + Mockito.when(session.createQuery("delete from Workflow where id =:id")).thenReturn(query); + workflowDAOImpl.delete(workflowId); + Assert.assertTrue(true); + } + + @Test + public void editTest() { + WorkflowLite workflowLight = new WorkflowLite(); + String creatorId = "1234"; + + Session session = PowerMockito.mock(Session.class); + Mockito.when(sessionFactory.openSession()).thenReturn(session); + Transaction tx = PowerMockito.mock(Transaction.class); + Mockito.when(session.beginTransaction()).thenReturn(tx); + Query query = PowerMockito.mock(Query.class); + Mockito.when(session.createQuery("from User where loginId =:loginId")).thenReturn(query); + + User user = new User(); + List list = new ArrayList<>(); + list.add(user); + Mockito.when(query.list()).thenReturn(list); + + Mockito.when(session.get(Workflow.class, workflowLight.getId())).thenReturn(new Workflow()); + + Workflow savedWorkflow = workflowDAOImpl.edit(workflowLight, creatorId); + Assert.assertNotNull(savedWorkflow); + } +} diff --git a/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/domain/WorkflowScheduleTest.java b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/domain/WorkflowScheduleTest.java new file mode 100644 index 00000000..4ff0f4fc --- /dev/null +++ b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/domain/WorkflowScheduleTest.java @@ -0,0 +1,87 @@ +/* + * ============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.workflow.domain; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class WorkflowScheduleTest { + + public WorkflowSchedule mockWorkflowSchedule(){ + WorkflowSchedule workflowSchedule = new WorkflowSchedule(); + + workflowSchedule.setId((long) 1); + workflowSchedule.setServerUrl("test"); + workflowSchedule.setWorkflowKey("test"); + workflowSchedule.setArguments("test"); + workflowSchedule.setCronDetails("test"); + workflowSchedule.setEndDateTime(null); + workflowSchedule.setStartDateTime(null); + workflowSchedule.setRecurrence("test"); + + return workflowSchedule; + } + + @SuppressWarnings("static-access") + @Test + public void workflowScheduleTest(){ + WorkflowSchedule workflowSchedule1 = mockWorkflowSchedule(); + + WorkflowSchedule workflowSchedule = new WorkflowSchedule(); + workflowSchedule.setId((long) 1); + workflowSchedule.setServerUrl("test"); + workflowSchedule.setWorkflowKey("test"); + workflowSchedule.setArguments("test"); + workflowSchedule.setCronDetails("test"); + workflowSchedule.setEndDateTime(null); + workflowSchedule.setStartDateTime(null); + workflowSchedule.setRecurrence("test"); + + + assertEquals(workflowSchedule.getId(), workflowSchedule1.getId()); + assertEquals(workflowSchedule.getServerUrl(), workflowSchedule1.getServerUrl()); + assertEquals(workflowSchedule.getWorkflowKey(), workflowSchedule1.getWorkflowKey()); + assertEquals(workflowSchedule.getArguments(), workflowSchedule1.getArguments()); + assertEquals(workflowSchedule.getCronDetails(), workflowSchedule1.getCronDetails()); + assertEquals(workflowSchedule.getEndDateTime(), workflowSchedule1.getEndDateTime()); + assertEquals(workflowSchedule.getStartDateTime(), workflowSchedule1.getStartDateTime()); + assertEquals(workflowSchedule.getRecurrence(), workflowSchedule1.getRecurrence()); + assertEquals(workflowSchedule.getSerialversionuid(), workflowSchedule1.getSerialversionuid()); + } +} diff --git a/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/models/WorkflowLiteTest.java b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/models/WorkflowLiteTest.java new file mode 100644 index 00000000..e8d3667e --- /dev/null +++ b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/models/WorkflowLiteTest.java @@ -0,0 +1,110 @@ +/* + * ============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.workflow.models; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class WorkflowLiteTest { + + public WorkflowLite mockWorkflowLite(){ + WorkflowLite workflowLite = new WorkflowLite(); + + workflowLite.setId((long) 1); + workflowLite.setName("test"); + workflowLite.setWorkflowKey("test"); + workflowLite.setDescription("test"); + workflowLite.setCreated("test"); + workflowLite.setCreatedBy("test"); + workflowLite.setModifiedBy("test"); + workflowLite.setLastUpdated("test"); + workflowLite.setActive("test"); + workflowLite.setRunLink("test"); + workflowLite.setSuspendLink("test"); + workflowLite.setModifiedLink("test"); + + return workflowLite; + } + + @Test + public void workflowLiteTest(){ + WorkflowLite workflowLite1 = mockWorkflowLite(); + + WorkflowLite workflowLite = new WorkflowLite(); + + workflowLite.setId((long) 1); + workflowLite.setName("test"); + workflowLite.setWorkflowKey("test"); + workflowLite.setDescription("test"); + workflowLite.setCreated("test"); + workflowLite.setCreatedBy("test"); + workflowLite.setModifiedBy("test"); + workflowLite.setLastUpdated("test"); + workflowLite.setActive("test"); + workflowLite.setRunLink("test"); + workflowLite.setSuspendLink("test"); + workflowLite.setModifiedLink("test"); + + assertEquals(workflowLite.getId(), workflowLite1.getId()); + assertEquals(workflowLite.getName(), workflowLite1.getName()); + assertEquals(workflowLite.getWorkflowKey(), workflowLite1.getWorkflowKey()); + assertEquals(workflowLite.getDescription(), workflowLite1.getDescription()); + assertEquals(workflowLite.getCreated(), workflowLite1.getCreated()); + assertEquals(workflowLite.getCreatedBy(), workflowLite1.getCreatedBy()); + assertEquals(workflowLite.getModifiedBy(), workflowLite1.getModifiedBy()); + assertEquals(workflowLite.getLastUpdated(), workflowLite1.getLastUpdated()); + assertEquals(workflowLite.getActive(), workflowLite1.getActive()); + assertEquals(workflowLite.getRunLink(), workflowLite1.getRunLink()); + assertEquals(workflowLite.getSuspendLink(), workflowLite1.getSuspendLink()); + assertEquals(workflowLite.getModifiedLink(), workflowLite1.getModifiedLink()); + } + + @Test + public void hashCodeTest(){ + WorkflowLite workflowLite = mockWorkflowLite(); + assertNotNull(workflowLite.hashCode()); + } + + @Test + public void equalsTest(){ + WorkflowLite workflowLite = mockWorkflowLite(); + WorkflowLite workflowLite1 = new WorkflowLite(); + assertEquals(false, workflowLite.equals(workflowLite1)); + } +} diff --git a/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/models/WorkflowTest.java b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/models/WorkflowTest.java new file mode 100644 index 00000000..c0e988e1 --- /dev/null +++ b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/models/WorkflowTest.java @@ -0,0 +1,110 @@ +/* + * ============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.workflow.models; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.onap.portalsdk.core.domain.support.NameValueId; + +public class WorkflowTest { + + public Workflow mockWorkflow(){ + Workflow workflow = new Workflow(); + + workflow.setId((long) 1); + workflow.setName("test"); + workflow.setWorkflowKey("test"); + workflow.setDescription("test"); + workflow.setCreated(null); + workflow.setCreatedBy(null); + workflow.setLastUpdated(null); + workflow.setModifiedBy(null); + workflow.setActive(false); + workflow.setRunLink("test"); + workflow.setSuspendLink("test"); + workflow.setModifiedLink("test"); + + return workflow; + } + + @Test + public void workflowTest(){ + Workflow workflow1 = mockWorkflow(); + + Workflow workflow = new Workflow(); + workflow.setId((long) 1); + workflow.setName("test"); + workflow.setWorkflowKey("test"); + workflow.setDescription("test"); + workflow.setCreated(null); + workflow.setCreatedBy(null); + workflow.setLastUpdated(null); + workflow.setModifiedBy(null); + workflow.setActive(false); + workflow.setRunLink("test"); + workflow.setSuspendLink("test"); + workflow.setModifiedLink("test"); + + assertEquals(workflow.getId(), workflow1.getId()); + assertEquals(workflow.getName(), workflow1.getName()); + assertEquals(workflow.getWorkflowKey(), workflow1.getWorkflowKey()); + assertEquals(workflow.getDescription(), workflow1.getDescription()); + assertEquals(workflow.getCreated(), workflow1.getCreated()); + assertEquals(workflow.getCreatedBy(), workflow1.getCreatedBy()); + assertEquals(workflow.getLastUpdated(), workflow1.getLastUpdated()); + assertEquals(workflow.getModifiedBy(), workflow1.getModifiedBy()); + assertEquals(workflow.getActive(), workflow1.getActive()); + assertEquals(workflow.getRunLink(), workflow1.getRunLink()); + assertEquals(workflow.getSuspendLink(), workflow1.getSuspendLink()); + assertEquals(workflow.getModifiedLink(), workflow1.getModifiedLink()); + } + + @Test + public void hashCodeTest(){ + Workflow workflow1 = mockWorkflow(); + assertNotNull(workflow1.hashCode()); + } + + @Test + public void equalsTest(){ + Workflow workflow1 = mockWorkflow(); + Workflow workflow = new Workflow(); + assertEquals(false, workflow.equals(workflow1)); + } +} diff --git a/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/scheduler/WorkFlowScheduleJobTest.java b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/scheduler/WorkFlowScheduleJobTest.java new file mode 100644 index 00000000..2bcd4235 --- /dev/null +++ b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/scheduler/WorkFlowScheduleJobTest.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.portalsdk.workflow.scheduler; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.powermock.modules.junit4.PowerMockRunner; +import org.quartz.JobDataMap; +import org.quartz.JobExecutionContext; + +@RunWith(PowerMockRunner.class) +public class WorkFlowScheduleJobTest { + + @InjectMocks + private WorkFlowScheduleJob workFlowScheduleJob; + + @Test(expected = RuntimeException.class) + public void executeInternalTest() throws Exception { + JobExecutionContext context = Mockito.mock(JobExecutionContext.class); + JobDataMap jobMap = Mockito.mock(JobDataMap.class); + Mockito.when(context.getMergedJobDataMap()).thenReturn(jobMap); + Mockito.when(jobMap.get("serverUrl")).thenReturn("URL"); + Mockito.when(jobMap.get("workflowKey")).thenReturn("Workflow"); + workFlowScheduleJob.executeInternal(context); + } +} diff --git a/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/scheduler/WorkFlowScheduleRegistryTest.java b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/scheduler/WorkFlowScheduleRegistryTest.java new file mode 100644 index 00000000..8a33aec3 --- /dev/null +++ b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/scheduler/WorkFlowScheduleRegistryTest.java @@ -0,0 +1,99 @@ +/* + * ============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.workflow.scheduler; + +import java.text.ParseException; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mockito; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.quartz.JobDetail; +import org.quartz.JobKey; +import org.springframework.scheduling.quartz.JobDetailFactoryBean; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({JobKey.class}) +public class WorkFlowScheduleRegistryTest { + + @InjectMocks + private WorkFlowScheduleRegistry workFlowScheduleRegistry; + + @Test + public void jobDetailFactoryBeanTest() { + Map contextInfoMap = new HashMap<>(); + JobDetailFactoryBean jobDetailFactory = workFlowScheduleRegistry.jobDetailFactoryBean(contextInfoMap); + Assert.assertNotNull(jobDetailFactory); + } + + @Test(expected = IllegalArgumentException.class) + public void cronTriggerFactoryBeanTest() throws Exception { + JobDetailFactoryBean jobDetailFactory = PowerMockito.mock(JobDetailFactoryBean.class); + JobDetail mockObj = PowerMockito.mock(JobDetail.class); + JobKey keyObj = PowerMockito.mock(JobKey.class); + + Mockito.when(jobDetailFactory.getObject()).thenReturn(mockObj); + Mockito.when(mockObj.getKey()).thenReturn(keyObj); + Mockito.when(keyObj.getName()).thenReturn("Test"); + Long id = 123L; + String cronExpression = "0 * * * * ? *"; + Date startDateTime = new Date(); + Date enddatetime = new Date(); + + workFlowScheduleRegistry.cronTriggerFactoryBean(jobDetailFactory, id, cronExpression, startDateTime, enddatetime); + } + + @Test(expected = ParseException.class) + public void setUpTriggerTest() throws Exception { + Long wfId = 123L; + String serverUrl = "URL"; + String workflowKey = "Key"; + String arguments =""; + String startdatetimecron = "today"; + Date startDateTime = new Date(); + Date enddatetime = new Date(); + workFlowScheduleRegistry.setUpTrigger(wfId, serverUrl, workflowKey, arguments, startdatetimecron, startDateTime, enddatetime); + } +} diff --git a/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/services/WorkflowScheduleServiceImplTest.java b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/services/WorkflowScheduleServiceImplTest.java new file mode 100644 index 00000000..846a994b --- /dev/null +++ b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/services/WorkflowScheduleServiceImplTest.java @@ -0,0 +1,115 @@ +/* + * ============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.workflow.services; + +import java.util.ArrayList; +import java.util.List; + +import org.hibernate.SessionFactory; +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.service.DataAccessService; +import org.onap.portalsdk.workflow.dao.WorkflowDAO; +import org.onap.portalsdk.workflow.domain.WorkflowSchedule; +import org.onap.portalsdk.workflow.scheduler.WorkFlowScheduleRegistry; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.context.ApplicationContext; + + +@RunWith(PowerMockRunner.class) +public class WorkflowScheduleServiceImplTest { + + @Mock + private SessionFactory sessionFactory; + + @Mock + private WorkflowDAO workflowDAO; + + @Mock + private WorkflowScheduleService workflowScheduleService; + + @Mock + private WorkFlowScheduleRegistry workflowRegistry; + + @Mock + private ApplicationContext appContext; + + @Mock + private DataAccessService dataAccessService; + + @InjectMocks + private WorkflowScheduleServiceImpl workflowScheduleServiceImpl; + + @Test + public void findAllTest(){ + workflowScheduleServiceImpl.findAll(); + Assert.assertTrue(true); + } + + @Test + public void saveWorkflowScheduleTest(){ + WorkflowSchedule ws = new WorkflowSchedule(); + workflowScheduleServiceImpl.saveWorkflowSchedule(ws); + Assert.assertTrue(true); + } + + @Test + public void triggerWorkflowSchedulingTest() { + WorkflowSchedule ws = new WorkflowSchedule(); + + List allWorkflows = new ArrayList<>(); + allWorkflows.add(ws); + Mockito.when(dataAccessService.executeQuery(Mockito.anyString(), Mockito.anyMap())).thenReturn(allWorkflows); + + workflowScheduleServiceImpl.triggerWorkflowScheduling(); + Assert.assertTrue(true); + } + + @Test + public void getWorkflowScheduleByKey() { + Long key = 123L; + WorkflowSchedule ws = new WorkflowSchedule(); + Mockito.when(dataAccessService.getDomainObject(WorkflowSchedule.class, key, null)).thenReturn(ws); + WorkflowSchedule workflowSchedule = workflowScheduleServiceImpl.getWorkflowScheduleByKey(key); + Assert.assertNotNull(workflowSchedule); + } +} diff --git a/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/services/WorkflowServiceImplTest.java b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/services/WorkflowServiceImplTest.java new file mode 100644 index 00000000..ce884d90 --- /dev/null +++ b/ecomp-sdk/epsdk-workflow/src/test/java/org/onap/portalsdk/workflow/services/WorkflowServiceImplTest.java @@ -0,0 +1,92 @@ +/* + * ============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.workflow.services; + +import org.hibernate.SessionFactory; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.onap.portalsdk.workflow.dao.WorkflowDAO; +import org.onap.portalsdk.workflow.domain.WorkflowSchedule; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +public class WorkflowServiceImplTest { + + @Mock + private SessionFactory sessionFactory; + + @Mock + private WorkflowDAO workflowDAO; + + @Mock + private WorkflowScheduleService workflowScheduleService; + + @InjectMocks + private WorkflowServiceImpl workflowServiceImpl; + + @Test + public void saveCronJobTest(){ + WorkflowSchedule workflowSchedule = new WorkflowSchedule(); + // mockedSession = Mockito.mock(Session.class); + // Mockito.when(sessionFactory.getCurrentSession()).thenReturn(mockedSession); + // Mockito.when(mockedSession.get(DomainVo.class, id)).thenReturn(domainVo); + workflowServiceImpl.saveCronJob(workflowSchedule); + } + + @Test + public void addWorkflowTest(){ + workflowServiceImpl.addWorkflow(null, null); + } + + @Test + public void editWorkflowTest(){ + workflowServiceImpl.editWorkflow(null, null); + } + + @Test + public void deleteWorkflowTest(){ + workflowServiceImpl.deleteWorkflow(null); + } + + @Test + public void getAllWorkflowsTest(){ + workflowServiceImpl.getAllWorkflows(); + } +} diff --git a/ecomp-sdk/pom.xml b/ecomp-sdk/pom.xml index a06b22db..39e04dde 100644 --- a/ecomp-sdk/pom.xml +++ b/ecomp-sdk/pom.xml @@ -307,13 +307,13 @@ The IDs MUST match Jenkins template values. --> releases - OpenECOMP - Release Repository + ONAP - Release Repository ${nexusproxy}/${releaseNexusPath} snapshots - OpenECOMP - Snapshot Repository + ONAP - Snapshot Repository ${nexusproxy}/${snapshotNexusPath} diff --git a/version.properties b/version.properties index 663379d3..dd5fdaca 100644 --- a/version.properties +++ b/version.properties @@ -3,8 +3,8 @@ # because they are used in Jenkins, whose plug-in doesn't support # -major=1 -minor=4 +major=2 +minor=2 patch=0 base_version=${major}.${minor}.${patch} -- cgit 1.2.3-korg