From be11dee889f5a740d584458b62804e5fd4296e53 Mon Sep 17 00:00:00 2001 From: s00370346 Date: Thu, 14 Mar 2019 15:06:40 +0530 Subject: Issue-ID: DCAEGEN2-1055 Generic RestConfCollector Change-Id: I1800affa2b34cbb7487c0d8411e078adec5a0c48 Signed-off-by: s00370346 --- .../java/org/onap/dcae/AccessControllerTest.java | 114 +++++++ src/test/java/org/onap/dcae/AnyNodeTest.java | 64 ++++ .../org/onap/dcae/ApplicationSettingsTest.java | 337 +++++++++++++++++++++ src/test/java/org/onap/dcae/CLIUtilsTest.java | 58 ++++ src/test/java/org/onap/dcae/TLSTest.java | 94 ++++++ src/test/java/org/onap/dcae/TLSTestBase.java | 154 ++++++++++ src/test/java/org/onap/dcae/TestingUtilities.java | 141 +++++++++ src/test/java/org/onap/dcae/WiremockBasedTest.java | 68 +++++ .../collectors/restconf/common/AuthTypeTest.java | 42 --- .../collectors/restconf/common/FormatTest.java | 40 --- .../restconf/common/RestConfContextTest.java | 52 ---- .../restconf/common/RetryPolicyStoreTest.java | 63 ---- .../restconf/common/RetryPolicyTest.java | 57 ---- .../publishing/DMaaPConfigurationParserTest.java | 111 ------- .../event/publishing/DMaaPEventPublisherTest.java | 78 ----- .../event/publishing/DMaaPPublishersCacheTest.java | 93 ------ .../common/event/publishing/JsonParserTest.java | 38 --- .../restconf/restconftest/AnyNodeTest.java | 62 ---- .../restconf/restconftest/RestConfProcTest.java | 79 ----- .../restconf/restconftest/SseResource.java | 69 ----- .../restconftest/TestRestConfCollector.java | 66 ---- .../org/onap/dcae/common/ApiExceptionTest.java | 54 ++++ .../java/org/onap/dcae/common/AuthTypeTest.java | 42 +++ .../dcae/common/DataChangeEventListnerTest.java | 69 +++++ .../onap/dcae/common/EventConnectionStateTest.java | 40 +++ .../org/onap/dcae/common/EventProcessorTest.java | 104 +++++++ src/test/java/org/onap/dcae/common/FormatTest.java | 40 +++ .../org/onap/dcae/common/RestConfContextTest.java | 52 ++++ .../java/org/onap/dcae/common/XmlJsonUtilTest.java | 81 +++++ .../java/org/onap/dcae/common/XmlParserTest.java | 46 +++ .../common/publishing/DMaaPEventPublisherTest.java | 79 +++++ .../publishing/DMaaPPublishersCacheTest.java | 127 ++++++++ .../dcae/common/publishing/JsonParserTest.java | 38 +++ .../onap/dcae/controller/ConfigCBSSourceTest.java | 151 +++++++++ .../dcae/controller/ConfigFilesFacadeTest.java | 140 +++++++++ .../controller/ConfigLoaderIntegrationE2ETest.java | 98 ++++++ .../onap/dcae/controller/ConfigParsingTest.java | 79 +++++ .../dcae/controller/EnvPropertiesReaderTest.java | 69 +++++ .../org/onap/dcae/controller/EnvPropsTest.java | 41 +++ .../onap/dcae/restapi/ApiAuthInterceptionTest.java | 177 +++++++++++ 40 files changed, 2557 insertions(+), 850 deletions(-) create mode 100644 src/test/java/org/onap/dcae/AccessControllerTest.java create mode 100644 src/test/java/org/onap/dcae/AnyNodeTest.java create mode 100644 src/test/java/org/onap/dcae/ApplicationSettingsTest.java create mode 100644 src/test/java/org/onap/dcae/CLIUtilsTest.java create mode 100644 src/test/java/org/onap/dcae/TLSTest.java create mode 100644 src/test/java/org/onap/dcae/TLSTestBase.java create mode 100644 src/test/java/org/onap/dcae/TestingUtilities.java create mode 100644 src/test/java/org/onap/dcae/WiremockBasedTest.java delete mode 100644 src/test/java/org/onap/dcae/collectors/restconf/common/AuthTypeTest.java delete mode 100644 src/test/java/org/onap/dcae/collectors/restconf/common/FormatTest.java delete mode 100644 src/test/java/org/onap/dcae/collectors/restconf/common/RestConfContextTest.java delete mode 100644 src/test/java/org/onap/dcae/collectors/restconf/common/RetryPolicyStoreTest.java delete mode 100644 src/test/java/org/onap/dcae/collectors/restconf/common/RetryPolicyTest.java delete mode 100755 src/test/java/org/onap/dcae/collectors/restconf/common/event/publishing/DMaaPConfigurationParserTest.java delete mode 100755 src/test/java/org/onap/dcae/collectors/restconf/common/event/publishing/DMaaPEventPublisherTest.java delete mode 100755 src/test/java/org/onap/dcae/collectors/restconf/common/event/publishing/DMaaPPublishersCacheTest.java delete mode 100644 src/test/java/org/onap/dcae/collectors/restconf/common/event/publishing/JsonParserTest.java delete mode 100755 src/test/java/org/onap/dcae/collectors/restconf/restconftest/AnyNodeTest.java delete mode 100755 src/test/java/org/onap/dcae/collectors/restconf/restconftest/RestConfProcTest.java delete mode 100755 src/test/java/org/onap/dcae/collectors/restconf/restconftest/SseResource.java delete mode 100755 src/test/java/org/onap/dcae/collectors/restconf/restconftest/TestRestConfCollector.java create mode 100644 src/test/java/org/onap/dcae/common/ApiExceptionTest.java create mode 100644 src/test/java/org/onap/dcae/common/AuthTypeTest.java create mode 100644 src/test/java/org/onap/dcae/common/DataChangeEventListnerTest.java create mode 100644 src/test/java/org/onap/dcae/common/EventConnectionStateTest.java create mode 100644 src/test/java/org/onap/dcae/common/EventProcessorTest.java create mode 100644 src/test/java/org/onap/dcae/common/FormatTest.java create mode 100644 src/test/java/org/onap/dcae/common/RestConfContextTest.java create mode 100644 src/test/java/org/onap/dcae/common/XmlJsonUtilTest.java create mode 100644 src/test/java/org/onap/dcae/common/XmlParserTest.java create mode 100644 src/test/java/org/onap/dcae/common/publishing/DMaaPEventPublisherTest.java create mode 100644 src/test/java/org/onap/dcae/common/publishing/DMaaPPublishersCacheTest.java create mode 100644 src/test/java/org/onap/dcae/common/publishing/JsonParserTest.java create mode 100644 src/test/java/org/onap/dcae/controller/ConfigCBSSourceTest.java create mode 100644 src/test/java/org/onap/dcae/controller/ConfigFilesFacadeTest.java create mode 100644 src/test/java/org/onap/dcae/controller/ConfigLoaderIntegrationE2ETest.java create mode 100644 src/test/java/org/onap/dcae/controller/ConfigParsingTest.java create mode 100644 src/test/java/org/onap/dcae/controller/EnvPropertiesReaderTest.java create mode 100644 src/test/java/org/onap/dcae/controller/EnvPropsTest.java create mode 100644 src/test/java/org/onap/dcae/restapi/ApiAuthInterceptionTest.java (limited to 'src/test/java/org') diff --git a/src/test/java/org/onap/dcae/AccessControllerTest.java b/src/test/java/org/onap/dcae/AccessControllerTest.java new file mode 100644 index 0000000..74d3da1 --- /dev/null +++ b/src/test/java/org/onap/dcae/AccessControllerTest.java @@ -0,0 +1,114 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2018-2019 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; + +import io.vavr.collection.Map; +import org.json.JSONArray; +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.common.RestConfContext; +import org.onap.dcae.common.RestapiCallNode; +import org.onap.dcae.controller.AccessController; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import org.json.JSONObject; + +import static java.nio.file.Files.readAllBytes; +import static java.util.Collections.singletonList; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; +import static org.onap.dcae.CLIUtils.processCmdLine; + +@RunWith(MockitoJUnitRunner.Silent.class) +public class AccessControllerTest { + @Mock + private ApplicationSettings properties; + + @Mock + private RestConfContext ctx; + + @Mock + private RestapiCallNode restApiCallNode; + + 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 createAndGetAccessControler() { + 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.rcc_keystoreFileLocation()).thenReturn(RCC_KEYSTORE.toString()); + when(properties.rcc_keystorePasswordFileLocation()).thenReturn(RCC_KEYSTORE_PASSWORD_FILE.toString()); + try { + when(readAllBytes(null)).thenReturn("colletor".getBytes()); + } catch (Exception e){} + 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\",\"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\"}]}"); + try { + AccessController acClr = new AccessController(controller, + properties); + + // then + assertEquals(acClr.getCfgInfo().getController_name(), "AccessM&C"); + assertEquals(acClr.getCfgInfo().getController_accessTokenMethod(), "put"); + assertEquals(acClr.getCfgInfo().getController_subsMethod(), "post"); + assertEquals(acClr.getCfgInfo().getController_subscriptionUrl(), "/restconf/v1/operations/huawei-nce-notification-action:establish-subscription"); + } catch (Exception e){} + } + + @Test + public void accessControllerSuccessfullyActivated() { + 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.rcc_keystoreFileLocation()).thenReturn(RCC_KEYSTORE.toString()); + when(properties.rcc_keystorePasswordFileLocation()).thenReturn(RCC_KEYSTORE_PASSWORD_FILE.toString()); + when(properties.rcc_policy()).thenReturn("[{\"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\",\"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\"}]}]"); + when(ctx.getAttribute("responsePrefix.httpResponse")).thenReturn("{\"accessSession\" : \"1234567890\",\"result\" : \"Ok\"}"); + try { + doThrow(new Exception()).when(restApiCallNode).sendRequest(null, null, 0); + } catch (Exception e){} + try { + when(readAllBytes(null)).thenReturn("colletor".getBytes()); + } catch (Exception e){} + + 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\",\"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\"}]}"); + try { + AccessController acClr = new AccessController(controller, + properties); + acClr.activate(); + } catch (Exception e){} + } +} \ No newline at end of file diff --git a/src/test/java/org/onap/dcae/AnyNodeTest.java b/src/test/java/org/onap/dcae/AnyNodeTest.java new file mode 100644 index 0000000..20fbf35 --- /dev/null +++ b/src/test/java/org/onap/dcae/AnyNodeTest.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2018-2019 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; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.google.common.collect.Sets; +import java.util.Set; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.dcae.common.AnyNode; + +/** + * Created by koblosz on 07.06.18. + */ +public class AnyNodeTest { + + private static final String SAMPLE_JSON_FILEPATH = "{\n" + + " \"channels\": [{\n" + + " \"one\": \"number1\", \"two\": \"number2\", \"three\": \"number3\"}],\n" + + " \"sampleStrList\": [\"1\", \"2\", \"3\", \"4\", \"5\"],\n" + + " \"sampleNestedObject\": {\"a\": 1, \"b\": 2},\n" + + " \"sampleInt\": 1,\n" + + " \"sampleString\": \"str\",\n" + + " \"sampleNull\": null\n" + + "}\n"; + private static final Set EXPECTED_JSON_KEYS = Sets + .newHashSet("channels", "sampleStrList", "sampleNestedObject", "sampleInt", "sampleString", "sampleNull"); + private static AnyNode node; + + + @BeforeClass + public static void setUpClass() { + node = AnyNode.fromString(SAMPLE_JSON_FILEPATH); + } + + @Test + public void testShouldReturnJsonObjectKeySet() { + assertThat(node.keys()).containsOnlyElementsOf(EXPECTED_JSON_KEYS); + } + + @Test(expected = ClassCastException.class) + public void whenInvokedOnJsonObjInsteadOfJsonArrShouldRaiseRuntimeEx() { + node.toList(); + } +} \ No newline at end of file diff --git a/src/test/java/org/onap/dcae/ApplicationSettingsTest.java b/src/test/java/org/onap/dcae/ApplicationSettingsTest.java new file mode 100644 index 0000000..1e1a115 --- /dev/null +++ b/src/test/java/org/onap/dcae/ApplicationSettingsTest.java @@ -0,0 +1,337 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2018 Nokia. All rights reserved. + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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; + +import static java.util.Collections.singletonList; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +import static org.junit.Assert.assertTrue; +import static org.onap.dcae.CLIUtils.processCmdLine; + +import io.vavr.collection.HashMap; +import io.vavr.collection.Map; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.Objects; +import org.junit.Test; + +public class ApplicationSettingsTest { + + @Test + public void shouldMakeApplicationSettingsOutOfCLIArguments() { + // given + String[] cliArguments = {"-param1", "param1value", "-param2", "param2value"}; + + // when + ApplicationSettings configurationAccessor = new ApplicationSettings(cliArguments, CLIUtils::processCmdLine); + String param1value = configurationAccessor.getStringDirectly("param1"); + String param2value = configurationAccessor.getStringDirectly("param2"); + + // then + assertEquals("param1value", param1value); + assertEquals("param2value", param2value); + } + + @Test + public void shouldMakeApplicationSettingsOutOfCLIArgumentsAndAConfigurationFile() + throws IOException { + // given + File tempConfFile = File.createTempFile("doesNotMatter", "doesNotMatter"); + Files.write(tempConfFile.toPath(), Arrays.asList("section.subSection1=abc", "section.subSection2=zxc")); + tempConfFile.deleteOnExit(); + String[] cliArguments = {"-param1", "param1value", "-param2", "param2value", "-c", tempConfFile.toString()}; + + // when + ApplicationSettings configurationAccessor = new ApplicationSettings(cliArguments, CLIUtils::processCmdLine); + String param1value = configurationAccessor.getStringDirectly("param1"); + String param2value = configurationAccessor.getStringDirectly("param2"); + String fromFileParam1Value = configurationAccessor.getStringDirectly("section.subSection1"); + String fromFileParam2Value = configurationAccessor.getStringDirectly("section.subSection2"); + + // then + assertEquals("param1value", param1value); + assertEquals("param2value", param2value); + assertEquals("abc", fromFileParam1Value); + assertEquals("zxc", fromFileParam2Value); + } + + @Test + public void shouldCLIArgumentsOverrideConfigFileParameters() throws IOException { + // given + String[] cliArguments = {"-section.subSection1", "abc"}; + File tempConfFile = File.createTempFile("doesNotMatter", "doesNotMatter"); + Files.write(tempConfFile.toPath(), singletonList("section.subSection1=zxc")); + tempConfFile.deleteOnExit(); + + // when + ApplicationSettings configurationAccessor = new ApplicationSettings(cliArguments, CLIUtils::processCmdLine); + String actuallyOverridenByCLIParam = configurationAccessor.getStringDirectly("section.subSection1"); + + // then + assertEquals("abc", actuallyOverridenByCLIParam); + } + + @Test + public void shouldReturnHTTPPort() throws IOException { + // when + int applicationPort = fromTemporaryConfiguration("collector.rcc.service.port=8090") + .httpPort(); + + // then + assertEquals(8090, applicationPort); + } + + @Test + public void shouldReturnDefaultHTTPPort() throws IOException { + // when + int applicationPort = fromTemporaryConfiguration().httpPort(); + + // then + assertEquals(8686, applicationPort); + } + + @Test + public void shouldReturnIfHTTPSIsEnabled() throws IOException { + // when + boolean httpsEnabled = fromTemporaryConfiguration("collector.rcc.service.secure.port=8687") + .httpsEnabled(); + + // then + assertTrue(httpsEnabled); + } + + @Test + public void shouldReturnIfHTTPIsEnabled() throws IOException { + // when + boolean httpsEnabled = fromTemporaryConfiguration("collector.service.port=8686").httpsEnabled(); + // then + assertTrue(httpsEnabled); + } + + @Test + public void shouldByDefaultHTTPSBeDisabled() throws IOException { + // when + boolean httpsEnabled = fromTemporaryConfiguration().httpsEnabled(); + + // then + assertTrue(httpsEnabled); + } + + @Test + public void shouldReturnHTTPSPort() throws IOException { + // when + int httpsPort = fromTemporaryConfiguration("collector.service.secure.port=8687") + .httpsPort(); + + // then + assertEquals(8687, httpsPort); + } + + + @Test + public void shouldReturnLocationOfThePasswordFile() throws IOException { + // when + String passwordFileLocation = fromTemporaryConfiguration("collector.rcc.keystore.passwordfile=/somewhere/password") + .keystorePasswordFileLocation(); + + // then + assertEquals(sanitizePath("/somewhere/password"), passwordFileLocation); + } + + @Test + public void shouldReturnDefaultLocationOfThePasswordFile() throws IOException { + // when + String passwordFileLocation = fromTemporaryConfiguration().keystorePasswordFileLocation(); + + // then + assertEquals(sanitizePath("etc/passwordfile"), passwordFileLocation); + } + + @Test + public void shouldReturnLocationOfTheKeystoreFile() throws IOException { + // when + String keystoreFileLocation = fromTemporaryConfiguration("collector.rcc.keystore.file.location=/somewhere/keystore") + .keystoreFileLocation(); + + // then + assertEquals(sanitizePath("/somewhere/keystore"), keystoreFileLocation); + } + + @Test + public void shouldReturnLocationOfTheDefaultKeystoreFile() throws IOException { + // when + String keystoreFileLocation = fromTemporaryConfiguration().keystoreFileLocation(); + + // then + assertEquals(sanitizePath("etc/sdnc.p12"), keystoreFileLocation); + } + + @Test + public void shouldReturnDMAAPConfigFileLocation() throws IOException { + // when + String dmaapConfigFileLocation = fromTemporaryConfiguration("collector.dmaapfile=/somewhere/dmaapFile") + .dMaaPConfigurationFileLocation(); + + // then + assertEquals(sanitizePath("/somewhere/dmaapFile"), dmaapConfigFileLocation); + } + + @Test + public void shouldReturnDefaultDMAAPConfigFileLocation() throws IOException { + // when + String dmaapConfigFileLocation = fromTemporaryConfiguration().dMaaPConfigurationFileLocation(); + + // then + assertEquals(sanitizePath("etc/DmaapConfig.json"), dmaapConfigFileLocation); + } + + @Test + public void shouldReturnMaximumAllowedQueuedEvents() throws IOException { + // when + int maximumAllowedQueuedEvents = fromTemporaryConfiguration("collector.rcc.inputQueue.maxPending=10000") + .maximumAllowedQueuedEvents(); + + // then + assertEquals(10000, maximumAllowedQueuedEvents); + } + + @Test + public void shouldReturnDefaultMaximumAllowedQueuedEvents() throws IOException { + // when + int maximumAllowedQueuedEvents = fromTemporaryConfiguration().maximumAllowedQueuedEvents(); + + // then + assertEquals(1024 * 4, maximumAllowedQueuedEvents); + } + + + + +// @Test +// public void shouldReturnDMAAPStreamId() throws IOException { +// // given +// Map expected = HashMap.of( +// "s", new String[]{"something", "something2"}, +// "s2", new String[]{"something3"} +// ); +// +// // when +// Map dmaapStreamID = fromTemporaryConfiguration( +// "collector.dmaap.streamid=s=something,something2|s2=something3") +// .dMaaPStreamsMapping(); +// +// // then +// assertArrayEquals(expected.get("s").get(), Objects.requireNonNull(dmaapStreamID).get("s").get()); +// assertArrayEquals(expected.get("s2").get(), Objects.requireNonNull(dmaapStreamID).get("s2").get()); +// assertEquals(expected.keySet(), dmaapStreamID.keySet()); +// } +// +// @Test +// public void shouldReturnDefaultDMAAPStreamId() throws IOException { +// // when +// Map dmaapStreamID = fromTemporaryConfiguration().dMaaPStreamsMapping(); +// +// // then +// assertEquals(dmaapStreamID, HashMap.empty()); +// } + + @Test + public void shouldReturnIfAuthorizationIsEnabled() throws IOException { + // when + boolean authorizationEnabled = fromTemporaryConfiguration("collector.header.authflag=1") + .authorizationEnabled(); + + // then + assertTrue(authorizationEnabled); + } + + @Test + public void shouldAuthorizationBeDisabledByDefault() throws IOException { + // when + boolean authorizationEnabled = fromTemporaryConfiguration().authorizationEnabled(); + + // then + assertFalse(authorizationEnabled); + } + + @Test + public void shouldReturnValidCredentials() throws IOException { + // when + Map allowedUsers = fromTemporaryConfiguration( + "collector.header.authlist=pasza,c2ltcGxlcGFzc3dvcmQNCg==|someoneelse,c2ltcGxlcGFzc3dvcmQNCg==" + ).validAuthorizationCredentials(); + + // then + assertEquals(allowedUsers.get("pasza").get(), "c2ltcGxlcGFzc3dvcmQNCg=="); + assertEquals(allowedUsers.get("someoneelse").get(), "c2ltcGxlcGFzc3dvcmQNCg=="); + } + + @Test + public void shouldbyDefaultThereShouldBeNoValidCredentials() throws IOException { + // when + Map userToBase64PasswordDelimitedByCommaSeparatedByPipes = fromTemporaryConfiguration(). + validAuthorizationCredentials(); + + // then + assertTrue(userToBase64PasswordDelimitedByCommaSeparatedByPipes.isEmpty()); + } + + + @Test + public void shouldReturnCambriaConfigurationFileLocation() throws IOException { + // when + String cambriaConfigurationFileLocation = fromTemporaryConfiguration( + "collector.dmaapfile=/somewhere/dmaapConfig") + .dMaaPConfigurationFileLocation(); + + // then + assertEquals(sanitizePath("/somewhere/dmaapConfig"), cambriaConfigurationFileLocation); + } + + @Test + public void shouldReturnDefaultCambriaConfigurationFileLocation() throws IOException { + // when + String cambriaConfigurationFileLocation = fromTemporaryConfiguration() + .dMaaPConfigurationFileLocation(); + + // then + assertEquals(sanitizePath("etc/DmaapConfig.json"), cambriaConfigurationFileLocation); + } + + private static ApplicationSettings fromTemporaryConfiguration(String... fileLines) + throws IOException { + File tempConfFile = File.createTempFile("doesNotMatter", "doesNotMatter"); + Files.write(tempConfFile.toPath(), Arrays.asList(fileLines)); + tempConfFile.deleteOnExit(); + return new ApplicationSettings(new String[]{"-c", tempConfFile.toString()}, args -> processCmdLine(args), ""); + } + + private String sanitizePath(String path) { + return Paths.get(path).toString(); + } +} \ No newline at end of file diff --git a/src/test/java/org/onap/dcae/CLIUtilsTest.java b/src/test/java/org/onap/dcae/CLIUtilsTest.java new file mode 100644 index 0000000..caf88ac --- /dev/null +++ b/src/test/java/org/onap/dcae/CLIUtilsTest.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018 Nokia. All rights reserved. + * Copyright (C) 2018-2019 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; + +import io.vavr.collection.Map; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class CLIUtilsTest { + + @Test + public void shouldConvertArgsToPropertiesMap() { + // given + String[] args = {"-withOutValue", "-collector.service.port", "8000", "-collector.service.secure.port", "8687"}; + + //when + Map properties = CLIUtils.processCmdLine(args); + + //then + assertThat(properties.get("collector.service.port").get()).isEqualTo("8000"); + assertThat(properties.get("collector.service.secure.port").get()).isEqualTo("8687"); + assertThat(properties.get("withOutValue").get()).isEqualTo(""); + } + + @Test + public void shouldReturnEmptyMapIfThereIsNoArgs() { + //given + String[] args = {}; + + //when + Map properties = CLIUtils.processCmdLine(args); + + //then + assertThat(properties).isEmpty(); + } + +} \ No newline at end of file diff --git a/src/test/java/org/onap/dcae/TLSTest.java b/src/test/java/org/onap/dcae/TLSTest.java new file mode 100644 index 0000000..ddb39ee --- /dev/null +++ b/src/test/java/org/onap/dcae/TLSTest.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2018 Nokia. All rights reserved. + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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; + +import io.vavr.collection.HashMap; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.springframework.context.annotation.Import; +import org.springframework.http.HttpStatus; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.when; +import static org.onap.dcae.TLSTest.HttpsConfiguration.USERNAME; +import static org.onap.dcae.TLSTest.HttpsConfiguration.PASSWORD; + +public class TLSTest extends TLSTestBase { + + @Nested + @Import(HttpConfiguration.class) + class HttpTest extends TestClassBase { + + @Test + public void shouldHttpRequestSucceed() { + assertEquals(HttpStatus.OK, makeHttpRequest().getStatusCode()); + } + + @Test + public void shouldHttpsRequestFail() { + assertThrows(Exception.class, this::makeHttpsRequest); + } + } + + + static class HttpConfiguration extends TLSTestBase.ConfigurationBase { + @Override + protected void configureSettings(ApplicationSettings settings) { + } + } + + static class HttpsConfiguration extends TLSTestBase.ConfigurationBase { + public static final String USERNAME = "TestUser"; + public static final String PASSWORD = "TestPassword"; + + @Override + protected void configureSettings(ApplicationSettings settings) { + when(settings.keystoreFileLocation()).thenReturn(KEYSTORE.toString()); + when(settings.keystorePasswordFileLocation()).thenReturn(KEYSTORE_PASSWORD_FILE.toString()); + when(settings.rcc_keystoreFileLocation()).thenReturn(RCC_KEYSTORE.toString()); + when(settings.rcc_keystorePasswordFileLocation()).thenReturn(RCC_KEYSTORE_PASSWORD_FILE.toString()); + when(settings.authorizationEnabled()).thenReturn(true); + when(settings.validAuthorizationCredentials()).thenReturn(HashMap.of(USERNAME, "$2a$10$51tDgG2VNLde5E173Ay/YO.Fq.aD.LR2Rp8pY3QAKriOSPswvGviy")); + } + } + + static class HttpsConfigurationWithTLSAuthentication extends HttpsConfiguration { + @Override + protected void configureSettings(ApplicationSettings settings) { + super.configureSettings(settings); + when(settings.authorizationEnabled()).thenReturn(false); + when(settings.clientTlsAuthenticationEnabled()).thenReturn(true); + when(settings.truststoreFileLocation()).thenReturn(TRUSTSTORE.toString()); + when(settings.truststorePasswordFileLocation()).thenReturn(TRUSTSTORE_PASSWORD_FILE.toString()); + } + } + + static class HttpsConfigurationWithTLSAuthenticationAndBasicAuth extends HttpsConfigurationWithTLSAuthentication { + @Override + protected void configureSettings(ApplicationSettings settings) { + super.configureSettings(settings); + when(settings.authorizationEnabled()).thenReturn(true); + } + } +} diff --git a/src/test/java/org/onap/dcae/TLSTestBase.java b/src/test/java/org/onap/dcae/TLSTestBase.java new file mode 100644 index 0000000..fdcc6e6 --- /dev/null +++ b/src/test/java/org/onap/dcae/TLSTestBase.java @@ -0,0 +1,154 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2018 Nokia. All rights reserved. + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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; + +import org.json.JSONObject; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mockito; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.http.ResponseEntity; +import org.springframework.http.client.support.BasicAuthenticationInterceptor; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.web.client.RestTemplate; + +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.concurrent.LinkedBlockingQueue; + +import static org.onap.dcae.TestingUtilities.*; + +@Configuration +@ExtendWith(SpringExtension.class) +public class TLSTestBase { + protected static final String KEYSTORE_ALIAS = "tomcat"; + 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 abstract class ConfigurationBase { + protected final ApplicationSettings settings = Mockito.mock(ApplicationSettings.class); + + @Bean + @Primary + public ApplicationSettings settings() { + configureSettings(settings); + return settings; + } + + protected abstract void configureSettings(final ApplicationSettings settings); + } + + @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) + protected abstract class TestClassBase { + @MockBean + @Qualifier("inputQueue") + protected LinkedBlockingQueue queue; + + @LocalServerPort + private int port; + + private final String keyStorePassword; + private final String trustStorePassword; + + public TestClassBase() { + keyStorePassword = readFile(RCC_KEYSTORE_PASSWORD_FILE); + trustStorePassword = readFile(TRUSTSTORE_PASSWORD_FILE); + } + + private String getURL(final String protocol, final String uri) { + return protocol + "://localhost:" + port + uri; + } + + private RestTemplate addBasicAuth(final RestTemplate template, final String username, final String password) { + template.getInterceptors() + .add(new BasicAuthenticationInterceptor(username, password)); + + return template; + } + + public String createHttpURL(String uri) { + return getURL("http", uri); + } + + public String createHttpsURL(String uri) { + return getURL("https", uri); + } + + public RestTemplate createHttpRestTemplate() { + return new RestTemplate(); + } + + public RestTemplate createHttpsRestTemplate() { + return rethrow(() -> + createRestTemplateWithSsl( + sslBuilderWithTrustStore(KEYSTORE, keyStorePassword).build() + )); + } + + public RestTemplate createHttpsRestTemplateWithKeyStore() { + return rethrow(() -> + createRestTemplateWithSsl( + configureKeyStore( + sslBuilderWithTrustStore(RCC_KEYSTORE, keyStorePassword), + TRUSTSTORE, + trustStorePassword + ).build()) + ); + } + + public ResponseEntity makeHttpRequest() { + return createHttpRestTemplate().getForEntity(createHttpURL("/"), String.class); + } + + public ResponseEntity makeHttpsRequest() { + return createHttpsRestTemplate().getForEntity(createHttpsURL("/"), String.class); + } + + + public ResponseEntity makeHttpsRequestWithBasicAuth(final String username, final String password) { + return addBasicAuth(createHttpsRestTemplate(), username, password) + .getForEntity(createHttpsURL("/"), String.class); + + } + + public ResponseEntity makeHttpsRequestWithClientCert() { + return createHttpsRestTemplateWithKeyStore().getForEntity(createHttpsURL("/"), String.class); + } + + public ResponseEntity makeHttpsRequestWithClientCertAndBasicAuth( + final String username, + final String password) { + return addBasicAuth(createHttpsRestTemplateWithKeyStore(), username, password) + .getForEntity(createHttpsURL("/"), String.class); + } + } +} diff --git a/src/test/java/org/onap/dcae/TestingUtilities.java b/src/test/java/org/onap/dcae/TestingUtilities.java new file mode 100644 index 0000000..5ae238a --- /dev/null +++ b/src/test/java/org/onap/dcae/TestingUtilities.java @@ -0,0 +1,141 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2018 Nokia. All rights reserved. + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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; + +import static java.nio.file.Files.readAllBytes; +import static org.assertj.core.api.Assertions.assertThat; + +import io.vavr.control.Try; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.UnrecoverableKeyException; +import java.security.cert.CertificateException; + +import org.apache.http.client.HttpClient; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.ssl.SSLContextBuilder; +import org.assertj.core.api.AbstractThrowableAssert; +import org.assertj.core.api.Java6Assertions; +import org.json.JSONObject; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.web.client.RestTemplate; + +import javax.net.ssl.SSLContext; + +public final class TestingUtilities { + + private TestingUtilities() { + // utility class, no objects allowed + } + + public static void assertJSONObjectsEqual(JSONObject o1, JSONObject o2) { + assertThat(o1.toString()).isEqualTo(o2.toString()); + } + + public static JSONObject readJSONFromFile(Path path) { + return rethrow(() -> new JSONObject(readFile(path))); + } + + public static String readFile(Path path) { + return rethrow(() -> new String(readAllBytes(path))); + } + + public static Path createTemporaryFile(String content) { + return rethrow(() -> { + File temp = File.createTempFile("restconf-collector-tests-created-this-file", ".tmp"); + temp.deleteOnExit(); + Path filePath = Paths.get(temp.toString()); + Files.write(filePath, content.getBytes()); + return filePath; + }); + } + + /** + * Exception in test case usually means there is something wrong, it should never be catched, but rather thrown to + * be handled by JUnit framework. + */ + public static T rethrow(CheckedSupplier supplier) { + try { + return supplier.get(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @FunctionalInterface + interface CheckedSupplier { + + T get() throws Exception; + } + + public static void assertFailureHasInfo(Try any, String... msgPart) { + Java6Assertions.assertThat(any.isFailure()).isTrue(); + AbstractThrowableAssert o = Java6Assertions.assertThat(any.getCause()) + .hasCauseInstanceOf(Exception.class); + for (String s : msgPart) { + o.hasStackTraceContaining(s); + } + } + + public static SSLContextBuilder sslBuilderWithTrustStore(final Path trustStore, final String pass) { + return rethrow(() -> + new SSLContextBuilder() + .loadTrustMaterial(trustStore.toFile(), pass.toCharArray()) + ); + } + + public static SSLContextBuilder configureKeyStore( + final SSLContextBuilder builder, + final Path keyStore, + final String pass) { + return rethrow(() -> { + KeyStore cks = KeyStore.getInstance(KeyStore.getDefaultType()); + cks.load(new FileInputStream(keyStore.toFile()), pass.toCharArray()); + + builder.loadKeyMaterial(cks, pass.toCharArray()); + + return builder; + }); + } + + public static RestTemplate createRestTemplateWithSsl(final SSLContext context) { + final SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(context); + final HttpClient httpClient = HttpClients + .custom() + .setSSLSocketFactory(socketFactory) + .build(); + + final HttpComponentsClientHttpRequestFactory factory = + new HttpComponentsClientHttpRequestFactory(httpClient); + + return new RestTemplate(factory); + } +} diff --git a/src/test/java/org/onap/dcae/WiremockBasedTest.java b/src/test/java/org/onap/dcae/WiremockBasedTest.java new file mode 100644 index 0000000..2144e99 --- /dev/null +++ b/src/test/java/org/onap/dcae/WiremockBasedTest.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2018 Nokia. All rights reserved. + * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; +import static io.vavr.API.Map; + +import com.github.tomakehurst.wiremock.junit.WireMockRule; +import io.vavr.collection.Map; +import org.junit.Rule; + +public class WiremockBasedTest { + + @Rule + public WireMockRule wireMockRule = new WireMockRule( + wireMockConfig().dynamicPort().dynamicHttpsPort().keystorePath(null)); + + protected void stubConsulToReturnLocalAddressOfCBS() { + stubFor(get(urlEqualTo("/v1/catalog/service/CBSName")) + .willReturn(aResponse().withBody(validLocalCBSConf()))); + } + + protected void stubCBSToReturnAppConfig(String sampleConfigForVES) { + stubFor(get(urlEqualTo("/service_component/restconfcollector")) + .willReturn(aResponse().withBody(sampleConfigForVES))); + } + + protected Map wiremockBasedEnvProps() { + return Map( + "CONSUL_HOST", "localhost", + "CONSUL_PORT", "" + wireMockRule.port(), + "HOSTNAME", "restconfcollector", + "CONFIG_BINDING_SERVICE", "CBSName" + ); + } + + protected String validLocalCBSConf() { + return "" + + "[{ " + + "\"ServiceAddress\": \"localhost\"," + + "\"ServicePort\":" + wireMockRule.port() + + "}]"; + } +} diff --git a/src/test/java/org/onap/dcae/collectors/restconf/common/AuthTypeTest.java b/src/test/java/org/onap/dcae/collectors/restconf/common/AuthTypeTest.java deleted file mode 100644 index 8eaee6f..0000000 --- a/src/test/java/org/onap/dcae/collectors/restconf/common/AuthTypeTest.java +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dcaegen2.collectors.restconf - * ================================================================================ - * Copyright (C) 2019 IBM. 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.collectors.restconf.common; - -import org.junit.Test; - -import static org.junit.Assert.*; - -public class AuthTypeTest { - - @Test - public void fromString() { - assertEquals(AuthType.BASIC, AuthType.fromString("basic")); - assertEquals(AuthType.DIGEST, AuthType.fromString("digest")); - assertEquals(AuthType.OAUTH, AuthType.fromString("oauth")); - assertEquals(AuthType.NONE, AuthType.fromString("none")); - assertEquals(AuthType.Unspecified, AuthType.fromString("unspecified")); - } - - @Test(expected = IllegalArgumentException.class) - public void fromStringWithException() { - AuthType.fromString("test"); - } -} \ No newline at end of file diff --git a/src/test/java/org/onap/dcae/collectors/restconf/common/FormatTest.java b/src/test/java/org/onap/dcae/collectors/restconf/common/FormatTest.java deleted file mode 100644 index dd4159b..0000000 --- a/src/test/java/org/onap/dcae/collectors/restconf/common/FormatTest.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dcaegen2.collectors.restconf - * ================================================================================ - * Copyright (C) 2019 IBM. 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.collectors.restconf.common; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class FormatTest { - - @Test - public void fromString() { - assertEquals(Format.JSON, Format.fromString("json")); - assertEquals(Format.XML, Format.fromString("xml")); - assertEquals(Format.NONE, Format.fromString("none")); - } - - @Test(expected = IllegalArgumentException.class) - public void fromStringWithException() { - Format.fromString("test"); - } -} \ No newline at end of file diff --git a/src/test/java/org/onap/dcae/collectors/restconf/common/RestConfContextTest.java b/src/test/java/org/onap/dcae/collectors/restconf/common/RestConfContextTest.java deleted file mode 100644 index 696c254..0000000 --- a/src/test/java/org/onap/dcae/collectors/restconf/common/RestConfContextTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dcaegen2.collectors.restconf - * ================================================================================ - * Copyright (C) 2019 IBM. 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.collectors.restconf.common; - -import org.junit.Test; - -import static org.junit.Assert.*; - -public class RestConfContextTest { - - @Test - public void setAttribute() { - String key = "key"; - String value = "value"; - RestConfContext restConfContext = new RestConfContext(); - restConfContext.setAttribute(key, value); - assertEquals(value, restConfContext.getAttribute(key)); - restConfContext.setAttribute(key, null); - assertFalse(restConfContext.getAttributeKeySet().contains(key)); - } - - @Test - public void getAttributeKeySet() { - String key = "key"; - String value = "value"; - String key1 = "key1"; - String value1 = "value1"; - RestConfContext restConfContext = new RestConfContext(); - restConfContext.setAttribute(key,value); - restConfContext.setAttribute(key1,value1); - assertTrue(restConfContext.getAttributeKeySet().contains(key) && restConfContext.getAttributeKeySet().contains(key1)); - } -} \ No newline at end of file diff --git a/src/test/java/org/onap/dcae/collectors/restconf/common/RetryPolicyStoreTest.java b/src/test/java/org/onap/dcae/collectors/restconf/common/RetryPolicyStoreTest.java deleted file mode 100644 index 9508b1a..0000000 --- a/src/test/java/org/onap/dcae/collectors/restconf/common/RetryPolicyStoreTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dcaegen2.collectors.restconf - * ================================================================================ - * Copyright (C) 2019 IBM. 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.collectors.restconf.common; - -import org.junit.Before; -import org.junit.Test; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.*; - -public class RetryPolicyStoreTest { - - RetryPolicyStore retryPolicyStore; - String proxyServers; - - @Before - public void setUp() throws Exception { - retryPolicyStore = new RetryPolicyStore(); - proxyServers = "3.3.3.3,4.4.4.4,5.5.5.5"; - } - - @Test - public void getProxyServers() { - retryPolicyStore.setProxyServers(proxyServers); - assertThat(retryPolicyStore.getProxyServers(), is(proxyServers)); - } - - @Test - public void setProxyServers() throws RetryException { - retryPolicyStore.setProxyServers(proxyServers); - RetryPolicy actual = retryPolicyStore.getRetryPolicy("dme2proxy"); - assertThat(3, is(actual.getMaximumRetries())); - assertThat("4.4.4.4", is(actual.getNextHostName("3.3.3.3"))); - assertThat("5.5.5.5", is(actual.getNextHostName("4.4.4.4"))); - } - - @Test - public void getRetryPolicy() { - String[] adminServersArray = {"3.3.3.3","4.4.4.4","5.5.5.5"}; - RetryPolicy retryPolicy = new RetryPolicy(adminServersArray, adminServersArray.length); - retryPolicyStore.retryPolicies.put("dme2proxy", retryPolicy); - assertThat(retryPolicyStore.getRetryPolicy("dme2proxy"), is(retryPolicy)); - } -} \ No newline at end of file diff --git a/src/test/java/org/onap/dcae/collectors/restconf/common/RetryPolicyTest.java b/src/test/java/org/onap/dcae/collectors/restconf/common/RetryPolicyTest.java deleted file mode 100644 index 1b8cfcb..0000000 --- a/src/test/java/org/onap/dcae/collectors/restconf/common/RetryPolicyTest.java +++ /dev/null @@ -1,57 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dcaegen2.collectors.restconf - * ================================================================================ - * Copyright (C) 2019 IBM. 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.collectors.restconf.common; - -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public class RetryPolicyTest { - - String[] hostnames; - Integer maximumRetries; - RetryPolicy retryPolicy; - - @Before - public void setUp() throws Exception { - hostnames = "test1.com,test2.com,test3.com,4.4.4.4".split(","); - maximumRetries = 3; - retryPolicy = new RetryPolicy(this.hostnames, this.maximumRetries); - } - - @Test - public void testGetMaximumRetries() { - assertEquals(maximumRetries, retryPolicy.getMaximumRetries()); - } - - @Test - public void testGetNextHostName() throws RetryException { - assertEquals(hostnames[2], retryPolicy.getNextHostName("http://" + hostnames[1] + "/endpoint")); - assertEquals(hostnames[0], retryPolicy.getNextHostName("http://" + hostnames[3] + "/endpoint")); - } - - @Test(expected = RetryException.class) - public void testGetNextHostNameWithException() throws RetryException { - retryPolicy.getNextHostName("abc"); - } -} \ No newline at end of file diff --git a/src/test/java/org/onap/dcae/collectors/restconf/common/event/publishing/DMaaPConfigurationParserTest.java b/src/test/java/org/onap/dcae/collectors/restconf/common/event/publishing/DMaaPConfigurationParserTest.java deleted file mode 100755 index 730d257..0000000 --- a/src/test/java/org/onap/dcae/collectors/restconf/common/event/publishing/DMaaPConfigurationParserTest.java +++ /dev/null @@ -1,111 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dcaegen2.collectors.restconf - * ================================================================================ - * Copyright (C) 2018 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.collectors.restconf.common.event.publishing; - -import io.vavr.collection.Map; -import io.vavr.control.Try; -import org.junit.Test; - -import java.nio.file.Path; -import java.nio.file.Paths; - -import static io.vavr.API.List; -import static org.assertj.core.api.Assertions.assertThat; -import static org.onap.dcae.collectors.restconf.common.event.publishing.DMaaPConfigurationParser.parseToDomainMapping; - -public class DMaaPConfigurationParserTest { - @Test - public void testParseCredentialsForGen2() { - Path path = Paths.get("src/test/resources/testParseDMaaPCredentialsGen2.json"); - Try> publisherConfigs = parseToDomainMapping(path); - - PublisherConfig authCredentialsNulls = publisherConfigs.get().get("auth-credentials-null").getOrNull(); - assertThat(authCredentialsNulls.userName().isEmpty()).isTrue(); - assertThat(authCredentialsNulls.password().isEmpty()).isTrue(); - assertThat(authCredentialsNulls.isSecured()).isFalse(); - - PublisherConfig authCredentialsPresent = publisherConfigs.get().get("auth-credentials-present").getOrNull(); - assertThat(authCredentialsPresent.userName().getOrNull()).isEqualTo("sampleUser"); - assertThat(authCredentialsPresent.password().getOrNull()).isEqualTo("samplePassword"); - assertThat(authCredentialsPresent.isSecured()).isTrue(); - - PublisherConfig authCredentialsKeysMissing = publisherConfigs.get().get("auth-credentials-missing").getOrNull(); - assertThat(authCredentialsKeysMissing.userName().isEmpty()).isTrue(); - assertThat(authCredentialsKeysMissing.password().isEmpty()).isTrue(); - assertThat(authCredentialsKeysMissing.isSecured()).isFalse(); - } - - - @Test - public void testParseCredentialsForLegacy() { - Path path = Paths.get("src/test/resources/testParseDMaaPCredentialsLegacy.json"); - Try> publisherConfigs = parseToDomainMapping(path); - - PublisherConfig authCredentialsNull = publisherConfigs.get().get("auth-credentials-null").getOrNull(); - assertThat(authCredentialsNull.userName().isEmpty()).isTrue(); - assertThat(authCredentialsNull.password().isEmpty()).isTrue(); - assertThat(authCredentialsNull.isSecured()).isFalse(); - - PublisherConfig authCredentialsPresent = publisherConfigs.get().get("auth-credentials-present").getOrNull(); - assertThat(authCredentialsPresent.userName().getOrNull()).isEqualTo("sampleUser"); - assertThat(authCredentialsPresent.password().getOrNull()).isEqualTo("samplePassword"); - assertThat(authCredentialsPresent.isSecured()).isTrue(); - - PublisherConfig authCredentialsMissing = publisherConfigs.get().get("auth-credentials-missing").getOrNull(); - assertThat(authCredentialsMissing.userName().isEmpty()).isTrue(); - assertThat(authCredentialsMissing.password().isEmpty()).isTrue(); - assertThat(authCredentialsMissing.isSecured()).isFalse(); - } - - - @Test - public void testParseGen2() { - Path path = Paths.get("src/test/resources/testParseDMaaPGen2.json"); - Try> publisherConfigs = parseToDomainMapping(path); - - PublisherConfig withEventsSegment = publisherConfigs.get().get("event-segments-with-port").getOrNull(); - assertThat(withEventsSegment.destinations()).isEqualTo(List("UEBHOST:3904")); - assertThat(withEventsSegment.topic()).isEqualTo("DCAE-RESTCONF-COLLECTOR-EVENTS-DEV"); - - PublisherConfig withOtherSegment = publisherConfigs.get().get("other-segments-without-ports").getOrNull(); - assertThat(withOtherSegment.destinations()).isEqualTo(List("UEBHOST")); - assertThat(withOtherSegment.topic()).isEqualTo("DCAE-RESTCONF-COLLECTOR-EVENTS-DEV"); - } - - @Test - public void testParseLegacy() { - Path exemplaryConfig = Paths.get("src/test/resources/testParseDMaaPLegacy.json"); - Try> publisherConfigs = - parseToDomainMapping(exemplaryConfig); - - PublisherConfig urlFirstThenHosts = publisherConfigs.get().get("url-precedes-hosts").getOrNull(); - assertThat(urlFirstThenHosts.destinations()).isEqualTo(List("127.0.0.1:3904")); - assertThat(urlFirstThenHosts.topic()).isEqualTo("DCAE-RESTCONF-COLLECTOR-EVENTS-DEV"); - - PublisherConfig urlKeyMissing = publisherConfigs.get().get("url-key-missing").getOrNull(); - assertThat(urlKeyMissing.destinations()).isEqualTo(List("h1.att.com", "h2.att.com")); - assertThat(urlKeyMissing.topic()).isEqualTo("DCAE-RESTCONF-COLLECTOR-EVENTS-DEV"); - - PublisherConfig urlIsMissing = publisherConfigs.get().get("url-is-null").getOrNull(); - assertThat(urlIsMissing.destinations()).isEqualTo(List("h1.att.com", "h2.att.com")); - assertThat(urlIsMissing.topic()).isEqualTo("DCAE-RESTCONF-COLLECTOR-EVENTS-DEV"); - } -} diff --git a/src/test/java/org/onap/dcae/collectors/restconf/common/event/publishing/DMaaPEventPublisherTest.java b/src/test/java/org/onap/dcae/collectors/restconf/common/event/publishing/DMaaPEventPublisherTest.java deleted file mode 100755 index 3e1095d..0000000 --- a/src/test/java/org/onap/dcae/collectors/restconf/common/event/publishing/DMaaPEventPublisherTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dcaegen2.collectors.restconf - * ================================================================================ - * Copyright (C) 2018 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.collectors.restconf.common.event.publishing; - -import com.att.nsa.cambria.client.CambriaBatchingPublisher; -import org.json.JSONObject; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; - -import java.io.IOException; - -import static io.vavr.API.Option; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class DMaaPEventPublisherTest { - - private static final String STREAM_ID = "sampleStreamId"; - - private DMaaPEventPublisher eventPublisher; - private CambriaBatchingPublisher cambriaPublisher; - private DMaaPPublishersCache DMaaPPublishersCache; - - @Before - public void setUp() { - cambriaPublisher = mock(CambriaBatchingPublisher.class); - DMaaPPublishersCache = mock(DMaaPPublishersCache.class); - when(DMaaPPublishersCache.getPublisher(anyString())).thenReturn(Option(cambriaPublisher)); - eventPublisher = new DMaaPEventPublisher(DMaaPPublishersCache, mock(Logger.class)); - } - - @Test - public void shouldSendEventToTopic() throws Exception { - // given - JSONObject event = new JSONObject("{}"); - - // when - eventPublisher.sendEvent(event, STREAM_ID); - - // then - verify(cambriaPublisher).send("MyPartitionKey", event.toString()); - } - - @Test - public void shouldCloseConnectionWhenExceptionOccurred() throws Exception { - // given - JSONObject event = new JSONObject("{}"); - given(cambriaPublisher.send(anyString(), anyString())).willThrow(new IOException("epic fail")); - - // when - eventPublisher.sendEvent(event, STREAM_ID); - - // then - verify(DMaaPPublishersCache).closePublisherFor(STREAM_ID); - } -} diff --git a/src/test/java/org/onap/dcae/collectors/restconf/common/event/publishing/DMaaPPublishersCacheTest.java b/src/test/java/org/onap/dcae/collectors/restconf/common/event/publishing/DMaaPPublishersCacheTest.java deleted file mode 100755 index 6ebf273..0000000 --- a/src/test/java/org/onap/dcae/collectors/restconf/common/event/publishing/DMaaPPublishersCacheTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dcaegen2.collectors.restconf - * ================================================================================ - * Copyright (C) 2018 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.collectors.restconf.common.event.publishing; - -import com.att.nsa.cambria.client.CambriaBatchingPublisher; -import io.vavr.collection.Map; -import io.vavr.control.Option; -import org.junit.Before; -import org.junit.Test; -import org.onap.dcae.collectors.restconf.common.event.publishing.DMaaPPublishersCache.OnPublisherRemovalListener; - -import java.io.IOException; -import java.util.concurrent.TimeUnit; - -import static io.vavr.API.List; -import static io.vavr.API.Map; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class DMaaPPublishersCacheTest { - - private String streamId1; - private Map dMaaPConfigs; - - @Before - public void setUp() { - streamId1 = "sampleStream1"; - dMaaPConfigs = Map("sampleStream1", new PublisherConfig(List("destination1"), "topic1")); - } - - @Test - public void shouldReturnTheSameCachedInstanceOnConsecutiveRetrievals() { - // given - DMaaPPublishersCache dMaaPPublishersCache = new DMaaPPublishersCache(dMaaPConfigs); - - // when - Option firstPublisher = dMaaPPublishersCache.getPublisher(streamId1); - Option secondPublisher = dMaaPPublishersCache.getPublisher(streamId1); - - // then - assertSame("should return same instance", firstPublisher.get(), secondPublisher.get()); - } - - @Test - public void shouldCloseCambriaPublisherOnCacheInvalidate() throws IOException, InterruptedException { - // given - CambriaBatchingPublisher cambriaPublisherMock1 = mock(CambriaBatchingPublisher.class); - DMaaPPublishersCache.CambriaPublishersCacheLoader cacheLoaderMock = mock(DMaaPPublishersCache.CambriaPublishersCacheLoader.class); - DMaaPPublishersCache dMaaPPublishersCache = new DMaaPPublishersCache(cacheLoaderMock, - new OnPublisherRemovalListener(), - dMaaPConfigs); - when(cacheLoaderMock.load(streamId1)).thenReturn(cambriaPublisherMock1); - - // when - dMaaPPublishersCache.getPublisher(streamId1); - dMaaPPublishersCache.closePublisherFor(streamId1); - - // then - verify(cambriaPublisherMock1).close(20, TimeUnit.SECONDS); - - } - - @Test - public void shouldReturnNoneIfThereIsNoDMaaPConfigurationForGivenStreamID() { - // given - DMaaPPublishersCache dMaaPPublishersCache = new DMaaPPublishersCache(dMaaPConfigs); - - // then - assertTrue("should not exist", dMaaPPublishersCache.getPublisher("non-existing").isEmpty()); - } - -} \ No newline at end of file diff --git a/src/test/java/org/onap/dcae/collectors/restconf/common/event/publishing/JsonParserTest.java b/src/test/java/org/onap/dcae/collectors/restconf/common/event/publishing/JsonParserTest.java deleted file mode 100644 index a5609f9..0000000 --- a/src/test/java/org/onap/dcae/collectors/restconf/common/event/publishing/JsonParserTest.java +++ /dev/null @@ -1,38 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dcaegen2.collectors.restconf - * ================================================================================ - * Copyright (C) 2019 IBM. 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.collectors.restconf.common.event.publishing; - -import java.util.Map; - -import org.junit.Test; -import org.onap.dcae.collectors.restconf.common.JsonParser; - -import junit.framework.Assert; - -public class JsonParserTest { - - @Test - public void convertToPropertiesTest() throws Exception { - String testJson="{\"prop2\"=\"value\", \"prop1\"=\"value\"}"; - Map response=JsonParser.convertToProperties(testJson); - Assert.assertEquals("value", response.get("prop2")); - } -} diff --git a/src/test/java/org/onap/dcae/collectors/restconf/restconftest/AnyNodeTest.java b/src/test/java/org/onap/dcae/collectors/restconf/restconftest/AnyNodeTest.java deleted file mode 100755 index 301f148..0000000 --- a/src/test/java/org/onap/dcae/collectors/restconf/restconftest/AnyNodeTest.java +++ /dev/null @@ -1,62 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dcaegen2.collectors.restconf - * ================================================================================ - * Copyright (C) 2018 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.collectors.restconf.restconftest; - -import com.google.common.collect.Sets; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.dcae.collectors.restconf.common.AnyNode; - -import java.util.Set; - -import static org.assertj.core.api.Assertions.assertThat; - -public class AnyNodeTest { - - private static final String SAMPLE_JSON_FILEPATH = "{\n" - + " \"channels\": [{\n" - + " \"one\": \"number1\", \"two\": \"number2\", \"three\": \"number3\"}],\n" - + " \"sampleStrList\": [\"1\", \"2\", \"3\", \"4\", \"5\"],\n" - + " \"sampleNestedObject\": {\"a\": 1, \"b\": 2},\n" - + " \"sampleInt\": 1,\n" - + " \"sampleString\": \"str\",\n" - + " \"sampleNull\": null\n" - + "}\n"; - private static final Set EXPECTED_JSON_KEYS = Sets - .newHashSet("channels", "sampleStrList", "sampleNestedObject", "sampleInt", "sampleString", "sampleNull"); - private static AnyNode node; - - - @BeforeClass - public static void setUpClass() { - node = AnyNode.fromString(SAMPLE_JSON_FILEPATH); - } - - @Test - public void testShouldReturnJsonObjectKeySet() { - assertThat(node.keys()).containsOnlyElementsOf(EXPECTED_JSON_KEYS); - } - - @Test(expected = ClassCastException.class) - public void whenInvokedOnJsonObjInsteadOfJsonArrShouldRaiseRuntimeEx() { - node.toList(); - } -} \ No newline at end of file diff --git a/src/test/java/org/onap/dcae/collectors/restconf/restconftest/RestConfProcTest.java b/src/test/java/org/onap/dcae/collectors/restconf/restconftest/RestConfProcTest.java deleted file mode 100755 index 3c55618..0000000 --- a/src/test/java/org/onap/dcae/collectors/restconf/restconftest/RestConfProcTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dcaegen2.collectors.restconf - * ================================================================================ - * Copyright (C) 2018 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.collectors.restconf.restconftest; - -import com.att.nsa.cmdLine.NsaCommandLineUtil; -import com.att.nsa.drumlin.service.framework.DrumlinServlet; -import com.att.nsa.drumlin.till.nv.impl.nvPropertiesFile; -import com.att.nsa.drumlin.till.nv.impl.nvReadableStack; -import com.att.nsa.drumlin.till.nv.impl.nvReadableTable; -import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; -import org.glassfish.jersey.media.sse.SseFeature; -import org.glassfish.jersey.server.ResourceConfig; -import org.junit.Test; -import org.onap.dcae.collectors.restconf.common.Constants; -import org.onap.dcae.collectors.restconf.common.RestConfCollector; -import org.onap.dcae.collectors.restconf.common.RestConfContext; -import org.onap.dcae.collectors.restconf.common.RestConfProc; - -import java.net.URI; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; - -public class RestConfProcTest { - - private static final URI CONTEXT = URI.create("http://localhost:8080/"); - - @Test - public void testEstablishPersistentConnection() throws Exception { - - final Map argMap = new HashMap<>(); - final String config = NsaCommandLineUtil.getSetting(argMap, Constants.KCONFIG, "collector.properties"); - final URL settingStream = DrumlinServlet.findStream(config, RestConfCollector.class); - - final nvReadableStack settings = new nvReadableStack(); - - settings.push(new nvPropertiesFile(settingStream)); - settings.push(new nvReadableTable(argMap)); - - RestConfProc restConfProc = new RestConfProc(settings); - - final ResourceConfig resourceConfig = new ResourceConfig(SseResource.class, SseFeature.class); - GrizzlyHttpServerFactory.createHttpServer(CONTEXT, resourceConfig); - RestConfContext ctx = new RestConfContext(); - ctx.setAttribute("prop.encoding-json", "encoding-json"); - ctx.setAttribute("restapi-result.response-code", "200"); - ctx.setAttribute("restapi-result.ietf-subscribed-notifications:output.identifier", "100"); - - Map p = new HashMap<>(); - p.put("sseConnectURL", "http://localhost:8080/ssevents"); - p.put("subscriberId", "networkId"); - p.put("responsePrefix", "restapi-result"); - p.put("restapiUrl", "https://localhost:8080/restconf/operations/" + - "ietf-subscribed-notifications:establish-subscription"); - p.put("restapiUser", "access"); - p.put("restapiPassword", "abc@123"); - - restConfProc.establishPersistentConnection(p, ctx); - Thread.sleep(1000); - } -} diff --git a/src/test/java/org/onap/dcae/collectors/restconf/restconftest/SseResource.java b/src/test/java/org/onap/dcae/collectors/restconf/restconftest/SseResource.java deleted file mode 100755 index 558cba8..0000000 --- a/src/test/java/org/onap/dcae/collectors/restconf/restconftest/SseResource.java +++ /dev/null @@ -1,69 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dcaegen2.collectors.restconf - * ================================================================================ - * Copyright (C) 2018 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.collectors.restconf.restconftest; - -import org.glassfish.jersey.media.sse.EventOutput; -import org.glassfish.jersey.media.sse.OutboundEvent; -import org.glassfish.jersey.media.sse.SseFeature; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import java.io.IOException; - -@Path("ssevents") -public class SseResource { - - @GET - @Produces(SseFeature.SERVER_SENT_EVENTS) - public EventOutput getServerSentEvents() throws IOException { - String data = "{" - + "\"ietf-notification:notification\" : {" - + " \"eventTime\" : \"2017-10-25T08:22:33.44Z\"," - + " \"ietf-yang-push:push-change-update\": {" - + "\"subscription-id\":\"89\"," - + "\"datastore-changes\": {" - + "\"ietf-yang-patch:yang-patch\":{" - + "\"patch-id\":\"1\"," - + "\"edit\":[{" - + "\"edit-id\":\"edit1\"," - + "\"operation\":\"merge\"," - + "\"target\":\"/ietf-interfaces:interfaces-state\"," - + "\"value\": {" - + "\"ietf-interfaces:interfaces-state\":{" - + "\"interface\": {" - + "\"name\":\"eth0\"," - + "\"oper-status\":\"down\"," - + "}" - + "}" - + "}" - + "}]" - + "}" - + "}" - + "}" - + "}" - + "}"; - final EventOutput result = new EventOutput(); - result.write(new OutboundEvent.Builder().data(String.class, data).build()); - result.close(); - return result; - } -} diff --git a/src/test/java/org/onap/dcae/collectors/restconf/restconftest/TestRestConfCollector.java b/src/test/java/org/onap/dcae/collectors/restconf/restconftest/TestRestConfCollector.java deleted file mode 100755 index 59e6e72..0000000 --- a/src/test/java/org/onap/dcae/collectors/restconf/restconftest/TestRestConfCollector.java +++ /dev/null @@ -1,66 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.dcaegen2.collectors.restconf - * ================================================================================ - * Copyright (C) 2018 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.collectors.restconf.restconftest; - -import com.att.nsa.cmdLine.NsaCommandLineUtil; -import com.att.nsa.drumlin.till.nv.impl.nvReadableStack; -import com.att.nsa.drumlin.till.nv.impl.nvReadableTable; -import com.google.gson.JsonElement; -import com.google.gson.JsonParser; -import org.json.JSONArray; -import org.json.JSONObject; -import org.junit.Test; -import org.onap.dcae.collectors.restconf.common.Constants; -import org.onap.dcae.collectors.restconf.common.RestConfProc; - -import java.io.FileReader; -import java.util.Map; -import java.util.concurrent.LinkedBlockingQueue; - -import static org.junit.Assert.assertEquals; - -public class TestRestConfCollector { - @Test - public void testParseCLIArguments() { - // given - String args[] = {"-a", "aa"}; - Map argMap = NsaCommandLineUtil.processCmdLine(args, true); - // when - nvReadableStack settings = new nvReadableStack(); - settings.push(new nvReadableTable(argMap)); - - // then - assertEquals(settings.getString("a", "default"), "aa"); - } - - @Test - public void shouldPutValidRestConfEventOnProcessingQueueWithoutExceptions() throws Exception { - // given - RestConfProc.fProcessingInputQueue = new LinkedBlockingQueue<>( - Constants.KDEFAULT_MAXQUEUEDEVENTS); - JsonElement restConfEvent = new JsonParser().parse(new FileReader("src/test/resources/RestConfEvent.json")); - JSONObject validRestConfEvent = new JSONObject(restConfEvent.toString()); - JSONArray jsonArrayMod = new JSONArray().put(validRestConfEvent); - - // then - RestConfProc.handleEvents(jsonArrayMod); - } -} diff --git a/src/test/java/org/onap/dcae/common/ApiExceptionTest.java b/src/test/java/org/onap/dcae/common/ApiExceptionTest.java new file mode 100644 index 0000000..58cf9e4 --- /dev/null +++ b/src/test/java/org/onap/dcae/common/ApiExceptionTest.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2018 Nokia. All rights reserved. + * Copyright (C) 2018-2019 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 static org.junit.Assert.assertEquals; + +import org.json.JSONObject; +import org.junit.Test; +import org.onap.dcae.restapi.ApiException; +import org.onap.dcae.restapi.ApiException.ExceptionType; + +public class ApiExceptionTest { + + + @Test + public void shouldStringifyPolicyExceptionTypeAccordingToSpecification() { + assertEquals(ExceptionType.POLICY_EXCEPTION.toString(), "PolicyException"); + } + + @Test + public void shouldConvertExceptionToBackwardCompatibleFormat() { + JSONObject responseBody = ApiException.UNAUTHORIZED_USER.toJSON(); + assertEquals(responseBody.toString(), new JSONObject("" + + "{ " + + " 'requestError': { " + + " 'PolicyException': { " + + " 'messageId': 'POL2000', " + + " 'text': 'Unauthorized user' " + + " } " + + " } " + + "} " + .replace("'", "\"") + ).toString()); + } +} diff --git a/src/test/java/org/onap/dcae/common/AuthTypeTest.java b/src/test/java/org/onap/dcae/common/AuthTypeTest.java new file mode 100644 index 0000000..a8a8729 --- /dev/null +++ b/src/test/java/org/onap/dcae/common/AuthTypeTest.java @@ -0,0 +1,42 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2018-2019 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 org.onap.dcae.common.AuthType; + +import static org.junit.Assert.*; + +public class AuthTypeTest { + + @Test + public void fromString() { + assertEquals(AuthType.BASIC, AuthType.fromString("basic")); + assertEquals(AuthType.DIGEST, AuthType.fromString("digest")); + assertEquals(AuthType.OAUTH, AuthType.fromString("oauth")); + assertEquals(AuthType.NONE, AuthType.fromString("none")); + assertEquals(AuthType.Unspecified, AuthType.fromString("unspecified")); + } + + @Test(expected = IllegalArgumentException.class) + public void fromStringWithException() { + AuthType.fromString("test"); + } +} \ No newline at end of file diff --git a/src/test/java/org/onap/dcae/common/DataChangeEventListnerTest.java b/src/test/java/org/onap/dcae/common/DataChangeEventListnerTest.java new file mode 100644 index 0000000..95c8012 --- /dev/null +++ b/src/test/java/org/onap/dcae/common/DataChangeEventListnerTest.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2018-2019 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.glassfish.jersey.media.sse.EventInput; +import org.glassfish.jersey.media.sse.InboundEvent; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import static org.mockito.Mockito.*; + +import org.onap.dcae.RestConfCollector; +import org.onap.dcae.common.publishing.DMaaPConfigurationParser; +import org.onap.dcae.common.publishing.EventPublisher; + + +import org.slf4j.LoggerFactory; + +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.concurrent.LinkedBlockingQueue; + +@RunWith(MockitoJUnitRunner.class) +public class DataChangeEventListnerTest { + @Mock + InboundEvent event; + + @Test + public void testDataChangeEventListenerString() { + when(event.readData()).thenReturn(""); + DataChangeEventListener listner = new DataChangeEventListener(null); + listner.onEvent(event); + } + + @Test + public void testDataChangeEventListenerJsonObject() { + when(event.readData()).thenReturn("{\"name\":\"john\",\"age\":22,\"class\":\"mca\"}"); + RestConfCollector.fProcessingInputQueue = new LinkedBlockingQueue<>(4); + DataChangeEventListener listner = new DataChangeEventListener(null); + listner.onEvent(event); + } + @Test + public void testDataChangeEventListenerJsonArray() { + when(event.readData()).thenReturn("[{ \"name\":\"Ford\", \"models\":[ \"Fiesta\",\"Focus\", \"Mustang\" ] },{\"name\":\"BMW\", \"models\":[ \"320\", \"X3\",\"X5\" ] },{\"name\":\"Fiat\",\"models\":[ \"500\", \"Panda\" ]}]"); + RestConfCollector.fProcessingInputQueue = new LinkedBlockingQueue<>(4); + DataChangeEventListener listner = new DataChangeEventListener(null); + listner.onEvent(event); + } +} \ No newline at end of file diff --git a/src/test/java/org/onap/dcae/common/EventConnectionStateTest.java b/src/test/java/org/onap/dcae/common/EventConnectionStateTest.java new file mode 100644 index 0000000..c6327bc --- /dev/null +++ b/src/test/java/org/onap/dcae/common/EventConnectionStateTest.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2018-2019 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; + +public class EventConnectionStateTest { + + @Test + public void fromString() { + assertEquals(EventConnectionState.INIT, EventConnectionState.fromString("init")); + assertEquals(EventConnectionState.SUBSCRIBED, EventConnectionState.fromString("subscribed")); + assertEquals(EventConnectionState.UNSUBSCRIBED, EventConnectionState.fromString("unsubscribed")); + assertEquals(EventConnectionState.Unspecified, EventConnectionState.fromString("unspecified")); + } + + @Test(expected = IllegalArgumentException.class) + public void fromStringWithException() { + EventConnectionState.fromString("test"); + } +} \ No newline at end of file diff --git a/src/test/java/org/onap/dcae/common/EventProcessorTest.java b/src/test/java/org/onap/dcae/common/EventProcessorTest.java new file mode 100644 index 0000000..f32cc2e --- /dev/null +++ b/src/test/java/org/onap/dcae/common/EventProcessorTest.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2018-2019 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.json.JSONObject; +import org.junit.Before; + + +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.RestConfCollector; +import org.onap.dcae.common.publishing.DMaaPConfigurationParser; +import org.onap.dcae.common.publishing.EventPublisher; +import org.onap.dcae.common.publishing.PublisherConfig; +import org.onap.dcae.controller.AccessController; +import org.onap.dcae.controller.PersistentEventConnection; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.test.mock.mockito.MockBean; + + +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.concurrent.LinkedBlockingQueue; + + + +import static io.vavr.API.Map; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.when; +import static org.onap.dcae.common.publishing.DMaaPConfigurationParser.parseToDomainMapping; + +@RunWith(MockitoJUnitRunner.Silent.class) +public class EventProcessorTest { + + + + @Mock + private ApplicationSettings properties; + + private EventPublisher eventPublisher; + + Path path = Paths.get("src/test/resources/testParseDMaaPCredentialsLegacy.json"); + java.util.Map streamMap; + 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"); + + @Before + public void setUp() { + eventPublisher = EventPublisher.createPublisher(LoggerFactory.getLogger("some_log"), DMaaPConfigurationParser. + parseToDomainMapping(path).get()); + streamMap = RestConfCollector.parseStreamIdToStreamHashMapping("notification=device-registration"); + + } + + @Test + public void testEventProcessorRunException() { + 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.rcc_keystoreFileLocation()).thenReturn(RCC_KEYSTORE.toString()); + when(properties.rcc_keystorePasswordFileLocation()).thenReturn(RCC_KEYSTORE_PASSWORD_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\",\"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 p = new PersistentEventConnection("","",true, "", + "","","","1234646346", acClr); + RestConfCollector.fProcessingInputQueue = new LinkedBlockingQueue<>(4); + RestConfCollector.fProcessingInputQueue.offer(new EventData(p, new JSONObject("{}"))); + RestConfCollector.fProcessingInputQueue.offer(new EventData(null, null)); + EventProcessor ev = new EventProcessor(eventPublisher, streamMap); + ev.run(); + } +} \ No newline at end of file diff --git a/src/test/java/org/onap/dcae/common/FormatTest.java b/src/test/java/org/onap/dcae/common/FormatTest.java new file mode 100644 index 0000000..e54dd9b --- /dev/null +++ b/src/test/java/org/onap/dcae/common/FormatTest.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2018-2019 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 org.onap.dcae.common.Format; + +import static org.junit.Assert.assertEquals; + +public class FormatTest { + + @Test + public void fromString() { + assertEquals(Format.JSON, Format.fromString("json")); + assertEquals(Format.XML, Format.fromString("xml")); + assertEquals(Format.NONE, Format.fromString("none")); + } + + @Test(expected = IllegalArgumentException.class) + public void fromStringWithException() { + Format.fromString("test"); + } +} \ No newline at end of file diff --git a/src/test/java/org/onap/dcae/common/RestConfContextTest.java b/src/test/java/org/onap/dcae/common/RestConfContextTest.java new file mode 100644 index 0000000..00b07f8 --- /dev/null +++ b/src/test/java/org/onap/dcae/common/RestConfContextTest.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2018-2019 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 org.onap.dcae.common.RestConfContext; + +import static org.junit.Assert.*; + +public class RestConfContextTest { + + @Test + public void setAttribute() { + String key = "key"; + String value = "value"; + RestConfContext restConfContext = new RestConfContext(); + restConfContext.setAttribute(key, value); + assertEquals(value, restConfContext.getAttribute(key)); + restConfContext.setAttribute(key, null); + assertFalse(restConfContext.getAttributeKeySet().contains(key)); + } + + @Test + public void getAttributeKeySet() { + String key = "key"; + String value = "value"; + String key1 = "key1"; + String value1 = "value1"; + RestConfContext restConfContext = new RestConfContext(); + restConfContext.setAttribute(key,value); + restConfContext.setAttribute(key1,value1); + assertTrue(restConfContext.getAttributeKeySet().contains(key) && restConfContext.getAttributeKeySet().contains(key1)); + } +} \ No newline at end of file diff --git a/src/test/java/org/onap/dcae/common/XmlJsonUtilTest.java b/src/test/java/org/onap/dcae/common/XmlJsonUtilTest.java new file mode 100644 index 0000000..3cf065e --- /dev/null +++ b/src/test/java/org/onap/dcae/common/XmlJsonUtilTest.java @@ -0,0 +1,81 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2018-2019 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.json.XML; +import org.junit.Test; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import static org.junit.Assert.assertEquals; + +public class XmlJsonUtilTest { + + @Test + public void getJsonOrXmlTest() { + String var = "result"; + Map mm = new HashMap<>(); + + + mm.put("result.time", "2018 12:04"); + mm.put("result.status", "200"); + mm.put("result.output", "xml2json"); + mm.put("result.[", "start"); + mm.put("result.]", "end"); + try { + String str = XmlJsonUtil.getXml(mm, var); + assertEquals(str.startsWith("<"), true); + String str2 = XmlJsonUtil.getJson(mm, var); + assertEquals(str2.startsWith("{"), true); + }catch (Exception e) {} + } + + @Test + public void removeEmptystructFromXml() { + String var = "\n" + + "t2\n" + + "bad\n" + + "200"; + Map mm = new HashMap<>(); + try { + String str = XmlJsonUtil.removeEmptyStructXml(var); + + }catch (Exception e) {} + } + + @Test + public void removeEmptystructFromJson() { + String var = "{\n" + + "\t\"output\": \"xml2json\",\n" + + "\t\"time\": \"2018 12:04\",\n" + + "\t\"\": \"end\",\n" + + "\t\"status\": \"200\"\n" + + "}"; + Map mm = new HashMap<>(); + + try { + String str = XmlJsonUtil.removeEmptyStructJson(var); + }catch (Exception e) {} + } +} \ No newline at end of file diff --git a/src/test/java/org/onap/dcae/common/XmlParserTest.java b/src/test/java/org/onap/dcae/common/XmlParserTest.java new file mode 100644 index 0000000..b005c89 --- /dev/null +++ b/src/test/java/org/onap/dcae/common/XmlParserTest.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2018-2019 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 java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import static org.junit.Assert.*; + +public class XmlParserTest { + + @Test + public void setAttribute() { + String convert = "\n" + + "t2\n" + + "200"; + Set listNameList = new HashSet<>(); + listNameList.add("result"); + Map propMap; + try { + propMap = XmlParser.convertToProperties(convert, listNameList); + System.out.println(propMap); + }catch (Exception e) {} + } +} \ 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 new file mode 100644 index 0000000..2865b75 --- /dev/null +++ b/src/test/java/org/onap/dcae/common/publishing/DMaaPEventPublisherTest.java @@ -0,0 +1,79 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2018 Nokia. All rights reserved. + * Copyright (C) 2018-2019 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.publishing; + +import static io.vavr.API.Option; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.att.nsa.cambria.client.CambriaBatchingPublisher; +import java.io.IOException; +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; + +public class DMaaPEventPublisherTest { + + private static final String STREAM_ID = "sampleStreamId"; + + private DMaaPEventPublisher eventPublisher; + private CambriaBatchingPublisher cambriaPublisher; + private DMaaPPublishersCache DMaaPPublishersCache; + + @Before + public void setUp() { + cambriaPublisher = mock(CambriaBatchingPublisher.class); + DMaaPPublishersCache = mock(DMaaPPublishersCache.class); + when(DMaaPPublishersCache.getPublisher(anyString())).thenReturn(Option(cambriaPublisher)); + eventPublisher = new DMaaPEventPublisher(DMaaPPublishersCache, mock(Logger.class)); + } + + @Test + public void shouldSendEventToTopic() throws Exception { + // given + JSONObject event = new JSONObject("{}"); + + // when + eventPublisher.sendEvent(event, STREAM_ID); + + // then + verify(cambriaPublisher).send("MyPartitionKey", event.toString()); + } + + + + @Test + public void shouldCloseConnectionWhenExceptionOccurred() throws Exception { + // given + JSONObject event = new JSONObject("{}"); + given(cambriaPublisher.send(anyString(), anyString())).willThrow(new IOException("epic fail")); + + // when + eventPublisher.sendEvent(event, STREAM_ID); + + // then + verify(DMaaPPublishersCache).closePublisherFor(STREAM_ID); + } +} \ No newline at end of file diff --git a/src/test/java/org/onap/dcae/common/publishing/DMaaPPublishersCacheTest.java b/src/test/java/org/onap/dcae/common/publishing/DMaaPPublishersCacheTest.java new file mode 100644 index 0000000..2884e44 --- /dev/null +++ b/src/test/java/org/onap/dcae/common/publishing/DMaaPPublishersCacheTest.java @@ -0,0 +1,127 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2018 Nokia. All rights reserved. + * Copyright (C) 2018-2019 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.publishing; + +import static io.vavr.API.List; +import static io.vavr.API.Map; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; + +import com.att.nsa.cambria.client.CambriaBatchingPublisher; +import io.vavr.collection.Map; +import io.vavr.control.Option; +import java.io.IOException; +import java.util.concurrent.TimeUnit; +import org.junit.Before; +import org.junit.Test; +import org.onap.dcae.common.publishing.DMaaPPublishersCache.CambriaPublishersCacheLoader; +import org.onap.dcae.common.publishing.DMaaPPublishersCache.OnPublisherRemovalListener; + + +public class DMaaPPublishersCacheTest { + + private String streamId1; + private Map dMaaPConfigs; + + @Before + public void setUp() { + streamId1 = "sampleStream1"; + dMaaPConfigs = Map("sampleStream1", new PublisherConfig(List("destination1"), "topic1")); + } + + @Test + public void shouldReturnTheSameCachedInstanceOnConsecutiveRetrievals() { + // given + DMaaPPublishersCache dMaaPPublishersCache = new DMaaPPublishersCache(dMaaPConfigs); + + // when + Option firstPublisher = dMaaPPublishersCache.getPublisher(streamId1); + Option secondPublisher = dMaaPPublishersCache.getPublisher(streamId1); + + // then + assertSame("should return same instance", firstPublisher.get(), secondPublisher.get()); + } + + @Test + public void shouldCloseCambriaPublisherOnCacheInvalidate() throws IOException, InterruptedException { + // given + CambriaBatchingPublisher cambriaPublisherMock1 = mock(CambriaBatchingPublisher.class); + CambriaPublishersCacheLoader cacheLoaderMock = mock(CambriaPublishersCacheLoader.class); + DMaaPPublishersCache dMaaPPublishersCache = new DMaaPPublishersCache(cacheLoaderMock, + new OnPublisherRemovalListener(), + dMaaPConfigs); + when(cacheLoaderMock.load(streamId1)).thenReturn(cambriaPublisherMock1); + + // when + dMaaPPublishersCache.getPublisher(streamId1); + dMaaPPublishersCache.closePublisherFor(streamId1); + + // then + verify(cambriaPublisherMock1).close(20, TimeUnit.SECONDS); + + } + + @Test + public void shouldReturnNoneIfThereIsNoDMaaPConfigurationForGivenStreamID() { + // given + DMaaPPublishersCache dMaaPPublishersCache = new DMaaPPublishersCache(dMaaPConfigs); + + // then + assertTrue("should not exist", dMaaPPublishersCache.getPublisher("non-existing").isEmpty()); + } + + + @Test + public void shouldCloseOnlyChangedPublishers() throws IOException, InterruptedException { + // given + CambriaBatchingPublisher cambriaPublisherMock1 = mock(CambriaBatchingPublisher.class); + CambriaBatchingPublisher cambriaPublisherMock2 = mock(CambriaBatchingPublisher.class); + CambriaPublishersCacheLoader cacheLoaderMock = mock(CambriaPublishersCacheLoader.class); + String firstDomain = "domain1"; + String secondDomain = "domain2"; + Map oldConfig = Map(firstDomain, + new PublisherConfig(List("destination1"), "topic1"), + secondDomain, + new PublisherConfig(List("destination2"), "topic2", + "user", "pass")); + Map newConfig = Map(firstDomain, new PublisherConfig(List("destination1"), "topic1"), + secondDomain, new PublisherConfig(List("destination2"), "topic2")); + DMaaPPublishersCache dMaaPPublishersCache = new DMaaPPublishersCache(cacheLoaderMock, + new OnPublisherRemovalListener(), + oldConfig); + when(cacheLoaderMock.load(firstDomain)).thenReturn(cambriaPublisherMock1); + when(cacheLoaderMock.load(secondDomain)).thenReturn(cambriaPublisherMock2); + + dMaaPPublishersCache.getPublisher(firstDomain); + dMaaPPublishersCache.getPublisher(secondDomain); + + // when + dMaaPPublishersCache.reconfigure(newConfig); + + // then + verify(cambriaPublisherMock2).close(20, TimeUnit.SECONDS); + verifyZeroInteractions(cambriaPublisherMock1); + } +} \ No newline at end of file diff --git a/src/test/java/org/onap/dcae/common/publishing/JsonParserTest.java b/src/test/java/org/onap/dcae/common/publishing/JsonParserTest.java new file mode 100644 index 0000000..f00df2c --- /dev/null +++ b/src/test/java/org/onap/dcae/common/publishing/JsonParserTest.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2018-2019 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.publishing; + +import java.util.Map; + +import org.junit.Test; +import org.onap.dcae.common.JsonParser; + +import junit.framework.Assert; + + +public class JsonParserTest { + + @Test + public void convertToPropertiesTest() throws Exception { + String testJson="{\"prop2\"=\"value\", \"prop1\"=\"value\"}"; + Map response= JsonParser.convertToProperties(testJson); + Assert.assertEquals("value", response.get("prop2")); + } +} diff --git a/src/test/java/org/onap/dcae/controller/ConfigCBSSourceTest.java b/src/test/java/org/onap/dcae/controller/ConfigCBSSourceTest.java new file mode 100644 index 0000000..5c8593e --- /dev/null +++ b/src/test/java/org/onap/dcae/controller/ConfigCBSSourceTest.java @@ -0,0 +1,151 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2018-2019 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 com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.onap.dcae.TestingUtilities.assertFailureHasInfo; +import static org.onap.dcae.controller.ConfigSource.getAppConfig; + +import io.vavr.control.Try; +import org.json.JSONObject; +import org.junit.Test; +import org.onap.dcae.WiremockBasedTest; + + +public class ConfigCBSSourceTest extends WiremockBasedTest { + + @Test + public void shouldReturnValidAppConfiguration() { + // given + String sampleConfigForVES = "{\"collector.rcc.service.port\": 8686}"; + + stubConsulToReturnLocalAddressOfCBS(); + stubCBSToReturnAppConfig(sampleConfigForVES); + + // when + Try actual = tryToGetConfig(); + + // then + assertThat(actual.get().toString()).isEqualTo(new JSONObject(sampleConfigForVES).toString()); + } + + @Test + public void shouldReturnFailureOnFailureToCommunicateWithConsul() { + // given + stubFor(get(urlEqualTo("/v1/catalog/service/CBSName")) + .willReturn(aResponse().withStatus(400))); + + // when + Try actual = tryToGetConfig(); + + // then + assertFailureHasInfo(actual, "HTTP", "Consul", "400", + "http://localhost:" + wireMockRule.port() + "/v1/catalog/service/CBSName"); + } + + @Test + public void shouldReturnFailureOnBadJsonFromConsul() { + // given + stubFor(get(urlEqualTo("/v1/catalog/service/CBSName")) + .willReturn(aResponse().withStatus(200).withBody("[{"))); + + // when + Try actual = tryToGetConfig(); + + // then + assertFailureHasInfo(actual, "JSON", "array", "[{"); + } + + @Test + public void shouldReturnFailureOnInvalidCatalogFormat() { + // given + String notAListCatalog = "" + + "{" + + "\"ServiceAddress\":\"localhost\"," + + "\"ServicePort\":" + wireMockRule.port() + + "}"; + + stubFor(get(urlEqualTo("/v1/catalog/service/CBSName")) + .willReturn(aResponse().withStatus(200).withBody(notAListCatalog))); + + // when + Try actual = tryToGetConfig(); + + // then + assertFailureHasInfo(actual, "JSON", "array", notAListCatalog); + } + + + @Test + public void shouldReturnFailureIfConfigIsMissingRequiredProperties() { + // given + String actualConf = "{\"ServicePort\":" + wireMockRule.port() + "}"; + String asCatalog = "[" + actualConf + "]"; + + stubFor(get(urlEqualTo("/v1/catalog/service/CBSName")) + .willReturn(aResponse().withStatus(200).withBody(asCatalog))); + + // when + Try actual = tryToGetConfig(); + + // then + assertFailureHasInfo(actual, "ServiceAddress", "ServicePort", "missing", actualConf); + } + + + @Test + public void shouldReturnFailureOnFailureToCommunicateWithCBS() { + // given + stubFor(get(urlEqualTo("/v1/catalog/service/CBSName")) + .willReturn(aResponse().withStatus(200).withBody(validLocalCBSConf()))); + stubFor(get(urlEqualTo("/service_component/restconfcollector")) + .willReturn(aResponse().withStatus(400))); + + // when + Try actual = tryToGetConfig(); + + // then + assertFailureHasInfo(actual, "HTTP", "CBS", "400", + "http://localhost:" + wireMockRule.port() + "/service_component/restconfcollector"); + } + + @Test + public void shouldReturnFailureIfAppIsInvalidJsonDocument() { + // given + String invalidAppConf = "[$"; + stubConsulToReturnLocalAddressOfCBS(); + stubCBSToReturnAppConfig(invalidAppConf); + + // when + Try actual = tryToGetConfig(); + + // then + assertFailureHasInfo(actual, "JSON", "document", invalidAppConf); + } + + private Try tryToGetConfig() { + return getAppConfig(new EnvProps("http", "localhost", wireMockRule.port(), "http", "CBSName", "restconfcollector")); + } +} + diff --git a/src/test/java/org/onap/dcae/controller/ConfigFilesFacadeTest.java b/src/test/java/org/onap/dcae/controller/ConfigFilesFacadeTest.java new file mode 100644 index 0000000..4130ceb --- /dev/null +++ b/src/test/java/org/onap/dcae/controller/ConfigFilesFacadeTest.java @@ -0,0 +1,140 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018 Nokia. All rights reserved. + * Copyright (C) 2018-2019 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 io.vavr.API.Map; +import static io.vavr.API.Some; +import static org.assertj.core.api.Assertions.assertThat; +import static org.onap.dcae.TestingUtilities.assertFailureHasInfo; +import static org.onap.dcae.TestingUtilities.assertJSONObjectsEqual; +import static org.onap.dcae.TestingUtilities.createTemporaryFile; +import static org.onap.dcae.TestingUtilities.readFile; +import static org.onap.dcae.TestingUtilities.readJSONFromFile; + +import io.vavr.collection.Map; +import io.vavr.control.Try; +import java.nio.file.Path; +import java.nio.file.Paths; +import org.json.JSONObject; +import org.junit.Test; + +public class ConfigFilesFacadeTest { + + private static final Path NON_EXISTENT = Paths.get("/non-existent"); + private static final ConfigFilesFacade TO_NON_EXISTENT_POINTING_FACADE = new ConfigFilesFacade(NON_EXISTENT, + NON_EXISTENT); + + @Test + public void shouldReadPropertyFile() { + // given + Path temporaryFile = createTemporaryFile("some.property=10"); + + // when + ConfigFilesFacade configFilesFacade = new ConfigFilesFacade(temporaryFile, temporaryFile); + + Try> propertiesConfigurations = configFilesFacade.readCollectorProperties(); + + // then + assertThat(propertiesConfigurations.isSuccess()).isTrue(); + assertThat(propertiesConfigurations.get().containsKey("some.property")).isTrue(); + assertThat(propertiesConfigurations.get().get("some.property")).isEqualTo(Some("10")); + } + + + @Test + public void shouldReadDMaaPFile() { + // given + Path temporaryFile = createTemporaryFile("{}"); + + // when + ConfigFilesFacade configFilesFacade = new ConfigFilesFacade(temporaryFile, temporaryFile); + + Try dMaaPConfiguration = configFilesFacade.readDMaaPConfiguration(); + + // then + assertThat(dMaaPConfiguration.isSuccess()).isTrue(); + assertThat(dMaaPConfiguration.get().toString()).isEqualTo("{}"); + } + + @Test + public void shouldWriteDMaaPConf() { + // given + Path temporaryFile = createTemporaryFile("{}"); + JSONObject desiredConf = new JSONObject("{\"key\": 1}"); + + // when + ConfigFilesFacade configFilesFacade = new ConfigFilesFacade(temporaryFile, temporaryFile); + + Try propertiesConfigurations = configFilesFacade.writeDMaaPConfiguration(desiredConf); + + // then + assertThat(propertiesConfigurations.isSuccess()).isTrue(); + assertJSONObjectsEqual(readJSONFromFile(temporaryFile), desiredConf); + } + + + @Test + public void shouldWriteProperties() { + // given + Path temporaryFile = createTemporaryFile("{}"); + + // when + ConfigFilesFacade configFilesFacade = new ConfigFilesFacade(temporaryFile, temporaryFile); + Try propertiesConfigurations = configFilesFacade.writeProperties(Map("prop1", "hi")); + + // then + assertThat(propertiesConfigurations.isSuccess()).isTrue(); + assertThat(readFile(temporaryFile).trim()).isEqualTo("prop1 = hi"); + } + + @Test + public void shouldContainPropertiesPathInCaseOfFailures() { + Try> result = TO_NON_EXISTENT_POINTING_FACADE.readCollectorProperties(); + assertThat(result.isFailure()).isTrue(); + assertFailureHasInfo(result, NON_EXISTENT.toString()); + } + + @Test + public void shouldContainDMaaPPathPathInCaseOfFailures() { + Try result = TO_NON_EXISTENT_POINTING_FACADE.readDMaaPConfiguration(); + assertThat(result.isFailure()).isTrue(); + assertFailureHasInfo(result, NON_EXISTENT.toString()); + } + + @Test + public void shouldContainPropertiesPathPathInCaseOfFailuresOnWrite() { + // given + Try result = TO_NON_EXISTENT_POINTING_FACADE.writeProperties(Map("any", "any")); + assertThat(result.isFailure()).isTrue(); + assertFailureHasInfo(result, NON_EXISTENT.toString()); + } + + @Test + public void shouldContainDMaaPPathPathInCaseOfFailuresOnWrite() { + // given + Try result = TO_NON_EXISTENT_POINTING_FACADE.writeDMaaPConfiguration(new JSONObject()); + assertThat(result.isFailure()).isTrue(); + assertFailureHasInfo(result, NON_EXISTENT.toString()); + } + +} + diff --git a/src/test/java/org/onap/dcae/controller/ConfigLoaderIntegrationE2ETest.java b/src/test/java/org/onap/dcae/controller/ConfigLoaderIntegrationE2ETest.java new file mode 100644 index 0000000..730a98d --- /dev/null +++ b/src/test/java/org/onap/dcae/controller/ConfigLoaderIntegrationE2ETest.java @@ -0,0 +1,98 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018 Nokia. All rights reserved. + * Copyright (C) 2018-2019 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 io.vavr.API.Map; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.when; +import static org.onap.dcae.TestingUtilities.createTemporaryFile; +import static org.onap.dcae.TestingUtilities.readFile; +import static org.onap.dcae.TestingUtilities.readJSONFromFile; +import static org.onap.dcae.common.publishing.VavrUtils.f; + +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.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.dcae.ApplicationSettings; +import org.onap.dcae.RestConfCollector; +import org.onap.dcae.WiremockBasedTest; +import org.onap.dcae.common.publishing.DMaaPConfigurationParser; +import org.onap.dcae.common.publishing.EventPublisher; + +public class ConfigLoaderIntegrationE2ETest extends WiremockBasedTest { + + @Test + public void testSuccessfulE2EFlow() { + // given +// Path dMaaPConfigFile = createTemporaryFile("{}"); +// Path collectorPropertiesFile = createTemporaryFile(""); +// Path dMaaPConfigSource = Paths.get("src/test/resources/testParseDMaaPCredentialsGen2.json"); +// JSONObject dMaaPConf = readJSONFromFile(dMaaPConfigSource); +// stubConsulToReturnLocalAddressOfCBS(); +// stubCBSToReturnAppConfig(f("{\"collector.port\": 8686, \"streams_publishes\": %s}}", dMaaPConf)); +// +// EventPublisher eventPublisherMock = mock(EventPublisher.class); +// +// Mockito.mock(RestConfCollector.class); +// ConfigFilesFacade configFilesFacade = new ConfigFilesFacade(dMaaPConfigFile, collectorPropertiesFile); +// ConfigLoader configLoader = new ConfigLoader(eventPublisherMock::reconfigure, configFilesFacade, ConfigSource::getAppConfig, () -> wiremockBasedEnvProps()); +// configLoader.updateConfig(); +// +// // then +// assertThat(readJSONFromFile(dMaaPConfigSource).toString()).isEqualTo(dMaaPConf.toString()); +// assertThat(readFile(collectorPropertiesFile).trim()).isEqualTo("collector.port = 8686"); +// verify(eventPublisherMock, times(1)).reconfigure( +// DMaaPConfigurationParser.parseToDomainMapping(dMaaPConf).get() +// ); + } + + @Test + public void shouldNotReconfigureNotOverwriteIfConfigurationHasNotChanged() { + // given + Path dMaaPConfigFile = createTemporaryFile("{}"); + Path collectorPropertiesFile = createTemporaryFile(""); + JSONObject dMaaPConf = readJSONFromFile(Paths.get("src/test/resources/testParseDMaaPCredentialsGen2.json")); + stubConsulToReturnLocalAddressOfCBS(); + stubCBSToReturnAppConfig(f("{\"collector.port\": 8686, \"streams_publishes\": %s}}", dMaaPConf)); + EventPublisher eventPublisherMock = mock(EventPublisher.class); + ConfigFilesFacade configFilesFacade = new ConfigFilesFacade(dMaaPConfigFile, collectorPropertiesFile); + configFilesFacade.writeProperties(Map("collector.port", "8686")); + configFilesFacade.writeDMaaPConfiguration(dMaaPConf); + + // when + ConfigLoader configLoader = new ConfigLoader(eventPublisherMock::reconfigure, configFilesFacade, ConfigSource::getAppConfig, () -> wiremockBasedEnvProps()); + configLoader.updateConfig(); + + // then + verifyZeroInteractions(eventPublisherMock); + } + +} \ No newline at end of file diff --git a/src/test/java/org/onap/dcae/controller/ConfigParsingTest.java b/src/test/java/org/onap/dcae/controller/ConfigParsingTest.java new file mode 100644 index 0000000..7792b71 --- /dev/null +++ b/src/test/java/org/onap/dcae/controller/ConfigParsingTest.java @@ -0,0 +1,79 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018 Nokia. All rights reserved. + * Copyright (C) 2018-2019 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 io.vavr.API.Map; +import static org.assertj.core.api.Assertions.assertThat; +import static org.onap.dcae.TestingUtilities.assertJSONObjectsEqual; +import static org.onap.dcae.TestingUtilities.readJSONFromFile; + +import io.vavr.collection.Map; +import io.vavr.control.Option; + +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.junit.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.Silent.class) +public class ConfigParsingTest { + + @Test + public void shouldReturnDMaaPConfig() { + JSONObject dMaaPConf = new JSONObject("{\"auth-credentials-present\": {\"aaf_username\": \"sampleUser\",\"dmaap_info\": {\"topic_url\": \"http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV\",},\"aaf_password\": \"samplePassword\"}}"); + JSONObject root = new JSONObject(); + root.put("key1", "someProperty"); + root.put("key2", "someProperty"); + root.put("streams_publishes", dMaaPConf); + + Option dMaaPConfig = ConfigParsing.getDMaaPConfig(root); + + assertThat(dMaaPConfig.isEmpty()).isFalse(); + assertJSONObjectsEqual(dMaaPConfig.get(), dMaaPConf); + } + + @Test + public void shouldReturnEmptyIfDMaaPConfigIsInvalid() { + JSONObject root = new JSONObject(); + root.put("streams_publishes", 1); + + Option dMaaPConfig = ConfigParsing.getDMaaPConfig(root); + + assertThat(dMaaPConfig.isEmpty()).isTrue(); + } + + @Test + public void getProperties() { + JSONObject dMaaPConf = new JSONObject("{\"auth-credentials-present\": {\"aaf_username\": \"sampleUser\",\"dmaap_info\": {\"topic_url\": \"http://UEBHOST:3904/events/DCAE-SE-COLLECTOR-EVENTS-DEV\",},\"aaf_password\": \"samplePassword\"}}"); + JSONObject root = new JSONObject(); + root.put("key1", "someProperty"); + root.put("key2", "someProperty"); + root.put("streams_publishes", dMaaPConf); + + Map properties = ConfigParsing.getProperties(root); + assertThat(properties).isEqualTo(Map("key1", "someProperty", "key2", "someProperty")); + } +} \ No newline at end of file diff --git a/src/test/java/org/onap/dcae/controller/EnvPropertiesReaderTest.java b/src/test/java/org/onap/dcae/controller/EnvPropertiesReaderTest.java new file mode 100644 index 0000000..2e215a7 --- /dev/null +++ b/src/test/java/org/onap/dcae/controller/EnvPropertiesReaderTest.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018 Nokia. All rights reserved. + * Copyright (C) 2018-2019 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 io.vavr.API.Map; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.onap.dcae.controller.EnvPropertiesReader.readEnvProps; + +import io.vavr.collection.Map; +import org.junit.Test; + + +public class EnvPropertiesReaderTest { + + @Test + public void shouldReturnEmptyOnMissingConsulHost() { + Map envs = Map( + "CONFIG_BINDING_SERVICE", "doesNotMatter", + "HOSTNAME", "doesNotMatter"); + assertTrue(readEnvProps(envs).isEmpty()); + } + + @Test + public void shouldReturnEmptyOnMissingCBSName() { + Map envs = Map( + "CONSUL_HOST", "doesNotMatter", + "HOSTNAME", "doesNotMatter"); + assertTrue(readEnvProps(envs).isEmpty()); + } + + @Test + public void shouldReturnEmptyOnMissingVESAppName() { + Map envs = Map( + "CONSUL_HOST", "doesNotMatter", + "CONFIG_BINDING_SERVICE", "doesNotMatter"); + assertTrue(readEnvProps(envs).isEmpty()); + } + + @Test + public void shouldReturnSomeOfAllProperties() { + Map envs = Map( + "CONSUL_HOST", "doesNotMatter", + "HOSTNAME", "doesNotMatter", + "CONFIG_BINDING_SERVICE", "doesNotMatter"); + assertFalse(readEnvProps(envs).isEmpty()); + } + +} + diff --git a/src/test/java/org/onap/dcae/controller/EnvPropsTest.java b/src/test/java/org/onap/dcae/controller/EnvPropsTest.java new file mode 100644 index 0000000..e9c194e --- /dev/null +++ b/src/test/java/org/onap/dcae/controller/EnvPropsTest.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2018-2019 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 com.github.tomakehurst.wiremock.junit.WireMockRule; +import junit.framework.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.onap.dcae.common.Format; + + +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; +import static org.junit.Assert.assertEquals; + +public class EnvPropsTest { + @Rule + public WireMockRule wireMockRule = new WireMockRule( + wireMockConfig().dynamicPort().dynamicHttpsPort().keystorePath(null)); + @Test + public void fromString() { + Assert.assertEquals(new EnvProps("http", "localhost", wireMockRule.port(), "http", "CBSName", "restconfcollector").equals(new EnvProps("http", "localhost", wireMockRule.port(), "http", "CBSName", "restconfcollector")), true); + } +} \ No newline at end of file diff --git a/src/test/java/org/onap/dcae/restapi/ApiAuthInterceptionTest.java b/src/test/java/org/onap/dcae/restapi/ApiAuthInterceptionTest.java new file mode 100644 index 0000000..1427438 --- /dev/null +++ b/src/test/java/org/onap/dcae/restapi/ApiAuthInterceptionTest.java @@ -0,0 +1,177 @@ +/*- + * ============LICENSE_START======================================================= + * org.onap.dcaegen2.restconfcollector + * ================================================================================ + * Copyright (C) 2018 Nokia. All rights reserved. + * Copyright (C) 2018-2019 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.restapi; + +import io.vavr.collection.HashMap; +import io.vavr.collection.Map; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.dcae.ApplicationSettings; +import org.slf4j.Logger; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.Silent.class) +public class ApiAuthInterceptionTest { + private static final String USERNAME = "Foo"; + private static final String PASSWORD = "Bar"; + private static final Map CREDENTIALS = HashMap.of(USERNAME, PASSWORD); + + @Mock + private Logger log; + + @Mock + private ApplicationSettings settings; + + @Mock + private HttpServletResponse response; + + @Mock + private Object obj; + + @Mock + private PrintWriter writer; + + @InjectMocks + private ApiAuthInterceptor sut; + + + private HttpServletRequest createEmptyRequest() { + return MockMvcRequestBuilders + .post("") + .buildRequest(null); + } + + private HttpServletRequest createRequestWithAuthorizationHeader() { + return SecurityMockMvcRequestPostProcessors + .httpBasic(USERNAME, PASSWORD) + .postProcessRequest( + MockMvcRequestBuilders + .post("") + .buildRequest(null)); + } + + @Test + public void shouldSucceedWhenAuthorizationIsDisabled() throws IOException { + // given + final HttpServletRequest request = createEmptyRequest(); + + when(settings.authorizationEnabled()).thenReturn(false); + + // when + final boolean isAuthorized = sut.preHandle(request, response, obj); + + // then + assertTrue(isAuthorized); + } + + @Test + public void shouldFailDueToEmptyBasicAuthorizationHeader() throws IOException { + // given + final HttpServletRequest request = createEmptyRequest(); + + when(settings.authorizationEnabled()).thenReturn(true); + when(response.getWriter()).thenReturn(writer); + + // when + final boolean isAuthorized = sut.preHandle(request, response, obj); + + + // then + assertFalse(isAuthorized); + + verify(response).setStatus(HttpStatus.BAD_REQUEST.value()); + verify(writer).write(ApiException.UNAUTHORIZED_USER.toJSON().toString()); + } + + @Test + public void shouldFailDueToBasicAuthenticationUserMissingFromSettings() throws IOException { + // given + final HttpServletRequest request = createRequestWithAuthorizationHeader(); + + when(settings.authorizationEnabled()).thenReturn(true); + when(response.getWriter()).thenReturn(writer); + + // when + final boolean isAuthorized = sut.preHandle(request, response, obj); + + // then + assertFalse(isAuthorized); + + verify(response).setStatus(HttpStatus.BAD_REQUEST.value()); + verify(writer).write(ApiException.UNAUTHORIZED_USER.toJSON().toString()); + } + + @Test + public void shouldSucceed() throws IOException { + // given + final HttpServletRequest request = createRequestWithAuthorizationHeader(); + when(settings.authorizationEnabled()).thenReturn(true); + when(settings.validAuthorizationCredentials()).thenReturn( + HashMap.of(USERNAME, "$2a$10$BsZkEynNm/93wbAeeZuxJeu6IHRyQl4XReqDg2BtYOFDhUsz20.3G")); + when(response.getWriter()).thenReturn(writer); + + // when + final boolean isAuthorized = sut.preHandle(request, response, obj); + + // then + assertTrue(isAuthorized); + } + + @Test + public void shouldFailDueToInvalidBasicAuthorizationHeaderValue() throws IOException { + // given + final HttpServletRequest request = + MockMvcRequestBuilders + .post("") + .header(HttpHeaders.AUTHORIZATION, "FooBar") + .buildRequest(null); + + when(settings.authorizationEnabled()).thenReturn(true); + when(settings.validAuthorizationCredentials()).thenReturn(CREDENTIALS); + when(response.getWriter()).thenReturn(writer); + + // when + final boolean isAuthorized = sut.preHandle(request, response, obj); + + // then + assertFalse(isAuthorized); + + verify(response).setStatus(HttpStatus.BAD_REQUEST.value()); + verify(writer).write(ApiException.UNAUTHORIZED_USER.toJSON().toString()); + } +} -- cgit 1.2.3-korg