From adb6bb038280a707060bbf411c48b86e34a3d9b1 Mon Sep 17 00:00:00 2001 From: Mukesh Paliwal Date: Tue, 21 Jun 2022 10:50:23 +0530 Subject: CodeCoverage improvement for dcaegen2-collectors-restconf Issue-ID: DCAEGEN2-3166 Signed-off-by: Mukesh Paliwal Change-Id: Ife1fafc0349297d2012c665c45e28aff4c34ba73 --- .../publishing/MessageRouterHttpStatusMapper.java | 4 +- .../dcae/controller/PersistentEventConnection.java | 26 ++-- .../org/onap/dcae/ApplicationExceptionTest.java | 14 ++- .../java/org/onap/dcae/common/HttpMethodTest.java | 39 ++++++ .../java/org/onap/dcae/common/XmlParserTest.java | 20 ++-- .../common/publishing/DMaaPEventPublisherTest.java | 15 +++ .../MessageRouterHttpStatusMapperTest.java | 45 +++++++ .../onap/dcae/controller/AccessControllerTest.java | 81 +++++++++++++ .../org/onap/dcae/controller/ConfigLoaderTest.java | 63 ++++++++++ .../org/onap/dcae/controller/ConversionTest.java | 55 +++++++++ .../org/onap/dcae/controller/EnvPropsTest.java | 34 +++++- .../controller/PersistentEventConnectionTest.java | 131 +++++++++++++++++++++ src/test/resources/testTemplatefile | 35 +++--- 13 files changed, 513 insertions(+), 49 deletions(-) create mode 100644 src/test/java/org/onap/dcae/common/HttpMethodTest.java create mode 100644 src/test/java/org/onap/dcae/controller/AccessControllerTest.java create mode 100644 src/test/java/org/onap/dcae/controller/ConfigLoaderTest.java create mode 100644 src/test/java/org/onap/dcae/controller/ConversionTest.java create mode 100644 src/test/java/org/onap/dcae/controller/PersistentEventConnectionTest.java diff --git a/src/main/java/org/onap/dcae/common/publishing/MessageRouterHttpStatusMapper.java b/src/main/java/org/onap/dcae/common/publishing/MessageRouterHttpStatusMapper.java index 4806127..ba11d84 100755 --- a/src/main/java/org/onap/dcae/common/publishing/MessageRouterHttpStatusMapper.java +++ b/src/main/java/org/onap/dcae/common/publishing/MessageRouterHttpStatusMapper.java @@ -77,12 +77,12 @@ public class MessageRouterHttpStatusMapper { } @NotNull - private static String resolveHttpCode(MessageRouterPublishResponse messageRouterPublishResponse) { + static String resolveHttpCode(MessageRouterPublishResponse messageRouterPublishResponse) { return Objects.requireNonNull(messageRouterPublishResponse.failReason()).substring(0, 3); } @NotNull - private static ApiException responseBody(String substring) { + static ApiException responseBody(String substring) { switch (substring) { case "404": return ApiException.NOT_FOUND; diff --git a/src/main/java/org/onap/dcae/controller/PersistentEventConnection.java b/src/main/java/org/onap/dcae/controller/PersistentEventConnection.java index 3b16360..98be6c3 100644 --- a/src/main/java/org/onap/dcae/controller/PersistentEventConnection.java +++ b/src/main/java/org/onap/dcae/controller/PersistentEventConnection.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * org.onap.dcaegen2.collectors.restconf * ================================================================================ - * Copyright (C) 2018-2021 Huawei. All rights reserved. + * Copyright (C) 2018-2022 Huawei. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,14 +20,14 @@ package org.onap.dcae.controller; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; import org.glassfish.jersey.media.sse.EventSource; import org.glassfish.jersey.media.sse.SseFeature; -import org.json.JSONArray; -import org.json.JSONObject; -import org.onap.dcae.common.*; +import org.onap.dcae.common.EventConnectionState; +import org.onap.dcae.common.RestConfContext; +import org.onap.dcae.common.AdditionalHeaderWebTarget; +import org.onap.dcae.common.DataChangeEventListener; +import org.onap.dcae.common.Constants; +import org.onap.dcae.common.Parameters; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -42,16 +42,16 @@ import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.HttpHeaders; -import java.security.KeyManagementException; import java.security.KeyStore; -import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Base64; import java.util.HashMap; import java.util.Map; -import static org.onap.dcae.common.RestapiCallNodeUtil.*; +import static org.onap.dcae.common.RestapiCallNodeUtil.getUriMethod; +import static org.onap.dcae.common.RestapiCallNodeUtil.getParameters; +import static org.onap.dcae.common.RestapiCallNodeUtil.addAuthType; public class PersistentEventConnection implements Runnable { private String event_name; @@ -156,7 +156,7 @@ public class PersistentEventConnection implements Runnable { } - private PersistentEventConnection(PersistentEventConnectionBuilder builder){ + public PersistentEventConnection(PersistentEventConnectionBuilder builder){ this.event_name = builder.event_name; this.event_description = builder.event_description; @@ -234,7 +234,7 @@ public class PersistentEventConnection implements Runnable { log.info("Closed connection to SSE source"); } - private void subscribe() { + public void subscribe() { try { modifyEventParamMap(Constants.KSETTING_REST_API_URL, getUriMethod(parentCtrllr.getProperties().authorizationEnabled()) + parentCtrllr.getCfgInfo().getController_restapiUrl() @@ -265,7 +265,7 @@ public class PersistentEventConnection implements Runnable { log.info("SSE received url " + event_sseventsUrl); } - private EventSource OpenSseConnection() throws Exception { + public EventSource OpenSseConnection() throws Exception { Parameters p = null; try { diff --git a/src/test/java/org/onap/dcae/ApplicationExceptionTest.java b/src/test/java/org/onap/dcae/ApplicationExceptionTest.java index 289c472..98edbe4 100644 --- a/src/test/java/org/onap/dcae/ApplicationExceptionTest.java +++ b/src/test/java/org/onap/dcae/ApplicationExceptionTest.java @@ -20,18 +20,24 @@ package org.onap.dcae; +import org.apache.commons.configuration.ConfigurationException; import org.junit.Test; -import javax.naming.ConfigurationException; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; public class ApplicationExceptionTest { @Test public void TestApplicationException() { - Exception ex = new Exception(); ConfigurationException confEx = new ConfigurationException(); - ApplicationException example = new ApplicationException("Exception"); + ApplicationException example3 = new ApplicationException(confEx); + Exception ex = new Exception(); ApplicationException example1 = new ApplicationException("Exception", ex); ApplicationException example2 = new ApplicationException(ex); - ApplicationException example3 = new ApplicationException(confEx); + ApplicationException example = new ApplicationException("Exception"); + assertTrue(example3.getMessage().contains("ConfigurationException")); + assertEquals(example1.getMessage(), "Exception"); + assertEquals(example2.getMessage(), "java.lang.Exception"); + assertEquals(example.getMessage(), "Exception"); } } diff --git a/src/test/java/org/onap/dcae/common/HttpMethodTest.java b/src/test/java/org/onap/dcae/common/HttpMethodTest.java new file mode 100644 index 0000000..2553ef9 --- /dev/null +++ b/src/test/java/org/onap/dcae/common/HttpMethodTest.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2022 Huawei. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.dcae.common; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class HttpMethodTest { + @Test + public void fromStringTest () throws Exception { + assertEquals(HttpMethod.GET, HttpMethod.fromString("get")); + assertEquals(HttpMethod.POST, HttpMethod.fromString("post")); + assertEquals(HttpMethod.PUT, HttpMethod.fromString("put")); + assertEquals(HttpMethod.PATCH, HttpMethod.fromString("patch")); + assertEquals(HttpMethod.DELETE, HttpMethod.fromString("delete")); + assertNull(null, HttpMethod.fromString(null)); + assertThrows(IllegalArgumentException.class,()->HttpMethod.fromString("test")); + } +} diff --git a/src/test/java/org/onap/dcae/common/XmlParserTest.java b/src/test/java/org/onap/dcae/common/XmlParserTest.java index 5ca80c0..ee4cf21 100644 --- a/src/test/java/org/onap/dcae/common/XmlParserTest.java +++ b/src/test/java/org/onap/dcae/common/XmlParserTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * org.onap.dcaegen2.restconfcollector * ================================================================================ - * Copyright (C) 2018-2019 Huawei. All rights reserved. + * Copyright (C) 2018-2022 Huawei. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,21 +25,19 @@ import java.util.Map; import java.util.Set; import org.junit.Test; +import static org.junit.Assert.assertEquals; + public class XmlParserTest { @Test - public void setAttribute() { - String convert = "\n" + public void setAttribute() throws Exception { + String convert = "\n" + "t2\n" - + "200"; + + "200"; Set listNameList = new HashSet<>(); listNameList.add("result"); Map propMap; - try { - propMap = XmlParser.convertToProperties(convert, listNameList); - System.out.println(propMap); - } catch (Exception e) { - System.out.println("Exception " + e); - } + propMap = XmlParser.convertToProperties(convert, listNameList); + assertEquals("200", propMap.get("root.status")); } -} \ No newline at end of file +} diff --git a/src/test/java/org/onap/dcae/common/publishing/DMaaPEventPublisherTest.java b/src/test/java/org/onap/dcae/common/publishing/DMaaPEventPublisherTest.java index 4ea6482..2a138b2 100644 --- a/src/test/java/org/onap/dcae/common/publishing/DMaaPEventPublisherTest.java +++ b/src/test/java/org/onap/dcae/common/publishing/DMaaPEventPublisherTest.java @@ -72,4 +72,19 @@ public class DMaaPEventPublisherTest { dMaaPEventPublisher.sendEvent(jo,"test"); assertEquals("test", publisherCache.get()._1); } + + @Test + public void sendEventclosePublisherTest () throws Exception { + List destination = List.of("test"); + PublisherConfig publisherConfig = new PublisherConfig(destination, "Test", "test", + "test123"); + DMaaPPublishersCache.CambriaPublishersCacheLoader publishersCache = + Mockito.mock(DMaaPPublishersCache.CambriaPublishersCacheLoader.class); + Map publisherCache = HashMap.of("test", publisherConfig); + publisherCache.put("test", publisherConfig); + DMaaPEventPublisher dMaaPEventPublisher = new DMaaPEventPublisher(publisherCache); + JSONObject jo = null; + dMaaPEventPublisher.sendEvent(jo,"test"); + assertEquals("test", publisherCache.get()._1); + } } diff --git a/src/test/java/org/onap/dcae/common/publishing/MessageRouterHttpStatusMapperTest.java b/src/test/java/org/onap/dcae/common/publishing/MessageRouterHttpStatusMapperTest.java index 12f0479..ce1d22c 100644 --- a/src/test/java/org/onap/dcae/common/publishing/MessageRouterHttpStatusMapperTest.java +++ b/src/test/java/org/onap/dcae/common/publishing/MessageRouterHttpStatusMapperTest.java @@ -22,15 +22,20 @@ package org.onap.dcae.common.publishing; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; +import org.onap.dcae.restapi.ApiException; import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.MessageRouterPublishResponse; import org.springframework.http.HttpStatus; import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.onap.dcae.ApplicationSettings.responseCompatibility; import static org.onap.dcae.common.publishing.MessageRouterHttpStatusMapper.getHttpStatus; +import static org.onap.dcae.common.publishing.MessageRouterHttpStatusMapper.resolveHttpCode; +import static org.onap.dcae.common.publishing.MessageRouterHttpStatusMapper.responseBody; class MessageRouterHttpStatusMapperTest { @@ -51,6 +56,20 @@ class MessageRouterHttpStatusMapperTest { assertSame(HttpStatus.ACCEPTED, httpStatusResponse); } + @Test + void shouldResponse202Test() { + //given + responseCompatibility = BACKWARDS_COMPATIBILITY; + MessageRouterPublishResponse messageRouterPublishResponse = mock(MessageRouterPublishResponse.class); + when(messageRouterPublishResponse.successful()).thenReturn(true); + + //when + HttpStatus httpStatusResponse = getHttpStatus(messageRouterPublishResponse); + + //then + assertSame(HttpStatus.ACCEPTED, httpStatusResponse); + } + @Test void shouldResponse200WhenBackwardsCompatibilityIsNone() { //given @@ -81,4 +100,30 @@ class MessageRouterHttpStatusMapperTest { //then assertThrows(RuntimeException.class,()->getHttpStatus(messageRouterPublishResponse)); } + + @Test + public void responseBodyTest () throws Exception { + ApiException result = responseBody("404"); + assertEquals(404, result.httpStatusCode); + result = responseBody("408"); + assertEquals(408, result.httpStatusCode); + result = responseBody("429"); + assertEquals(429, result.httpStatusCode); + result = responseBody("502"); + assertEquals(502, result.httpStatusCode); + result = responseBody("503"); + assertEquals(503, result.httpStatusCode); + result = responseBody("504"); + assertEquals(504, result.httpStatusCode); + result = responseBody("test"); + assertEquals(500, result.httpStatusCode); + } + + @Test + public void resolveHttpCodeTest () throws Exception { + MessageRouterPublishResponse messageRouterPublishResponse = mock(MessageRouterPublishResponse.class); + when(messageRouterPublishResponse.failReason()).thenReturn("error code"); + String result = resolveHttpCode(messageRouterPublishResponse); + assertNotNull(result); + } } diff --git a/src/test/java/org/onap/dcae/controller/AccessControllerTest.java b/src/test/java/org/onap/dcae/controller/AccessControllerTest.java new file mode 100644 index 0000000..42d3d7f --- /dev/null +++ b/src/test/java/org/onap/dcae/controller/AccessControllerTest.java @@ -0,0 +1,81 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2022 Huawei. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.dcae.controller; + +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.when; + +import java.nio.file.Path; +import java.nio.file.Paths; +import org.json.JSONObject; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.dcae.ApplicationSettings; +import org.onap.dcae.common.RestConfContext; + + +@RunWith(MockitoJUnitRunner.Silent.class) +public class AccessControllerTest { + + @Mock + private ApplicationSettings properties; + + @Mock + private RestConfContext ctx; + + protected static final Path RESOURCES = Paths.get("src", "test", "resources"); + protected static final Path KEYSTORE = Paths.get(RESOURCES.toString(), "keystore"); + protected static final Path KEYSTORE_PASSWORD_FILE = Paths.get(RESOURCES.toString(), "passwordfile"); + protected static final Path TRUSTSTORE = Paths.get(RESOURCES.toString(), "truststore"); + protected static final Path TRUSTSTORE_PASSWORD_FILE = Paths.get(RESOURCES.toString(), "trustpasswordfile"); + protected static final Path RCC_KEYSTORE_PASSWORD_FILE = Paths.get(RESOURCES.toString(), "rcc_passwordfile"); + protected static final Path RCC_KEYSTORE = Paths.get(RESOURCES.toString(), "sdnc.p12"); + protected static final Path DMAAP_FILE = Paths.get(RESOURCES.toString(), "testDmaapConfig_ip.json"); + @Test + public void createAndGetAccessControler() throws Exception { + when(properties.truststoreFileLocation()).thenReturn(TRUSTSTORE.toString()); + when(properties.truststorePasswordFileLocation()).thenReturn(TRUSTSTORE_PASSWORD_FILE.toString()); + when(properties.keystoreFileLocation()).thenReturn(KEYSTORE.toString()); + when(properties.keystorePasswordFileLocation()).thenReturn(KEYSTORE_PASSWORD_FILE.toString()); + when(properties.rccKeystoreFileLocation()).thenReturn(RCC_KEYSTORE.toString()); + when(properties.rccKeystorePasswordFileLocation()).thenReturn(RCC_KEYSTORE_PASSWORD_FILE.toString()); + when(properties.dMaaPConfigurationFileLocation()).thenReturn(DMAAP_FILE.toString()); + + JSONObject controller = new JSONObject("{\"controller_name\":\"AccessM&C\",\"controller_restapiUrl\":" + + "\"10.118.191.43:26335\",\"controller_restapiUser\":\"access\",\"controller_restapiPassword\":" + + "\"Huawei@123\",\"controller_accessTokenUrl\":\"/rest/plat/smapp/v1/oauth/token\"," + + "\"controller_accessTokenFile\":\"./etc/access-token.json\",\"controller_accessTokenMethod\"" + + ":\"put\",\"controller_subsMethod\":\"post\",\"controller_subscriptionUrl\":" + + "\"/restconf/v1/operations/huawei-nce-notification-action:establish-subscription\"," + + "\"controller_disableSsl\":\"true\",\"event_details\":[{\"event_name\":\"ONT_registration\"," + + "\"event_description\":\"ONTregistartionevent\",\"event_sseventUrlEmbed\":\"true\"," + + "\"event_sseventsField\":\"output.url\",\"event_sseventsUrl\":\"null\"," + + "\"event_subscriptionTemplate\":\"./etc/ont_registartion_subscription_template.json\"," + + "\"event_unSubscriptionTemplate\":\"./etc/ont_registartion_unsubscription_template.json\"," + + "\"event_ruleId\":\"777777777\"}]}"); + AccessController acClr = new AccessController(controller, + properties); + acClr.setExecutor(null); + int acClrHashCode = acClr.hashCode(); + assertNotNull(acClrHashCode); + } +} diff --git a/src/test/java/org/onap/dcae/controller/ConfigLoaderTest.java b/src/test/java/org/onap/dcae/controller/ConfigLoaderTest.java new file mode 100644 index 0000000..6e37d7a --- /dev/null +++ b/src/test/java/org/onap/dcae/controller/ConfigLoaderTest.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2022 Huawei. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.dcae.controller; + +import org.json.JSONObject; +import org.junit.Test; +import org.onap.dcae.WiremockBasedTest; +import org.onap.dcae.common.publishing.EventPublisher; + +import java.nio.file.Path; +import java.nio.file.Paths; + +import static io.vavr.API.Map; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.mock; +import static org.onap.dcae.TestingUtilities.createTemporaryFile; +import static org.onap.dcae.TestingUtilities.readJsonFromFile; +import static org.onap.dcae.common.publishing.VavrUtils.f; + +public class ConfigLoaderTest extends WiremockBasedTest { + @Test + public void shouldNotReconfigureNotOverwriteIfConfigurationHasNotChanged() throws Exception { + + Path dmaapConfigFile = createTemporaryFile("temp_dmaapConfigFile", "{}"); + Path collectorPropertiesFile = createTemporaryFile("temp_collectorPropertiesFile", ""); + JSONObject dmaapConf = readJsonFromFile( + Paths.get("src/test/resources/testParseDMaaPCredentialsGen2.json")); + stubConsulToReturnLocalAddressOfCbs(); + stubCbsToReturnAppConfig(f("{\"collector.port\": 8080, \"streams_publishes\": %s}}", dmaapConf)); + EventPublisher eventPublisherMock = mock(EventPublisher.class); + ConfigFilesFacade configFilesFacade = new ConfigFilesFacade(dmaapConfigFile, collectorPropertiesFile); + configFilesFacade.writeProperties(Map("collector.port", "8080")); + configFilesFacade.writeDMaaPConfiguration(dmaapConf); + + ConfigLoader configLoader = new ConfigLoader(eventPublisherMock::reconfigure, + configFilesFacade, ConfigSource::getAppConfig, () -> wiremockBasedEnvProps()); + + // when + JSONObject dmaapConf2 = readJsonFromFile( + Paths.get("src/test/resources/testParseDMaaPCredentialsGen2Temp.json")); + configFilesFacade.writeDMaaPConfiguration(dmaapConf2); + configFilesFacade.writeProperties(Map("collector.port", "8081")); + configLoader = configLoader.create(null, dmaapConfigFile, collectorPropertiesFile ); + assertNotNull(configLoader); + } +} diff --git a/src/test/java/org/onap/dcae/controller/ConversionTest.java b/src/test/java/org/onap/dcae/controller/ConversionTest.java new file mode 100644 index 0000000..65ec6fb --- /dev/null +++ b/src/test/java/org/onap/dcae/controller/ConversionTest.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2022 Huawei. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.dcae.controller; + +import io.vavr.collection.List; +import io.vavr.control.Try; +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Iterator; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class ConversionTest implements Conversions { + @Test + public void toJsonTest () throws Exception { + Try jo = Conversions.toJson("{\"name\":\"Test\",\"description\":\"description\"}"); + jo.onSuccess(value -> assertEquals(value.get("name"), "Test")); + } + + @Test + public void toJsonArrayTest () throws Exception { + Try jo = Conversions.toJsonArray("[{\"name\":\"Test\",\"description\":\"description\"}]"); + jo.onSuccess(value -> assertTrue(value.get(0).toString().contains("Test"))); + } + + @Test + public void toListTest () throws Exception { + ArrayList al = new ArrayList(); + al.add("Test"); + Iterator itr = al.iterator(); + List jo = Conversions.toList(itr); + assertEquals(jo.get(0), "Test"); + } +} diff --git a/src/test/java/org/onap/dcae/controller/EnvPropsTest.java b/src/test/java/org/onap/dcae/controller/EnvPropsTest.java index 1276e6b..b6086a2 100644 --- a/src/test/java/org/onap/dcae/controller/EnvPropsTest.java +++ b/src/test/java/org/onap/dcae/controller/EnvPropsTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * org.onap.dcaegen2.restconfcollector * ================================================================================ - * Copyright (C) 2018-2019 Huawei. All rights reserved. + * Copyright (C) 2018-2022 Huawei. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,7 @@ package org.onap.dcae.controller; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertEquals; import com.github.tomakehurst.wiremock.junit.WireMockRule; @@ -41,4 +42,33 @@ public class EnvPropsTest { .equals(new EnvProps("http", "localhost", wireMockRule.port(), "http", "CBSName", "restconfcollector")), true); } -} \ No newline at end of file + + @Test + public void fromStringTest() { + assertEquals(new EnvProps("http", "localhost", wireMockRule.port(), + "http", "CBSName", "restconfcollector") + .equals(null), false); + } + + @Test + public void fromStringSameObjTest() { + EnvProps envProps = new EnvProps("http", "localhost", wireMockRule.port(), + "http", "CBSName", "restconfcollector"); + assertEquals(envProps.equals(envProps), true); + } + + @Test + public void toStringTest() { + String envProps = new EnvProps("http", "localhost", wireMockRule.port(), + "http", "CBSName", "restconfcollector").toString(); + String str = "EnvProps{consulProtocol='http', consulHost='localhost', consulPort="+wireMockRule.port()+", cbsProtocol='http', cbsName='CBSName', appName='restconfcollector'}"; + assertEquals(envProps, str); + } + + @Test + public void hashCodeTest() { + int envHashCode = new EnvProps("http", "localhost", wireMockRule.port(), + "http", "CBSName", "restconfcollector").hashCode(); + assertNotNull(envHashCode); + } +} diff --git a/src/test/java/org/onap/dcae/controller/PersistentEventConnectionTest.java b/src/test/java/org/onap/dcae/controller/PersistentEventConnectionTest.java new file mode 100644 index 0000000..fed0b8e --- /dev/null +++ b/src/test/java/org/onap/dcae/controller/PersistentEventConnectionTest.java @@ -0,0 +1,131 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2022 Huawei. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.dcae.controller; + +import org.json.JSONObject; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.dcae.ApplicationSettings; +import org.onap.dcae.common.RestConfContext; +import org.onap.dcae.common.RestapiCallNode; + +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Map; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.Silent.class) +public class PersistentEventConnectionTest { + + @Mock + private ApplicationSettings properties; + + + protected static final Path RESOURCES = Paths.get("src", "test", "resources"); + protected static final Path KEYSTORE = Paths.get(RESOURCES.toString(), "keystore"); + protected static final Path KEYSTORE_PASSWORD_FILE = Paths.get(RESOURCES.toString(), "passwordfile"); + protected static final Path TRUSTSTORE = Paths.get(RESOURCES.toString(), "truststore"); + protected static final Path TRUSTSTORE_PASSWORD_FILE = Paths.get(RESOURCES.toString(), "trustpasswordfile"); + protected static final Path RCC_KEYSTORE_PASSWORD_FILE = Paths.get(RESOURCES.toString(), "rcc_passwordfile"); + protected static final Path RCC_KEYSTORE = Paths.get(RESOURCES.toString(), "sdnc.p12"); + + @Test + public void runTest() throws Exception { + when(properties.truststoreFileLocation()).thenReturn(TRUSTSTORE.toString()); + when(properties.truststorePasswordFileLocation()).thenReturn(TRUSTSTORE_PASSWORD_FILE.toString()); + when(properties.keystoreFileLocation()).thenReturn(KEYSTORE.toString()); + when(properties.keystorePasswordFileLocation()).thenReturn(KEYSTORE_PASSWORD_FILE.toString()); + when(properties.rccKeystoreFileLocation()).thenReturn(RCC_KEYSTORE.toString()); + when(properties.rccKeystorePasswordFileLocation()).thenReturn(RCC_KEYSTORE_PASSWORD_FILE.toString()); + when(properties.controllerConfigFileLocation()) + .thenReturn(Paths.get("etc/ont_config.json").toAbsolutePath().toString()); + + RestapiCallNode restApiCallNode = Mockito.mock(RestapiCallNode.class); + Mockito.doNothing().when(restApiCallNode).sendRequest(any(), any(), any()); + + JSONObject controller = new JSONObject( + "{\"controller_name\":\"AccessM&C\",\"controller_restapiUrl\":\"10.118.191.43:26335\"," + + "\"controller_restapiUser\":\"access\",\"controller_restapiPassword\":\"Huawei@123\"," + + "\"controller_accessTokenUrl\":\"/rest/plat/smapp/v1/oauth/token\"," + + "\"controller_accessTokenFile\":\"./etc/access-token.json\"," + + "\"controller_accessTokenMethod\":\"put\",\"controller_subsMethod\":\"post\"," + + "\"controller_subscriptionUrl\":" + + "\"/restconf/v1/operations/huawei-nce-notification-action:establish-subscription\"," + + "\"controller_disableSsl\":\"true\",\"event_details\":[{\"event_name\":" + + "\"ONT_registration\",\"event_description\":\"ONTregistartionevent\"," + + "\"event_sseventUrlEmbed\":\"true\",\"event_sseventsField\":\"output.url\"," + + "\"event_sseventsUrl\":\"null\"," + + "\"event_subscriptionTemplate\":\"./etc/ont_registartion_subscription_template.json\"," + + "\"event_unSubscriptionTemplate\":" + + "\"./etc/ont_registartion_unsubscription_template.json\"," + + "\"event_ruleId\":\"777777777\"}]}"); + AccessController acClr = new AccessController(controller, properties); + + + PersistentEventConnection perEvtConnBuild = + new PersistentEventConnection.PersistentEventConnectionBuilder().setEventName("test_event") + .setEventDescription("test_description").setEventRuleId("1234646346") + .setEventSseventsField("test").setEventSseventsUrl("test") + .setEventSseventUrlEmbed(true).setEventSubscriptionTemplate("test") + .setEventUnSubscriptionTemplate("test").setParentCtrllr(acClr) + .setModifyEvent(true).setModifyMethod("modifyOntEvent") + .setUserData("remote_id=AC9.0234.0337;svlan=1001;macAddress=00:11:22:33:44:55;") + .createPersistentEventConnection(); + perEvtConnBuild.modifyEventParamMap("restapiUrl", "10.118.191.43:26335"); + assertNotNull(perEvtConnBuild); + + String evtParamVal = perEvtConnBuild.getEventParamMapValue("restapiUrl"); + assertEquals("10.118.191.43:26335", evtParamVal); + + perEvtConnBuild.subscribe(); + perEvtConnBuild.OpenSseConnection(); + + String evtRuleId = perEvtConnBuild.getEventRuleId(); + assertEquals("1234646346", evtRuleId); + + String modifyMethod = perEvtConnBuild.getModifyMethod(); + assertEquals("modifyOntEvent", modifyMethod); + + AccessController parentCtrl = perEvtConnBuild.getParentCtrllr(); + assertNotNull(parentCtrl); + + String userData = perEvtConnBuild.getUserData(); + assertEquals("remote_id=AC9.0234.0337;svlan=1001;macAddress=00:11:22:33:44:55;", userData); + + RestConfContext contextData = perEvtConnBuild.getCtx(); + assertNotNull(contextData); + + Map evtParaMap = perEvtConnBuild.getEventParaMap(); + assertNotNull("10.118.191.43:26335", evtParaMap.get("restapiUrl")); + + perEvtConnBuild.shutdown(); + + boolean isModify = perEvtConnBuild.isModifyEvent(); + assertTrue(isModify); + } +} diff --git a/src/test/resources/testTemplatefile b/src/test/resources/testTemplatefile index 8ce08dd..cd3eacd 100755 --- a/src/test/resources/testTemplatefile +++ b/src/test/resources/testTemplatefile @@ -1,18 +1,19 @@ -${ - "input": { - "encoding": "encode-json", - "protocol": "sse", - "subscription" : [ - { - "topic" : "resources", - "object-type-infos" : [ - { - "object-type" : "onu", - "version" : "v1" - } - ], - "operation" : ["create"] - } - ] +${repeat: { + "input": { + "encoding": "encode-json", + "protocol": "sse", + "subscription" : [ + { + "topic" : "resources", + "object-type-infos" : [ + { + "object-type" : "onu", + "version" : "v1" + } + ], + "operation" : ["create"] + } + ] + } } -} \ No newline at end of file +} -- cgit 1.2.3-korg