From c818065d90aad39e61992ee44fa13568b80ee7b3 Mon Sep 17 00:00:00 2001 From: s00370346 Date: Fri, 12 Jul 2019 11:35:54 +0530 Subject: Issue-ID: DCAEGEN2-1661 Fix Some Compilation warnings, sonar issue Signed-off-by: s00370346 Change-Id: Id01028b87c101ff2544d93c68a59f9cc46020d8d --- .../onap/dcae/common/DataChangeEventListener.java | 3 +- .../org/onap/dcae/common/EventConnectionState.java | 4 +- .../java/org/onap/dcae/common/EventProcessor.java | 12 +- .../org/onap/dcae/common/publishing/VavrUtils.java | 7 +- .../dcae/controller/PersistentEventConnection.java | 10 +- .../java/org/onap/dcae/AccessControllerTest.java | 160 ++++++++++++++--- .../org/onap/dcae/ApplicationSettingsTest.java | 95 ++++------ src/test/java/org/onap/dcae/CLIUtilsTest.java | 58 ------ src/test/java/org/onap/dcae/CliUtilsTest.java | 59 ++++++ .../org/onap/dcae/RestApiCallNodeUtilTest.java | 127 +++++++------ src/test/java/org/onap/dcae/TLSTest.java | 135 -------------- src/test/java/org/onap/dcae/TLSTestBase.java | 154 ---------------- src/test/java/org/onap/dcae/TestingUtilities.java | 71 ++++++-- src/test/java/org/onap/dcae/TlsTest.java | 138 +++++++++++++++ src/test/java/org/onap/dcae/TlsTestBase.java | 163 +++++++++++++++++ src/test/java/org/onap/dcae/WiremockBasedTest.java | 10 +- .../dcae/common/AdditionalHeaderWebTargetTest.java | 60 +++++-- .../java/org/onap/dcae/common/AuthTypeTest.java | 6 +- .../dcae/common/DataChangeEventListnerTest.java | 18 +- .../onap/dcae/common/EventConnectionStateTest.java | 7 +- .../org/onap/dcae/common/EventProcessorTest.java | 157 ++++++++-------- src/test/java/org/onap/dcae/common/FormatTest.java | 5 +- .../org/onap/dcae/common/RestApiCallNodeTest.java | 197 +++++++++++++++++++-- .../org/onap/dcae/common/RestConfContextTest.java | 10 +- .../java/org/onap/dcae/common/XmlJsonUtilTest.java | 59 ++++-- .../java/org/onap/dcae/common/XmlParserTest.java | 15 +- .../common/publishing/DMaaPEventPublisherTest.java | 14 +- .../publishing/DMaaPPublishersCacheTest.java | 61 +++++-- .../dcae/common/publishing/JsonParserTest.java | 28 +-- .../onap/dcae/controller/ConfigCBSSourceTest.java | 151 ---------------- .../onap/dcae/controller/ConfigCbsSourceTest.java | 153 ++++++++++++++++ .../dcae/controller/ConfigFilesFacadeTest.java | 23 +-- .../controller/ConfigLoaderIntegrationE2ETest.java | 88 ++++----- .../onap/dcae/controller/ConfigParsingTest.java | 23 ++- .../dcae/controller/EnvPropertiesReaderTest.java | 5 +- .../org/onap/dcae/controller/EnvPropsTest.java | 15 +- .../onap/dcae/restapi/ApiAuthInterceptionTest.java | 20 ++- 37 files changed, 1371 insertions(+), 950 deletions(-) delete mode 100644 src/test/java/org/onap/dcae/CLIUtilsTest.java create mode 100644 src/test/java/org/onap/dcae/CliUtilsTest.java delete mode 100644 src/test/java/org/onap/dcae/TLSTest.java delete mode 100644 src/test/java/org/onap/dcae/TLSTestBase.java create mode 100644 src/test/java/org/onap/dcae/TlsTest.java create mode 100644 src/test/java/org/onap/dcae/TlsTestBase.java delete mode 100644 src/test/java/org/onap/dcae/controller/ConfigCBSSourceTest.java create mode 100644 src/test/java/org/onap/dcae/controller/ConfigCbsSourceTest.java diff --git a/src/main/java/org/onap/dcae/common/DataChangeEventListener.java b/src/main/java/org/onap/dcae/common/DataChangeEventListener.java index 6cf2291..b37730e 100755 --- a/src/main/java/org/onap/dcae/common/DataChangeEventListener.java +++ b/src/main/java/org/onap/dcae/common/DataChangeEventListener.java @@ -60,7 +60,7 @@ public class DataChangeEventListener implements EventListener { log.info("Received heart beat "); } } catch (Exception e) { - log.info("InboundEvent event is malformed"); + log.info("InboundEvent event is malformed " + e); } } @@ -75,6 +75,7 @@ public class DataChangeEventListener implements EventListener { } catch (JSONException ex) { try { new JSONArray(test); + return jsonType.ARRAY; } catch (JSONException ex1) { return jsonType.NONE; diff --git a/src/main/java/org/onap/dcae/common/EventConnectionState.java b/src/main/java/org/onap/dcae/common/EventConnectionState.java index 3e53247..83d3c85 100644 --- a/src/main/java/org/onap/dcae/common/EventConnectionState.java +++ b/src/main/java/org/onap/dcae/common/EventConnectionState.java @@ -22,7 +22,7 @@ package org.onap.dcae.common; public enum EventConnectionState { - INIT, SUBSCRIBED, UNSUBSCRIBED, Unspecified; + INIT, SUBSCRIBED, UNSUBSCRIBED, UNSPECIFIED; public static EventConnectionState fromString(String s) { if ("init".equalsIgnoreCase(s)) { @@ -35,7 +35,7 @@ public enum EventConnectionState { return UNSUBSCRIBED; } if ("unspecified".equalsIgnoreCase(s)) { - return Unspecified; + return UNSPECIFIED; } throw new IllegalArgumentException("Invalid value for format: " + s); } diff --git a/src/main/java/org/onap/dcae/common/EventProcessor.java b/src/main/java/org/onap/dcae/common/EventProcessor.java index 1879700..f870d3f 100644 --- a/src/main/java/org/onap/dcae/common/EventProcessor.java +++ b/src/main/java/org/onap/dcae/common/EventProcessor.java @@ -56,8 +56,8 @@ public class EventProcessor implements Runnable { while (true) { ev = RestConfCollector.fProcessingInputQueue.take(); - // As long as the producer is running we remove elements from - // the queue. + /* As long as the producer is running we remove elements from + * the queue */ log.info("QueueSize:" + RestConfCollector.fProcessingInputQueue.size() + "\tEventProcessor\tRemoving element: " + ev.getEventObj()); /*@TODO: Right now all event publish to single domain and consume by VES collector. Later maybe send to specific domain */ @@ -72,7 +72,7 @@ public class EventProcessor implements Runnable { } } catch (Exception e) { - log.error("EventProcessor InterruptedException" + e.getMessage()); + log.error("EventProcessor InterruptedException " + e); Thread.currentThread().interrupt(); } } @@ -87,7 +87,7 @@ public class EventProcessor implements Runnable { log.info("Invoking method " + ev.getConn().getModifyMethod() + " isModify " + ev.getConn().isModifyEvent()); modifiedObj = (JSONObject)(this.getClass().getMethod(ev.getConn().getModifyMethod(), EventData.class, String.class).invoke(this, ev, ev.getConn().getUserData())); - }catch (Exception e) { + } catch (Exception e) { log.warn("No such method exist" + e); } } @@ -127,9 +127,7 @@ public class EventProcessor implements Runnable { JSONObject finalObj = new JSONObject(); Path configFile = Paths.get(conn.getParentCtrllr().getProperties().controllerConfigFileLocation()); try { - //log.info("Paths " + configFile.toString()); String bytes = new String(Files.readAllBytes(configFile)); - //log.info("Bytes " + bytes); newJSON = new JSONObject(bytes); newJSON.put("serialNumber", json1.getJSONObject("notification").getJSONObject("message").getJSONObject("content").getJSONObject("onu").get("sn")); newJSON.put("softwareVersion", json1.getJSONObject("notification").getJSONObject("message").get("version")); @@ -181,11 +179,9 @@ public class EventProcessor implements Runnable { newJSON.put("vendorName", usrDataMap.get("vendorName")); } } - //additionalfields.put("remote-id", attachment-point); } catch (Exception e) { log.info("File reading error " + e); } - //log.info("Modified json " + newJSON); finalObj.put("pnfRegistration", newJSON); log.info("final obj"+ finalObj.toString()); return finalObj; diff --git a/src/main/java/org/onap/dcae/common/publishing/VavrUtils.java b/src/main/java/org/onap/dcae/common/publishing/VavrUtils.java index 1db4e18..209aa82 100644 --- a/src/main/java/org/onap/dcae/common/publishing/VavrUtils.java +++ b/src/main/java/org/onap/dcae/common/publishing/VavrUtils.java @@ -32,11 +32,14 @@ import static io.vavr.API.$; public final class VavrUtils { private VavrUtils() { - // utils aggregator + /* utils aggregator */ } /** * Shortcut for 'string interpolation' + * @param msg String message + * @param args var args + * @return String */ public static String f(String msg, Object... args) { return String.format(msg, args); @@ -45,6 +48,8 @@ public final class VavrUtils { /** * Wrap failure with a more descriptive message of what has failed and chain original cause. Used to provide a * context for errors instead of raw exception. + * @param msg String message + * @return Case */ public static Case enhanceError(String msg) { return API.Case($(), e -> new RuntimeException(msg, e)); diff --git a/src/main/java/org/onap/dcae/controller/PersistentEventConnection.java b/src/main/java/org/onap/dcae/controller/PersistentEventConnection.java index ecbec31..7434fc2 100644 --- a/src/main/java/org/onap/dcae/controller/PersistentEventConnection.java +++ b/src/main/java/org/onap/dcae/controller/PersistentEventConnection.java @@ -180,7 +180,7 @@ public class PersistentEventConnection implements Runnable { @Override public void run() { - int sleep_time = 5000; + long sleep_time = 5000; boolean openState = false; EventSource eventSrc = null; while (running) { @@ -203,7 +203,9 @@ public class PersistentEventConnection implements Runnable { } catch (InterruptedException ie) { log.info("Exception: " + ie.getMessage()); running = false; - eventSrc.close(); + if (eventSrc != null) { + eventSrc.close(); + } Thread.currentThread().interrupt(); return; } catch (Exception e){ @@ -217,7 +219,7 @@ public class PersistentEventConnection implements Runnable { } } try { - if (eventSrc.isOpen()) { + if ((eventSrc != null) && (eventSrc.isOpen())) { eventSrc.close(); } }catch (Exception e) { @@ -243,7 +245,7 @@ public class PersistentEventConnection implements Runnable { log.error("Failed to receive sbscription notiication, trying again", e); try { parentCtrllr.getRestApiCallNode().sendRequest(eventParaMap, ctx, null); - }catch (Exception ex){ + } catch (Exception ex){ log.error("Exception occured again! Trying again", e); Thread.currentThread().interrupt(); } diff --git a/src/test/java/org/onap/dcae/AccessControllerTest.java b/src/test/java/org/onap/dcae/AccessControllerTest.java index 1e01340..4d66811 100644 --- a/src/test/java/org/onap/dcae/AccessControllerTest.java +++ b/src/test/java/org/onap/dcae/AccessControllerTest.java @@ -20,6 +20,16 @@ package org.onap.dcae; +import static java.nio.file.Files.readAllBytes; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.concurrent.ExecutorService; +import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; @@ -28,17 +38,8 @@ 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.nio.file.Path; -import java.nio.file.Paths; -import java.util.concurrent.ExecutorService; - -import org.json.JSONObject; import org.onap.dcae.controller.PersistentEventConnection; -import static java.nio.file.Files.readAllBytes; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.Silent.class) public class AccessControllerTest { @@ -49,8 +50,6 @@ public class AccessControllerTest { @Mock private RestConfContext ctx; - - protected static final Path RESOURCES = Paths.get("src", "test", "resources"); protected static final Path KEYSTORE = Paths.get(RESOURCES.toString(), "keystore"); protected static final Path KEYSTORE_PASSWORD_FILE = Paths.get(RESOURCES.toString(), "passwordfile"); @@ -58,7 +57,7 @@ public class AccessControllerTest { protected static final Path TRUSTSTORE_PASSWORD_FILE = Paths.get(RESOURCES.toString(), "trustpasswordfile"); protected static final Path RCC_KEYSTORE_PASSWORD_FILE = Paths.get(RESOURCES.toString(), "rcc_passwordfile"); protected static final Path RCC_KEYSTORE = Paths.get(RESOURCES.toString(), "sdnc.p12"); - + protected static final Path DMAAP_FILE = Paths.get(RESOURCES.toString(), "testDmaapConfig_ip.json"); @Test public void createAndGetAccessControler() { when(properties.truststoreFileLocation()).thenReturn(TRUSTSTORE.toString()); @@ -67,10 +66,20 @@ public class AccessControllerTest { when(properties.keystorePasswordFileLocation()).thenReturn(KEYSTORE_PASSWORD_FILE.toString()); when(properties.rccKeystoreFileLocation()).thenReturn(RCC_KEYSTORE.toString()); when(properties.rccKeystorePasswordFileLocation()).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\",\"controller_disableSsl\":\"true\",\"event_details\":[{\"event_name\":\"ONT_registration\",\"event_description\":\"ONTregistartionevent\",\"event_sseventUrlEmbed\":\"true\",\"event_sseventsField\":\"output.url\",\"event_sseventsUrl\":\"null\",\"event_subscriptionTemplate\":\"./etc/ont_registartion_subscription_template.json\",\"event_unSubscriptionTemplate\":\"./etc/ont_registartion_unsubscription_template.json\",\"event_ruleId\":\"777777777\"}]}"); + when(properties.dMaaPConfigurationFileLocation()).thenReturn(DMAAP_FILE.toString()); + + JSONObject controller = new JSONObject("{\"controller_name\":\"AccessM&C\",\"controller_restapiUrl\":" + + "\"10.118.191.43:26335\",\"controller_restapiUser\":\"access\",\"controller_restapiPassword\":" + + "\"Huawei@123\",\"controller_accessTokenUrl\":\"/rest/plat/smapp/v1/oauth/token\"," + + "\"controller_accessTokenFile\":\"./etc/access-token.json\",\"controller_accessTokenMethod\"" + + ":\"put\",\"controller_subsMethod\":\"post\",\"controller_subscriptionUrl\":" + + "\"/restconf/v1/operations/huawei-nce-notification-action:establish-subscription\"," + + "\"controller_disableSsl\":\"true\",\"event_details\":[{\"event_name\":\"ONT_registration\"," + + "\"event_description\":\"ONTregistartionevent\",\"event_sseventUrlEmbed\":\"true\"," + + "\"event_sseventsField\":\"output.url\",\"event_sseventsUrl\":\"null\"," + + "\"event_subscriptionTemplate\":\"./etc/ont_registartion_subscription_template.json\"," + + "\"event_unSubscriptionTemplate\":\"./etc/ont_registartion_unsubscription_template.json\"," + + "\"event_ruleId\":\"777777777\"}]}"); try { AccessController acClr = new AccessController(controller, properties); @@ -79,8 +88,11 @@ public class AccessControllerTest { 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){} + assertEquals(acClr.getCfgInfo().getController_subscriptionUrl(), + "/restconf/v1/operations/huawei-nce-notification-action:establish-subscription"); + } catch (Exception e) { + System.out.println("Exception " + e); + } } @Test @@ -91,11 +103,95 @@ public class AccessControllerTest { when(properties.keystorePasswordFileLocation()).thenReturn(KEYSTORE_PASSWORD_FILE.toString()); when(properties.rccKeystoreFileLocation()).thenReturn(RCC_KEYSTORE.toString()); when(properties.rccKeystorePasswordFileLocation()).thenReturn(RCC_KEYSTORE_PASSWORD_FILE.toString()); - when(properties.rccPolicy()).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\",\"controller_disableSsl\":\"true\",\"event_details\":[{\"event_name\":\"ONT_registration\",\"event_description\":\"ONTregistartionevent\",\"event_sseventUrlEmbed\":\"true\",\"event_sseventsField\":\"output.url\",\"event_sseventsUrl\":\"null\",\"event_subscriptionTemplate\":\"./etc/ont_registartion_subscription_template.json\",\"event_unSubscriptionTemplate\":\"./etc/ont_registartion_unsubscription_template.json\",\"event_ruleId\":\"777777777\"}]}]"); - when(ctx.getAttribute("responsePrefix.httpResponse")).thenReturn("{\"accessSession\" : \"1234567890\",\"result\" : \"Ok\"}"); + when(properties.dMaaPConfigurationFileLocation()).thenReturn(DMAAP_FILE.toString()); + when(properties.rccPolicy()).thenReturn("[{\"controller_name\":\"AccessM&C\"," + + "\"controller_restapiUrl\":\"172.30.0.55:26335\"," + + "\"controller_restapiUser\":\"access\",\"controller_restapiPassword\":" + + "\"Huawei@123\",\"controller_accessTokenUrl\":\"/rest/plat/smapp/v1/oauth/token\"," + + "\"controller_accessTokenFile\":\"./etc/access-token.json\"," + + "\"controller_accessTokenMethod\":\"put\",\"controller_subsMethod\":\"post\"," + + "\"controller_subscriptionUrl\":\"/restconf/v1/operations/huawei-nce-notification-action:" + + "establish-subscription\",\"controller_disableSsl\":\"true\",\"event_details\":[{\"event_name" + + "\":\"ONT_registration\",\"event_description\":\"ONTregistartionevent\"," + + "\"event_sseventUrlEmbed\":\"true\",\"event_sseventsField\":\"output.url\"," + + "\"event_sseventsUrl\":\"null\",\"event_subscriptionTemplate\":" + + "\"./etc/ont_registartion_subscription_template.json\",\"event_unSubscriptionTemplate\":" + + "\"./etc/ont_registartion_unsubscription_template.json\",\"event_ruleId\":\"777777777\", " + + "\"modifyData\": \"true\", \"modifyMethod\": \"modifyOntEvent\", \"userData\": " + + "\"remote_id=AC9.0234.0337;svlan=100;cvlan=10;\"}]}]"); + when(ctx.getAttribute("responsePrefix.httpResponse")).thenReturn("{\"accessSession\" : \"1234567890\"," + + "\"result\" : \"Ok\"}"); + + try { + + RestapiCallNode restApiCallNode = Mockito.mock(RestapiCallNode.class); + Mockito.doNothing().when(restApiCallNode).sendRequest(any(), any(), any()); + ExecutorService executor = Mockito.mock(ExecutorService.class); + Mockito.doNothing().when(executor).execute(any()); + PersistentEventConnection conn = mock(PersistentEventConnection.class); + Mockito.doNothing().when(conn).run(); + when(properties.authorizationEnabled()).thenReturn(true); + JSONObject controller = new JSONObject("{\"controller_name\":\"AccessM&C\"," + + "\"controller_restapiUrl\":\"10.118.191.43:26335\",\"controller_restapiUser\":\"access\"," + + "\"controller_restapiPassword\":\"Huawei@123\",\"controller_accessTokenUrl\":" + + "\"/rest/plat/smapp/v1/oauth/token\",\"controller_accessTokenFile\":" + + "\"./etc/access-token.json\",\"controller_accessTokenMethod\":\"put\"," + + "\"controller_subsMethod\":\"post\",\"controller_subscriptionUrl\":\"" + + "/restconf/v1/operations/huawei-nce-notification-action:establish-subscription\"," + + "\"controller_disableSsl\":\"true\",\"event_details\":[{\"event_name\":\"ONT_registration\"," + + "\"event_description\":\"ONTregistartionevent\",\"event_sseventUrlEmbed\":\"true\"," + + "\"event_sseventsField\":\"output.url\",\"event_sseventsUrl\":\"null\"," + + "\"event_subscriptionTemplate\":\"./etc/ont_registartion_subscription_template.json\"," + + "\"event_unSubscriptionTemplate\":\"./etc/ont_registartion_unsubscription_template.json\"," + + "\"event_ruleId\":\"777777777\", \"modifyData\": \"true\"}]}"); + AccessController acClr = new AccessController(controller, + properties); + AccessController acClr2 = new AccessController(controller, + properties); + acClr.equals(acClr2); + acClr.setRestApiCallNode(restApiCallNode); + //acClr.setExecutor(executor); + acClr.getCtx().setAttribute("responsePrefix.httpResponse", + "{\"accessSession\" : \"12dsaf4-2323-1231131232323\"}"); + acClr.activate(); + acClr.clearAllPersistentConnectios(); + } catch (Exception e) { + System.out.println("Exception " + e); + } + } + + @Test + public void accessControllerSuccessfullyActivated2() { + when(properties.truststoreFileLocation()).thenReturn(TRUSTSTORE.toString()); + when(properties.truststorePasswordFileLocation()).thenReturn(TRUSTSTORE_PASSWORD_FILE.toString()); + when(properties.keystoreFileLocation()).thenReturn(KEYSTORE.toString()); + when(properties.keystorePasswordFileLocation()).thenReturn(KEYSTORE_PASSWORD_FILE.toString()); + when(properties.rccKeystoreFileLocation()).thenReturn(RCC_KEYSTORE.toString()); + when(properties.rccKeystorePasswordFileLocation()).thenReturn(RCC_KEYSTORE_PASSWORD_FILE.toString()); + when(properties.dMaaPConfigurationFileLocation()).thenReturn(DMAAP_FILE.toString()); + when(properties.rccPolicy()).thenReturn("[{\"controller_name\":\"AccessM&C\"," + + "\"controller_restapiUrl\":\"172.30.0.55:26335\"," + + "\"controller_restapiUser\":\"access\",\"controller_restapiPassword\":" + + "\"Huawei@123\",\"controller_accessTokenUrl\":\"/rest/plat/smapp/v1/oauth/token\"," + + "\"controller_accessTokenFile\":\"./etc/access-token.json\"," + + "\"controller_accessTokenMethod\":\"put\",\"controller_subsMethod\":\"post\"," + + "\"controller_subscriptionUrl\":\"/restconf/v1/operations/huawei-nce-notification-action:" + + "establish-subscription\",\"controller_disableSsl\":\"true\",\"event_details\":[{\"event_name" + + "\":\"ONT_registration\",\"event_description\":\"ONTregistartionevent\"," + + "\"event_sseventUrlEmbed\":\"true\",\"event_sseventsField\":\"output.url\"," + + "\"event_sseventsUrl\":\"null\",\"event_subscriptionTemplate\":" + + "\"./etc/ont_registartion_subscription_template.json\",\"event_unSubscriptionTemplate\":" + + "\"./etc/ont_registartion_unsubscription_template.json\",\"event_ruleId\":\"777777777\", " + + "\"modifyData\": \"true\", \"modifyMethod\": \"modifyOntEvent\", \"userData\": " + + "\"remote_id=AC9.0234.0337;svlan=100;cvlan=10;\"}]}]"); + when(ctx.getAttribute("responsePrefix.httpResponse")).thenReturn("{\"accessSession\" : \"1234567890\"," + + "\"result\" : \"Ok\"}"); try { + RestConfCollector.main(new String[]{"-c", + Paths.get("src/test/resources/testcollector.properties").toString()}); + RestapiCallNode restApiCallNode = Mockito.mock(RestapiCallNode.class); Mockito.doNothing().when(restApiCallNode).sendRequest(any(), any(), any()); ExecutorService executor = Mockito.mock(ExecutorService.class); @@ -103,16 +199,32 @@ public class AccessControllerTest { PersistentEventConnection conn = mock(PersistentEventConnection.class); Mockito.doNothing().when(conn).run(); when(properties.authorizationEnabled()).thenReturn(true); - JSONObject controller = new JSONObject("{\"controller_name\":\"AccessM&C\",\"controller_restapiUrl\":\"10.118.191.43:26335\",\"controller_restapiUser\":\"access\",\"controller_restapiPassword\":\"Huawei@123\",\"controller_accessTokenUrl\":\"/rest/plat/smapp/v1/oauth/token\",\"controller_accessTokenFile\":\"./etc/access-token.json\",\"controller_accessTokenMethod\":\"put\",\"controller_subsMethod\":\"post\",\"controller_subscriptionUrl\":\"/restconf/v1/operations/huawei-nce-notification-action:establish-subscription\",\"controller_disableSsl\":\"true\",\"event_details\":[{\"event_name\":\"ONT_registration\",\"event_description\":\"ONTregistartionevent\",\"event_sseventUrlEmbed\":\"true\",\"event_sseventsField\":\"output.url\",\"event_sseventsUrl\":\"null\",\"event_subscriptionTemplate\":\"./etc/ont_registartion_subscription_template.json\",\"event_unSubscriptionTemplate\":\"./etc/ont_registartion_unsubscription_template.json\",\"event_ruleId\":\"777777777\"}]}"); + JSONObject controller = new JSONObject("{\"controller_name\":\"AccessM&C\"," + + "\"controller_restapiUrl\":\"10.118.191.43:26335\",\"controller_restapiUser\":\"access\"," + + "\"controller_restapiPassword\":\"Huawei@123\",\"controller_accessTokenUrl\":" + + "\"/rest/plat/smapp/v1/oauth/token\",\"controller_accessTokenFile\":" + + "\"./etc/access-token.json\",\"controller_accessTokenMethod\":\"put\"," + + "\"controller_subsMethod\":\"post\",\"controller_subscriptionUrl\":\"" + + "/restconf/v1/operations/huawei-nce-notification-action:establish-subscription\"," + + "\"controller_disableSsl\":\"true\",\"event_details\":[{\"event_name\":\"ONT_registration\"," + + "\"event_description\":\"ONTregistartionevent\",\"event_sseventUrlEmbed\":\"true\"," + + "\"event_sseventsField\":\"output.url\",\"event_sseventsUrl\":\"null\"," + + "\"event_subscriptionTemplate\":\"./etc/ont_registartion_subscription_template.json\"," + + "\"event_unSubscriptionTemplate\":\"./etc/ont_registartion_unsubscription_template.json\"," + + "\"event_ruleId\":\"777777777\", \"modifyData\": \"true\"}]}"); AccessController acClr = new AccessController(controller, properties); AccessController acClr2 = new AccessController(controller, properties); acClr.equals(acClr2); acClr.setRestApiCallNode(restApiCallNode); - acClr.setExecutor(executor); - acClr.getCtx().setAttribute("responsePrefix.httpResponse","{\"accessSession\" : \"12dsaf4-2323-1231131232323\"}"); + //acClr.setExecutor(executor); + acClr.getCtx().setAttribute("responsePrefix.httpResponse", + "{\"accessSession\" : \"12dsaf4-2323-1231131232323\"}"); acClr.activate(); - } catch (Exception e){} + acClr.clearAllPersistentConnectios(); + } catch (Exception e) { + System.out.println("Exception " + e); + } } } \ 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 index 3a9549f..d16953a 100644 --- a/src/test/java/org/onap/dcae/ApplicationSettingsTest.java +++ b/src/test/java/org/onap/dcae/ApplicationSettingsTest.java @@ -44,7 +44,7 @@ import org.junit.Test; public class ApplicationSettingsTest { @Test - public void shouldMakeApplicationSettingsOutOfCLIArguments() { + public void shouldMakeApplicationSettingsOutOfCliArguments() { // given String[] cliArguments = {"-param1", "param1value", "-param2", "param2value"}; @@ -59,7 +59,7 @@ public class ApplicationSettingsTest { } @Test - public void shouldMakeApplicationSettingsOutOfCLIArgumentsAndAConfigurationFile() + public void shouldMakeApplicationSettingsOutOfCliArgumentsAndAConfigurationFile() throws IOException { // given File tempConfFile = File.createTempFile("doesNotMatter", "doesNotMatter"); @@ -71,18 +71,21 @@ public class ApplicationSettingsTest { 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); + + String fromFileParam1Value = configurationAccessor.getStringDirectly("section.subSection1"); + String fromFileParam2Value = configurationAccessor.getStringDirectly("section.subSection2"); + + // then assertEquals("abc", fromFileParam1Value); assertEquals("zxc", fromFileParam2Value); } @Test - public void shouldCLIArgumentsOverrideConfigFileParameters() throws IOException { + public void shouldCliArgumentsOverrideConfigFileParameters() throws IOException { // given String[] cliArguments = {"-section.subSection1", "abc"}; File tempConfFile = File.createTempFile("doesNotMatter", "doesNotMatter"); @@ -91,20 +94,19 @@ public class ApplicationSettingsTest { // when ApplicationSettings configurationAccessor = new ApplicationSettings(cliArguments, CLIUtils::processCmdLine); - String actuallyOverridenByCLIParam = configurationAccessor.getStringDirectly("section.subSection1"); + String actuallyOverridenByCliParam = configurationAccessor.getStringDirectly("section.subSection1"); // then - assertEquals("abc", actuallyOverridenByCLIParam); + assertEquals("abc", actuallyOverridenByCliParam); configurationAccessor.reloadProperties(); - Path p = configurationAccessor.configurationFileLocation(); boolean auth = configurationAccessor.clientTlsAuthenticationEnabled(); assertEquals(auth, false); } @Test - public void shouldReturnHTTPPort() throws IOException { + public void shouldReturnHttpPort() throws IOException { // when int applicationPort = fromTemporaryConfiguration("collector.rcc.service.port=8090") .httpPort(); @@ -114,7 +116,7 @@ public class ApplicationSettingsTest { } @Test - public void shouldReturnDefaultHTTPPort() throws IOException { + public void shouldReturnDefaultHttpPort() throws IOException { // when int applicationPort = fromTemporaryConfiguration().httpPort(); @@ -123,7 +125,7 @@ public class ApplicationSettingsTest { } @Test - public void shouldReturnIfHTTPSIsEnabled() throws IOException { + public void shouldReturnIfHttpSIsEnabled() throws IOException { // when boolean httpsEnabled = fromTemporaryConfiguration("collector.rcc.service.secure.port=8687") .httpsEnabled(); @@ -133,7 +135,7 @@ public class ApplicationSettingsTest { } @Test - public void shouldReturnIfHTTPIsEnabled() throws IOException { + public void shouldReturnIfHttpIsEnabled() throws IOException { // when boolean httpsEnabled = fromTemporaryConfiguration("collector.service.port=8080").httpsEnabled(); // then @@ -141,7 +143,7 @@ public class ApplicationSettingsTest { } @Test - public void shouldByDefaultHTTPSBeDisabled() throws IOException { + public void shouldByDefaultHttpSBeDisabled() throws IOException { // when boolean httpsEnabled = fromTemporaryConfiguration().httpsEnabled(); @@ -150,7 +152,7 @@ public class ApplicationSettingsTest { } @Test - public void shouldReturnHTTPSPort() throws IOException { + public void shouldReturnHttpSPort() throws IOException { // when int httpsPort = fromTemporaryConfiguration("collector.service.secure.port=8687") .httpsPort(); @@ -163,7 +165,8 @@ public class ApplicationSettingsTest { @Test public void shouldReturnLocationOfThePasswordFile() throws IOException { // when - String passwordFileLocation = fromTemporaryConfiguration("collector.rcc.keystore.passwordfile=/somewhere/password") + String passwordFileLocation = fromTemporaryConfiguration( + "collector.rcc.keystore.passwordfile=/somewhere/password") .keystorePasswordFileLocation(); // then @@ -182,7 +185,8 @@ public class ApplicationSettingsTest { @Test public void shouldReturnLocationOfTheKeystoreFile() throws IOException { // when - String keystoreFileLocation = fromTemporaryConfiguration("collector.rcc.keystore.file.location=/somewhere/keystore") + String keystoreFileLocation = fromTemporaryConfiguration( + "collector.rcc.keystore.file.location=/somewhere/keystore") .keystoreFileLocation(); // then @@ -199,9 +203,10 @@ public class ApplicationSettingsTest { } @Test - public void shouldReturnDMAAPConfigFileLocation() throws IOException { + public void shouldReturnDmaapConfigFileLocation() throws IOException { // when - String dmaapConfigFileLocation = fromTemporaryConfiguration("collector.dmaapfile=/somewhere/dmaapFile") + String dmaapConfigFileLocation = fromTemporaryConfiguration( + "collector.dmaapfile=/somewhere/dmaapFile") .dMaaPConfigurationFileLocation(); // then @@ -209,7 +214,7 @@ public class ApplicationSettingsTest { } @Test - public void shouldReturnDefaultDMAAPConfigFileLocation() throws IOException { + public void shouldReturnDefaultDmaapConfigFileLocation() throws IOException { // when String dmaapConfigFileLocation = fromTemporaryConfiguration().dMaaPConfigurationFileLocation(); @@ -220,7 +225,8 @@ public class ApplicationSettingsTest { @Test public void shouldReturnMaximumAllowedQueuedEvents() throws IOException { // when - int maximumAllowedQueuedEvents = fromTemporaryConfiguration("collector.rcc.inputQueue.maxPending=10000") + int maximumAllowedQueuedEvents = fromTemporaryConfiguration( + "collector.rcc.inputQueue.maxPending=10000") .maximumAllowedQueuedEvents(); // then @@ -236,37 +242,6 @@ public class ApplicationSettingsTest { 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 @@ -301,8 +276,8 @@ public class ApplicationSettingsTest { @Test public void shouldbyDefaultThereShouldBeNoValidCredentials() throws IOException { // when - Map userToBase64PasswordDelimitedByCommaSeparatedByPipes = fromTemporaryConfiguration(). - validAuthorizationCredentials(); + Map userToBase64PasswordDelimitedByCommaSeparatedByPipes = fromTemporaryConfiguration() + .validAuthorizationCredentials(); // then assertTrue(userToBase64PasswordDelimitedByCommaSeparatedByPipes.isEmpty()); @@ -333,7 +308,7 @@ public class ApplicationSettingsTest { @Test public void shouldrccKeystorePathExistDefault() throws IOException { // when - String path= fromTemporaryConfiguration().rccKeystoreFileLocation(); + String path = fromTemporaryConfiguration().rccKeystoreFileLocation(); // then assertEquals(sanitizePath("etc/keystore"), path); @@ -342,7 +317,7 @@ public class ApplicationSettingsTest { @Test public void shouldrccKeystorePasswordExistDefault() throws IOException { // when - String path= fromTemporaryConfiguration().rccKeystorePasswordFileLocation(); + String path = fromTemporaryConfiguration().rccKeystorePasswordFileLocation(); // then assertEquals(sanitizePath("etc/rcc_passwordfile"), path); @@ -351,7 +326,7 @@ public class ApplicationSettingsTest { @Test public void shouldTruststorePathExistDefault() throws IOException { // when - String path= fromTemporaryConfiguration().truststorePasswordFileLocation(); + String path = fromTemporaryConfiguration().truststorePasswordFileLocation(); // then assertEquals(sanitizePath("etc/trustpasswordfile"), path); @@ -360,7 +335,7 @@ public class ApplicationSettingsTest { @Test public void shouldTruststorePasswordExistDefault() throws IOException { // when - String path= fromTemporaryConfiguration().truststoreFileLocation(); + String path = fromTemporaryConfiguration().truststoreFileLocation(); // then assertEquals(sanitizePath("etc/truststore.onap.client.jks"), path); @@ -392,12 +367,16 @@ public class ApplicationSettingsTest { // then assertEquals(stream, null); } + 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), ""); + return new ApplicationSettings( + new String[]{"-c", tempConfFile.toString()}, + args -> processCmdLine(args), + ""); } private String sanitizePath(String path) { diff --git a/src/test/java/org/onap/dcae/CLIUtilsTest.java b/src/test/java/org/onap/dcae/CLIUtilsTest.java deleted file mode 100644 index caf88ac..0000000 --- a/src/test/java/org/onap/dcae/CLIUtilsTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/*- - * ============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/CliUtilsTest.java b/src/test/java/org/onap/dcae/CliUtilsTest.java new file mode 100644 index 0000000..66d3f9b --- /dev/null +++ b/src/test/java/org/onap/dcae/CliUtilsTest.java @@ -0,0 +1,59 @@ +/*- + * ============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 static org.assertj.core.api.Assertions.assertThat; + +import io.vavr.collection.Map; +import org.junit.Test; + + +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/RestApiCallNodeUtilTest.java b/src/test/java/org/onap/dcae/RestApiCallNodeUtilTest.java index 723ffea..477975c 100644 --- a/src/test/java/org/onap/dcae/RestApiCallNodeUtilTest.java +++ b/src/test/java/org/onap/dcae/RestApiCallNodeUtilTest.java @@ -20,17 +20,20 @@ package org.onap.dcae; -import org.junit.Test; -import org.onap.dcae.common.*; +import static org.junit.Assert.assertEquals; + +import java.util.HashMap; +import java.util.Map; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; -import java.util.*; -import java.util.Map; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import org.junit.Test; +import org.onap.dcae.common.AuthType; +import org.onap.dcae.common.Constants; +import org.onap.dcae.common.Parameters; +import org.onap.dcae.common.RestapiCallNodeUtil; + /** * Created by koblosz on 07.06.18. @@ -69,12 +72,14 @@ public class RestApiCallNodeUtilTest { String trustPassword = "admin"; paraMap.put(Constants.KSETTING_TRUST_STORE_PASSWORD, trustPassword); paraMap.put(Constants.KSETTING_KEY_STORE_FILENAME, null); - String KeyPassword = "admin"; - paraMap.put(Constants.KSETTING_KEY_STORE_PASSWD, KeyPassword); + String keyPassword = "admin"; + paraMap.put(Constants.KSETTING_KEY_STORE_PASSWD, keyPassword); try { - Parameters p = RestapiCallNodeUtil.getParameters(paraMap); - assertEquals(p.contentType, "application/json"); - } catch (Exception e) {} + Parameters parameters = RestapiCallNodeUtil.getParameters(paraMap); + assertEquals(parameters.contentType, "application/json"); + } catch (Exception e) { + System.out.println("Exception " + e); + } } @@ -82,7 +87,11 @@ public class RestApiCallNodeUtilTest { public void parseComplexParam() { Map paraMap = new HashMap<>(); paraMap.put(Constants.KDEFAULT_TEMP_FILENAME, null); - paraMap.put(Constants.KSETTING_REST_API_URL, "https://sonar.onap.org/component_measures?id=org.onap.dcaegen2.collectors.restconf%3Arestconfcollector&metric=coverage&selected=org.onap.dcaegen2.collectors.restconf%3Arestconfcollector%3Asrc%2Fmain%2Fjava%2Forg%2Fonap%2Fdcae%2Fcommon%2FRestapiCallNodeUtil.java"); + paraMap.put(Constants.KSETTING_REST_API_URL, + "https://sonar.onap.org/component_measures?id=org.onap.dcaegen2.collectors." + + "restconf%3Arestconfcollector&metric=coverage&selected=org.onap.dcaegen2.collectors" + + ".restconf%3Arestconfcollector%3Asrc%2Fmain%2Fjava%2Forg%2Fonap%2Fdcae%2Fcommon%2F" + + "RestapiCallNodeUtil.java"); paraMap.put(Constants.KSETTING_HTTP_METHOD, "post"); paraMap.put(Constants.KSETTING_RESP_PREFIX, "responsePrefix"); paraMap.put(Constants.KSETTING_SKIP_SENDING, "false"); @@ -109,21 +118,25 @@ public class RestApiCallNodeUtilTest { String trustPassword = "admin"; paraMap.put(Constants.KSETTING_TRUST_STORE_PASSWORD, trustPassword); paraMap.put(Constants.KSETTING_KEY_STORE_FILENAME, null); - String KeyPassword = "admin"; - paraMap.put(Constants.KSETTING_KEY_STORE_PASSWD, KeyPassword); + String keyPassword = "admin"; + paraMap.put(Constants.KSETTING_KEY_STORE_PASSWD, keyPassword); try { - Parameters p = RestapiCallNodeUtil.getParameters(paraMap); - assertEquals(p.contentType, "application/json"); - } catch (Exception e) {} + Parameters parameters = RestapiCallNodeUtil.getParameters(paraMap); + assertEquals(parameters.contentType, "application/json"); + } catch (Exception e) { + System.out.println("Exception " + e); + } } @Test public void parseinValidUrl() { Map paraMap = new HashMap<>(); - paraMap.put(Constants.KSETTING_REST_API_URL, ""); + paraMap.put(Constants.KSETTING_REST_API_URL, "$$$"); try { - Parameters p = RestapiCallNodeUtil.getParameters(paraMap); - } catch (Exception e) {} + Parameters parameters = RestapiCallNodeUtil.getParameters(paraMap); + } catch (Exception e) { + System.out.println("Exception " + e); + } } @Test @@ -158,47 +171,53 @@ public class RestApiCallNodeUtilTest { String trustPassword = "admin"; paraMap.put(Constants.KSETTING_TRUST_STORE_PASSWORD, trustPassword); paraMap.put(Constants.KSETTING_KEY_STORE_FILENAME, null); - String KeyPassword = "admin"; - paraMap.put(Constants.KSETTING_KEY_STORE_PASSWD, KeyPassword); + String keyPassword = "admin"; + paraMap.put(Constants.KSETTING_KEY_STORE_PASSWD, keyPassword); Client client = ClientBuilder.newBuilder().build(); try { - Parameters p = RestapiCallNodeUtil.getParameters(paraMap); - p.restapiUser = "restapiUser"; - p.restapiPassword = "restapiPassword"; - RestapiCallNodeUtil.addAuthType(client, p); - - p.restapiUser = null; - p.restapiPassword = null; - p.oAuthConsumerKey = "restapiUser"; - p.oAuthSignatureMethod = "restapiPassword"; - p.oAuthConsumerSecret = "someval"; - RestapiCallNodeUtil.addAuthType(client, p); - - p.authtype = AuthType.DIGEST; - p.restapiUser = "restapiUser"; - p.restapiPassword = "restapiPassword"; - RestapiCallNodeUtil.addAuthType(client, p); - } catch (Exception e) {} + Parameters parameters = RestapiCallNodeUtil.getParameters(paraMap); + parameters.restapiUser = "restapiUser"; + parameters.restapiPassword = "restapiPassword"; + RestapiCallNodeUtil.addAuthType(client, parameters); + + parameters.restapiUser = null; + parameters.restapiPassword = null; + parameters.oAuthConsumerKey = "restapiUser"; + parameters.oAuthSignatureMethod = "restapiPassword"; + parameters.oAuthConsumerSecret = "someval"; + RestapiCallNodeUtil.addAuthType(client, parameters); + + parameters.authtype = AuthType.DIGEST; + parameters.restapiUser = "restapiUser"; + parameters.restapiPassword = "restapiPassword"; + RestapiCallNodeUtil.addAuthType(client, parameters); + } catch (Exception e) { + System.out.println("Exception " + e); + } try { - Parameters p = RestapiCallNodeUtil.getParameters(paraMap); - p.authtype = AuthType.BASIC; - p.restapiUser = "restapiUser"; - p.restapiPassword = "restapiPassword"; - RestapiCallNodeUtil.addAuthType(client, p); + Parameters parameters = RestapiCallNodeUtil.getParameters(paraMap); + parameters.authtype = AuthType.BASIC; + parameters.restapiUser = "restapiUser"; + parameters.restapiPassword = "restapiPassword"; + RestapiCallNodeUtil.addAuthType(client, parameters); - } catch (Exception e) {} + } catch (Exception e) { + System.out.println("Exception " + e); + } try { - Parameters p = RestapiCallNodeUtil.getParameters(paraMap); - p.authtype = AuthType.OAUTH; - p.oAuthConsumerKey = "restapiUser"; - p.oAuthSignatureMethod = "restapiPassword"; - p.oAuthConsumerSecret = "someval"; - RestapiCallNodeUtil.addAuthType(client, p); - - } catch (Exception e) {} + Parameters parameters = RestapiCallNodeUtil.getParameters(paraMap); + parameters.authtype = AuthType.OAUTH; + parameters.oAuthConsumerKey = "restapiUser"; + parameters.oAuthSignatureMethod = "restapiPassword"; + parameters.oAuthConsumerSecret = "someval"; + RestapiCallNodeUtil.addAuthType(client, parameters); + + } catch (Exception e) { + System.out.println("Exception " + e); + } } } \ 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 deleted file mode 100644 index 37505d3..0000000 --- a/src/test/java/org/onap/dcae/TLSTest.java +++ /dev/null @@ -1,135 +0,0 @@ -/*- - * ============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.PASSWORD; -import static org.onap.dcae.TLSTest.HttpsConfiguration.USERNAME; - -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); - } - } - - @Nested - @Import(HttpsConfiguration.class) - class HttpsTest extends TestClassBase { - - - @Test - public void shouldHttpsRequestWithoutBasicAuthFail() { - assertThrows(Exception.class, this::makeHttpsRequest); - } - - @Test - public void shouldHttpsRequestWithBasicAuthSucceed() { - assertEquals(HttpStatus.OK, makeHttpsRequestWithBasicAuth(USERNAME, PASSWORD).getStatusCode()); - } - } - - @Nested - @Import(HttpsConfigurationWithTLSAuthentication.class) - class HttpsWithTLSAuthenticationTest extends TestClassBase { - - @Test - public void shouldHttpsRequestWithoutCertificateFail() { - assertThrows(Exception.class, this::makeHttpsRequest); - } - } - - @Nested - @Import(HttpsConfigurationWithTLSAuthenticationAndBasicAuth.class) - class HttpsWithTLSAuthenticationAndBasicAuthTest extends TestClassBase { - - @Test - public void shouldHttpsRequestWithoutBasicAuthFail() { - assertThrows(Exception.class, this::makeHttpsRequestWithClientCert); - } - - @Test - public void shouldHttpsRequestWithBasicAuthSucceed() { - assertEquals(HttpStatus.OK, makeHttpsRequestWithClientCertAndBasicAuth(USERNAME, PASSWORD).getStatusCode()); - } - } - - 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.rccKeystoreFileLocation()).thenReturn(RCC_KEYSTORE.toString()); - when(settings.rccKeystorePasswordFileLocation()).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.authorizationEnabled()).thenReturn(true); - 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 deleted file mode 100644 index a35f009..0000000 --- a/src/test/java/org/onap/dcae/TLSTestBase.java +++ /dev/null @@ -1,154 +0,0 @@ -/*- - * ============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(), "passwordfile"); - protected static final Path RCC_KEYSTORE = Paths.get(RESOURCES.toString(), "keystore"); - - 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 index 5ae238a..14c34c9 100644 --- a/src/test/java/org/onap/dcae/TestingUtilities.java +++ b/src/test/java/org/onap/dcae/TestingUtilities.java @@ -19,25 +19,20 @@ * 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 javax.net.ssl.SSLContext; import org.apache.http.client.HttpClient; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.HttpClients; @@ -48,7 +43,7 @@ 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 { @@ -56,21 +51,41 @@ public final class TestingUtilities { // utility class, no objects allowed } - public static void assertJSONObjectsEqual(JSONObject o1, JSONObject o2) { + /** + * Assert if JSON Objects are Equal. + * @param o1 JSONObject one. + * @param o2 JSONObject two. + */ + public static void assertJsonObjectsEqual(JSONObject o1, JSONObject o2) { assertThat(o1.toString()).isEqualTo(o2.toString()); } - public static JSONObject readJSONFromFile(Path path) { + /** + * Read JSON From File. + * @param path path of file. + * @return JSON Object. + */ + public static JSONObject readJsonFromFile(Path path) { return rethrow(() -> new JSONObject(readFile(path))); } + /** + * Read File from givn path. + * @param path path of file. + * @return String content. + */ public static String readFile(Path path) { return rethrow(() -> new String(readAllBytes(path))); } - public static Path createTemporaryFile(String content) { + /** + * Create Temporary File. + * @param content content of file. + * @return Path. + */ + public static Path createTemporaryFile(String name, String content) { return rethrow(() -> { - File temp = File.createTempFile("restconf-collector-tests-created-this-file", ".tmp"); + File temp = File.createTempFile(name, ".tmp"); temp.deleteOnExit(); Path filePath = Paths.get(temp.toString()); Files.write(filePath, content.getBytes()); @@ -82,6 +97,7 @@ public final class TestingUtilities { * 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(); @@ -90,21 +106,36 @@ public final class TestingUtilities { } } + /** + * + * @param . + */ @FunctionalInterface interface CheckedSupplier { T get() throws Exception; } + /** Assert if Failure Has Info. + * + * @param any any object + * @param msgPart msg part + */ public static void assertFailureHasInfo(Try any, String... msgPart) { Java6Assertions.assertThat(any.isFailure()).isTrue(); - AbstractThrowableAssert o = Java6Assertions.assertThat(any.getCause()) + AbstractThrowableAssert instance = Java6Assertions.assertThat(any.getCause()) .hasCauseInstanceOf(Exception.class); for (String s : msgPart) { - o.hasStackTraceContaining(s); + instance.hasStackTraceContaining(s); } } + /** + * SSL Builder With TrustStore. + * @param trustStore path of file. + * @param pass password. + * @return SSLContextBuilder. + */ public static SSLContextBuilder sslBuilderWithTrustStore(final Path trustStore, final String pass) { return rethrow(() -> new SSLContextBuilder() @@ -112,6 +143,13 @@ public final class TestingUtilities { ); } + /** + * Configure Key Store for testing. + * @param builder class builder. + * @param keyStore path of file. + * @param pass password. + * @return SSLContextBuilder. + */ public static SSLContextBuilder configureKeyStore( final SSLContextBuilder builder, final Path keyStore, @@ -126,6 +164,11 @@ public final class TestingUtilities { }); } + /** + * Create Rest Template With Ssl. + * @param context ssl context + * @return RestTemplate + */ public static RestTemplate createRestTemplateWithSsl(final SSLContext context) { final SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(context); final HttpClient httpClient = HttpClients 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..a141985 --- /dev/null +++ b/src/test/java/org/onap/dcae/TlsTest.java @@ -0,0 +1,138 @@ +/*- + * ============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 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.PASSWORD; +import static org.onap.dcae.TlsTest.HttpsConfiguration.USERNAME; + +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; + +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); + } + } + + @Nested + @Import(HttpsConfiguration.class) + class HttpsTest extends TestClassBase { + + + @Test + public void shouldHttpsRequestWithoutBasicAuthFail() { + assertThrows(Exception.class, this::makeHttpsRequest); + } + + @Test + public void shouldHttpsRequestWithBasicAuthSucceed() { + assertEquals(HttpStatus.OK, makeHttpsRequestWithBasicAuth(USERNAME, PASSWORD).getStatusCode()); + } + } + + @Nested + @Import(HttpsConfigurationWithTlsAuthentication.class) + class HttpsWithTlsAuthenticationTest extends TestClassBase { + + @Test + public void shouldHttpsRequestWithoutCertificateFail() { + assertThrows(Exception.class, this::makeHttpsRequest); + } + } + + @Nested + @Import(HttpsConfigurationWithTlsAuthenticationAndBasicAuth.class) + class HttpsWithTlsAuthenticationAndBasicAuthTest extends TestClassBase { + + @Test + public void shouldHttpsRequestWithoutBasicAuthFail() { + assertThrows(Exception.class, this::makeHttpsRequestWithClientCert); + } + + @Test + public void shouldHttpsRequestWithBasicAuthSucceed() { + assertEquals(HttpStatus.OK, + makeHttpsRequestWithClientCertAndBasicAuth(USERNAME, PASSWORD).getStatusCode()); + } + } + + 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.rccKeystoreFileLocation()).thenReturn(RCC_KEYSTORE.toString()); + when(settings.rccKeystorePasswordFileLocation()).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.authorizationEnabled()).thenReturn(true); + 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..708b3bd --- /dev/null +++ b/src/test/java/org/onap/dcae/TlsTestBase.java @@ -0,0 +1,163 @@ +/*- + * ============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 org.onap.dcae.TestingUtilities.configureKeyStore; +import static org.onap.dcae.TestingUtilities.createRestTemplateWithSsl; +import static org.onap.dcae.TestingUtilities.readFile; +import static org.onap.dcae.TestingUtilities.rethrow; +import static org.onap.dcae.TestingUtilities.sslBuilderWithTrustStore; + +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.concurrent.LinkedBlockingQueue; + +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; + + + + + +@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(), "passwordfile"); + protected static final Path RCC_KEYSTORE = Paths.get(RESOURCES.toString(), "keystore"); + + protected abstract static 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/WiremockBasedTest.java b/src/test/java/org/onap/dcae/WiremockBasedTest.java index 2144e99..da1ee1d 100644 --- a/src/test/java/org/onap/dcae/WiremockBasedTest.java +++ b/src/test/java/org/onap/dcae/WiremockBasedTest.java @@ -39,14 +39,14 @@ public class WiremockBasedTest { public WireMockRule wireMockRule = new WireMockRule( wireMockConfig().dynamicPort().dynamicHttpsPort().keystorePath(null)); - protected void stubConsulToReturnLocalAddressOfCBS() { + protected void stubConsulToReturnLocalAddressOfCbs() { stubFor(get(urlEqualTo("/v1/catalog/service/CBSName")) - .willReturn(aResponse().withBody(validLocalCBSConf()))); + .willReturn(aResponse().withBody(validLocalCbsConf()))); } - protected void stubCBSToReturnAppConfig(String sampleConfigForVES) { + protected void stubCbsToReturnAppConfig(String sampleConfigForVes) { stubFor(get(urlEqualTo("/service_component/restconfcollector")) - .willReturn(aResponse().withBody(sampleConfigForVES))); + .willReturn(aResponse().withBody(sampleConfigForVes))); } protected Map wiremockBasedEnvProps() { @@ -58,7 +58,7 @@ public class WiremockBasedTest { ); } - protected String validLocalCBSConf() { + protected String validLocalCbsConf() { return "" + "[{ " + "\"ServiceAddress\": \"localhost\"," diff --git a/src/test/java/org/onap/dcae/common/AdditionalHeaderWebTargetTest.java b/src/test/java/org/onap/dcae/common/AdditionalHeaderWebTargetTest.java index 8f47899..3a927e1 100644 --- a/src/test/java/org/onap/dcae/common/AdditionalHeaderWebTargetTest.java +++ b/src/test/java/org/onap/dcae/common/AdditionalHeaderWebTargetTest.java @@ -20,31 +20,61 @@ package org.onap.dcae.common; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.HashMap; +import java.util.Map; +import javax.ws.rs.client.Invocation; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; -import javax.ws.rs.client.WebTarget; -import static org.mockito.Mockito.*; + @RunWith(MockitoJUnitRunner.Silent.class) public class AdditionalHeaderWebTargetTest { - @Test - public void AdditionalHaderWebTargettestBase() { + public void additionalHaderWebTargettestBase() { + final Invocation.Builder mockBuilder = Mockito.mock(Invocation.Builder.class); + WebTarget target = mock(WebTarget.class); - AdditionalHeaderWebTarget t = new AdditionalHeaderWebTarget(target, "aaa112", "someheader"); - t.getConfiguration(); - t.getUri(); - t.getUriBuilder(); - t.path(""); - t.register(AdditionalHeaderWebTarget.class); - t.register(AdditionalHeaderWebTarget.class,0); - t.register(AdditionalHeaderWebTarget.class, AdditionalHeaderWebTarget.class); + when(target.request()).thenReturn(mockBuilder); + when(target.request("application/json")).thenReturn(mockBuilder); + when(target.request(MediaType.APPLICATION_JSON)).thenReturn(mockBuilder); + JSONObject jsonObject = new JSONObject("{\"key\": 1}"); + Map someMap = new HashMap<>(); + someMap.put("id", jsonObject); + AdditionalHeaderWebTarget webTarget = new AdditionalHeaderWebTarget(target, "aaa112", + "someheader"); + webTarget.getConfiguration(); + webTarget.getUri(); + webTarget.getUriBuilder(); + webTarget.path(""); + webTarget.register(AdditionalHeaderWebTarget.class); + webTarget.register(AdditionalHeaderWebTarget.class,0); + webTarget.register(AdditionalHeaderWebTarget.class, AdditionalHeaderWebTarget.class); Object obj = new Object(); - t.register(obj); - t.register(obj, 0); - t.register(obj, AdditionalHeaderWebTarget.class); + webTarget.register(obj); + webTarget.register(obj, 0); + webTarget.register(obj, AdditionalHeaderWebTarget.class); + webTarget.request(); + webTarget.request("application/json"); + webTarget.request(MediaType.APPLICATION_JSON_TYPE); + webTarget.resolveTemplate("key", jsonObject); + webTarget.resolveTemplate("key", jsonObject, false); + webTarget.resolveTemplateFromEncoded("key", jsonObject); + webTarget.resolveTemplates(someMap); + webTarget.resolveTemplates(someMap, false); + webTarget.resolveTemplatesFromEncoded(someMap); + + webTarget.matrixParam("key", jsonObject); + webTarget.queryParam("key", jsonObject); + webTarget.property("key", jsonObject); } } \ No newline at end of file diff --git a/src/test/java/org/onap/dcae/common/AuthTypeTest.java b/src/test/java/org/onap/dcae/common/AuthTypeTest.java index a8a8729..604730f 100644 --- a/src/test/java/org/onap/dcae/common/AuthTypeTest.java +++ b/src/test/java/org/onap/dcae/common/AuthTypeTest.java @@ -17,12 +17,12 @@ * 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.assertEquals; -import static org.junit.Assert.*; +import org.junit.Test; public class AuthTypeTest { diff --git a/src/test/java/org/onap/dcae/common/DataChangeEventListnerTest.java b/src/test/java/org/onap/dcae/common/DataChangeEventListnerTest.java index 95c8012..3d48bf2 100644 --- a/src/test/java/org/onap/dcae/common/DataChangeEventListnerTest.java +++ b/src/test/java/org/onap/dcae/common/DataChangeEventListnerTest.java @@ -17,28 +17,21 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.dcae.common; +import static org.mockito.Mockito.when; -import org.glassfish.jersey.media.sse.EventInput; +import java.util.concurrent.LinkedBlockingQueue; 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 { @@ -59,9 +52,12 @@ public class DataChangeEventListnerTest { 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\" ]}]"); + 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); diff --git a/src/test/java/org/onap/dcae/common/EventConnectionStateTest.java b/src/test/java/org/onap/dcae/common/EventConnectionStateTest.java index c6327bc..8970e73 100644 --- a/src/test/java/org/onap/dcae/common/EventConnectionStateTest.java +++ b/src/test/java/org/onap/dcae/common/EventConnectionStateTest.java @@ -17,11 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.dcae.common; +import static org.junit.Assert.assertEquals; + import org.junit.Test; -import static org.junit.Assert.assertEquals; + public class EventConnectionStateTest { @@ -30,7 +33,7 @@ public class EventConnectionStateTest { assertEquals(EventConnectionState.INIT, EventConnectionState.fromString("init")); assertEquals(EventConnectionState.SUBSCRIBED, EventConnectionState.fromString("subscribed")); assertEquals(EventConnectionState.UNSUBSCRIBED, EventConnectionState.fromString("unsubscribed")); - assertEquals(EventConnectionState.Unspecified, EventConnectionState.fromString("unspecified")); + assertEquals(EventConnectionState.UNSPECIFIED, EventConnectionState.fromString("unspecified")); } @Test(expected = IllegalArgumentException.class) diff --git a/src/test/java/org/onap/dcae/common/EventProcessorTest.java b/src/test/java/org/onap/dcae/common/EventProcessorTest.java index 04a2952..e86af85 100644 --- a/src/test/java/org/onap/dcae/common/EventProcessorTest.java +++ b/src/test/java/org/onap/dcae/common/EventProcessorTest.java @@ -17,14 +17,18 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.dcae.common; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.concurrent.LinkedBlockingQueue; import org.json.JSONObject; import org.junit.Before; - - import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; @@ -38,25 +42,9 @@ import org.onap.dcae.controller.AccessController; import org.onap.dcae.controller.PersistentEventConnection; import org.slf4j.LoggerFactory; - -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.ArgumentMatchers.any; -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; @@ -72,10 +60,13 @@ public class EventProcessorTest { 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"); + /** + * set up before testcase. + */ @Before public void setUp() { - eventPublisher = EventPublisher.createPublisher(LoggerFactory.getLogger("some_log"), DMaaPConfigurationParser. - parseToDomainMapping(path).get()); + eventPublisher = EventPublisher.createPublisher(LoggerFactory.getLogger("some_log"), + DMaaPConfigurationParser.parseToDomainMapping(path).get()); streamMap = RestConfCollector.parseStreamIdToStreamHashMapping("notification=device-registration"); } @@ -83,59 +74,77 @@ public class EventProcessorTest { @Test public void testEventProcessorRunException() { try { - when(properties.truststoreFileLocation()).thenReturn(TRUSTSTORE.toString()); - - when(properties.truststorePasswordFileLocation()).thenReturn(TRUSTSTORE_PASSWORD_FILE.toString()); - when(properties.keystoreFileLocation()).thenReturn(KEYSTORE.toString()); - when(properties.keystorePasswordFileLocation()).thenReturn(KEYSTORE_PASSWORD_FILE.toString()); - when(properties.rccKeystoreFileLocation()).thenReturn(RCC_KEYSTORE.toString()); - when(properties.rccKeystorePasswordFileLocation()).thenReturn(RCC_KEYSTORE_PASSWORD_FILE.toString()); - when(properties.controllerConfigFileLocation()).thenReturn(Paths.get("etc/ont_config.json").toAbsolutePath().toString()); - - RestapiCallNode restApiCallNode = Mockito.mock(RestapiCallNode.class); - Mockito.doNothing().when(restApiCallNode).sendRequest(any(), any(), any()); - - - JSONObject controller = new JSONObject( - "{\"controller_name\":\"AccessM&C\",\"controller_restapiUrl\":\"10.118.191.43:26335\",\"controller_restapiUser\":\"access\",\"controller_restapiPassword\":\"Huawei@123\",\"controller_accessTokenUrl\":\"/rest/plat/smapp/v1/oauth/token\",\"controller_accessTokenFile\":\"./etc/access-token.json\",\"controller_accessTokenMethod\":\"put\",\"controller_subsMethod\":\"post\",\"controller_subscriptionUrl\":\"/restconf/v1/operations/huawei-nce-notification-action:establish-subscription\",\"controller_disableSsl\":\"true\",\"event_details\":[{\"event_name\":\"ONT_registration\",\"event_description\":\"ONTregistartionevent\",\"event_sseventUrlEmbed\":\"true\",\"event_sseventsField\":\"output.url\",\"event_sseventsUrl\":\"null\",\"event_subscriptionTemplate\":\"./etc/ont_registartion_subscription_template.json\",\"event_unSubscriptionTemplate\":\"./etc/ont_registartion_unsubscription_template.json\",\"event_ruleId\":\"777777777\"}]}"); - AccessController acClr = new AccessController(controller, properties); - - PersistentEventConnection p = new PersistentEventConnection.PersistentEventConnectionBuilder().setEventName("") - .setEventDescription("").setEventSseventUrlEmbed(true).setEventSseventsField("").setEventSseventsUrl("") - .setEventSubscriptionTemplate("").setEventUnSubscriptionTemplate("").setEventRuleId("1234646346") - .setParentCtrllr(acClr).setModifyEvent(true).setModifyMethod("modifyOntEvent") - .setUserData("remote_id=AC9.0234.0337;svlan=1001;macAddress=00:11:22:33:44:55;") - .createPersistentEventConnection(); - p.getEventParamMapValue("restapiUrl"); - p.modifyEventParamMap("restapiUrl", "10.118.191.43:26335"); - RestConfCollector.fProcessingInputQueue = new LinkedBlockingQueue<>(4); - p.getParentCtrllr().setRestApiCallNode(restApiCallNode); - RestConfCollector.fProcessingInputQueue.offer(new EventData(p, new JSONObject("{\n" + - " \"notification\" : {\n" + - " \"notification-id\" : \"01010101011\",\n" + - " \"event-time\" : \"2019-3-9T3:30:30.547z\",\n" + - " \"message\" : {\n" + - " \"object-type\" : \"onu\",\n" + - " \"topic\" : \"resources\",\n" + - " \"version\" : \"v1\",\n" + - " \"operation\" : \"create\",\n" + - " \"content\" : {\n" + - " \"onu\" : {\n" + - " \"alias\" : \"\",\n" + - " \"refParentLTP\" : \"gpon.0.5.1\",\n" + - " \"sn\" : \"HWTCC01B7503\",\n" + - " \"refParentLTPNativeId\" : \"NE=167772165,FR=0,S=5,CP=-1,PP=||1|\",\n" + - " \"onuId\": \"\",\n" + - " \"refParentNE\" : \"aaaaaaaaa-aaaaa-aaaa-aaaa-aaa167772165\",\n" + - " \"refParentNeNativeId\": \"NE=167772165\"\n" + - " }\n" + - " }\n" + - " }\n" + - " }\n" + - "}"))); - RestConfCollector.fProcessingInputQueue.offer(new EventData(null, null)); - EventProcessor ev = new EventProcessor(eventPublisher, streamMap); - ev.run(); - } catch (Exception e){} + when(properties.truststoreFileLocation()).thenReturn(TRUSTSTORE.toString()); + when(properties.truststorePasswordFileLocation()).thenReturn(TRUSTSTORE_PASSWORD_FILE.toString()); + when(properties.keystoreFileLocation()).thenReturn(KEYSTORE.toString()); + when(properties.keystorePasswordFileLocation()).thenReturn(KEYSTORE_PASSWORD_FILE.toString()); + when(properties.rccKeystoreFileLocation()).thenReturn(RCC_KEYSTORE.toString()); + when(properties.rccKeystorePasswordFileLocation()).thenReturn(RCC_KEYSTORE_PASSWORD_FILE.toString()); + when(properties.controllerConfigFileLocation()) + .thenReturn(Paths.get("etc/ont_config.json").toAbsolutePath().toString()); + + RestapiCallNode restApiCallNode = Mockito.mock(RestapiCallNode.class); + Mockito.doNothing().when(restApiCallNode).sendRequest(any(), any(), any()); + + + JSONObject controller = new JSONObject( + "{\"controller_name\":\"AccessM&C\",\"controller_restapiUrl\":\"10.118.191.43:26335\"," + + "\"controller_restapiUser\":\"access\",\"controller_restapiPassword\":\"Huawei@123\"," + + "\"controller_accessTokenUrl\":\"/rest/plat/smapp/v1/oauth/token\"," + + "\"controller_accessTokenFile\":\"./etc/access-token.json\"," + + "\"controller_accessTokenMethod\":\"put\",\"controller_subsMethod\":\"post\"," + + "\"controller_subscriptionUrl\":" + + "\"/restconf/v1/operations/huawei-nce-notification-action:establish-subscription\"," + + "\"controller_disableSsl\":\"true\",\"event_details\":[{\"event_name\":" + + "\"ONT_registration\",\"event_description\":\"ONTregistartionevent\"," + + "\"event_sseventUrlEmbed\":\"true\",\"event_sseventsField\":\"output.url\"," + + "\"event_sseventsUrl\":\"null\"," + + "\"event_subscriptionTemplate\":\"./etc/ont_registartion_subscription_template.json\"," + + "\"event_unSubscriptionTemplate\":" + + "\"./etc/ont_registartion_unsubscription_template.json\"," + + "\"event_ruleId\":\"777777777\"}]}"); + AccessController acClr = new AccessController(controller, properties); + + PersistentEventConnection eventConnection = new PersistentEventConnection.PersistentEventConnectionBuilder() + .setEventName("") + .setEventDescription("").setEventSseventUrlEmbed(true).setEventSseventsField("") + .setEventSseventsUrl("") + .setEventSubscriptionTemplate("").setEventUnSubscriptionTemplate("").setEventRuleId("1234646346") + .setParentCtrllr(acClr).setModifyEvent(true).setModifyMethod("modifyOntEvent") + .setUserData("remote_id=AC9.0234.0337;svlan=1001;macAddress=00:11:22:33:44:55;") + .createPersistentEventConnection(); + eventConnection.getEventParamMapValue("restapiUrl"); + eventConnection.modifyEventParamMap("restapiUrl", "10.118.191.43:26335"); + RestConfCollector.fProcessingInputQueue = new LinkedBlockingQueue<>(4); + eventConnection.getParentCtrllr().setRestApiCallNode(restApiCallNode); + RestConfCollector.fProcessingInputQueue.offer(new EventData(eventConnection, new JSONObject("{\n" + + " \"notification\" : {\n" + + " \"notification-id\" : \"01010101011\",\n" + + " \"event-time\" : \"2019-3-9T3:30:30.547z\",\n" + + " \"message\" : {\n" + + " \"object-type\" : \"onu\",\n" + + " \"topic\" : \"resources\",\n" + + " \"version\" : \"v1\",\n" + + " \"operation\" : \"create\",\n" + + " \"content\" : {\n" + + " \"onu\" : {\n" + + " \"alias\" : \"\",\n" + + " \"refParentLTP\" : \"gpon.0.5.1\",\n" + + " \"sn\" : \"HWTCC01B7503\",\n" + + " \"refParentLTPNativeId\" : \"NE=167772165,FR=0,S=5,CP=-1,PP=||1|\",\n" + + " \"onuId\": \"\",\n" + + " \"refParentNE\" : \"aaaaaaaaa-aaaaa-aaaa-aaaa-aaa167772165\",\n" + + " \"refParentNeNativeId\": \"NE=167772165\"\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + "}"))); + RestConfCollector.fProcessingInputQueue.offer(new EventData(null, null)); + EventProcessor ev = new EventProcessor(eventPublisher, streamMap); + ev.run(); + } catch (Exception e) { + System.out.println("Exception " + e); + } } } \ 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 index e54dd9b..61e9e85 100644 --- a/src/test/java/org/onap/dcae/common/FormatTest.java +++ b/src/test/java/org/onap/dcae/common/FormatTest.java @@ -17,13 +17,14 @@ * 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; +import org.junit.Test; + public class FormatTest { @Test diff --git a/src/test/java/org/onap/dcae/common/RestApiCallNodeTest.java b/src/test/java/org/onap/dcae/common/RestApiCallNodeTest.java index 3534a6c..3b533e9 100644 --- a/src/test/java/org/onap/dcae/common/RestApiCallNodeTest.java +++ b/src/test/java/org/onap/dcae/common/RestApiCallNodeTest.java @@ -20,20 +20,26 @@ package org.onap.dcae.common; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + import com.sun.jersey.api.client.WebResource; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Map; +import javax.ws.rs.core.MultivaluedHashMap; import org.glassfish.jersey.client.ClientResponse; import org.junit.Test; import org.mockito.Mockito; -import java.util.HashMap; -import java.util.Map; - -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.*; public class RestApiCallNodeTest { @Test - public void RestApiCallNodeTestSendEmptyMessageNoTemplate() { + public void restApiCallNodeTestSendEmptyMessageNoTemplate() { RestapiCallNode rest = new RestapiCallNode(); RestConfContext ctx = new RestConfContext(); Map paraMap = new HashMap<>(); @@ -65,8 +71,8 @@ public class RestApiCallNodeTest { String trustPassword = "admin"; paraMap.put(Constants.KSETTING_TRUST_STORE_PASSWORD, trustPassword); paraMap.put(Constants.KSETTING_KEY_STORE_FILENAME, null); - String KeyPassword = "admin"; - paraMap.put(Constants.KSETTING_KEY_STORE_PASSWD, KeyPassword); + String keyPassword = "admin"; + paraMap.put(Constants.KSETTING_KEY_STORE_PASSWD, keyPassword); WebResource webResource = mock(WebResource.class); @@ -77,11 +83,13 @@ public class RestApiCallNodeTest { when(webResource.accept(anyString())).thenReturn(webResourceBuilder); rest.sendRequest(paraMap, ctx, 1); - }catch (Exception e){} + } catch (Exception e) { + System.out.println("Exception " + e); + } } @Test - public void RestApiCallNodeTestSendEmptyMessageWithTemplate() { + public void restApiCallNodeTestSendEmptyMessageWithTemplate() { RestapiCallNode rest = new RestapiCallNode(); RestConfContext ctx = new RestConfContext(); Map paraMap = new HashMap<>(); @@ -97,7 +105,7 @@ public class RestApiCallNodeTest { paraMap.put(Constants.KSETTING_REST_PASSWD, null); paraMap.put(Constants.KDEFAULT_REQUESTBODY, null); - paraMap.put(Constants.KSETTING_AUTH_TYPE, "unspecified"); + paraMap.put(Constants.KSETTING_AUTH_TYPE, "digest"); paraMap.put(Constants.KSETTING_CONTENT_TYPE, "application/json"); paraMap.put(Constants.KSETTING_OAUTH_CONSUMER_KEY, null); paraMap.put(Constants.KSETTING_OAUTH_CONSUMER_SECRET, null); @@ -113,9 +121,60 @@ public class RestApiCallNodeTest { String trustPassword = "admin"; paraMap.put(Constants.KSETTING_TRUST_STORE_PASSWORD, trustPassword); paraMap.put(Constants.KSETTING_KEY_STORE_FILENAME, null); - String KeyPassword = "admin"; - paraMap.put(Constants.KSETTING_KEY_STORE_PASSWD, KeyPassword); + String keyPassword = "admin"; + paraMap.put(Constants.KSETTING_KEY_STORE_PASSWD, keyPassword); + + + WebResource webResource = mock(WebResource.class); + WebResource.Builder webResourceBuilder = mock(WebResource.Builder.class); + ClientResponse clientResponse = mock(ClientResponse.class); + try { + Mockito.doNothing().when(webResourceBuilder).method("post"); + when(webResource.accept(anyString())).thenReturn(webResourceBuilder); + + rest.sendRequest(paraMap, ctx, 1); + } catch (Exception e) { + System.out.println("Exception " + e); + } + } + + @Test + public void restApiCallNodeTestSkipSending() { + RestapiCallNode rest = new RestapiCallNode(); + RestConfContext ctx = new RestConfContext(); + Map paraMap = new HashMap<>(); + paraMap.put(Constants.KDEFAULT_TEMP_FILENAME, null); + paraMap.put(Constants.KSETTING_REST_API_URL, "https://127.0.0.1:8080/rest/sample"); + paraMap.put(Constants.KSETTING_HTTP_METHOD, "post"); + paraMap.put(Constants.KSETTING_RESP_PREFIX, "responsePrefix"); + paraMap.put(Constants.KSETTING_SKIP_SENDING, "false"); + paraMap.put(Constants.KSETTING_SSE_CONNECT_URL, null); + paraMap.put(Constants.KSETTING_FORMAT, "json"); + + paraMap.put(Constants.KSETTING_REST_UNAME, null); + paraMap.put(Constants.KSETTING_REST_PASSWD, null); + paraMap.put(Constants.KDEFAULT_REQUESTBODY, null); + paraMap.put(Constants.KSETTING_AUTH_TYPE, "unspecified"); + paraMap.put(Constants.KSETTING_CONTENT_TYPE, "application/json"); + paraMap.put(Constants.KSETTING_OAUTH_CONSUMER_KEY, null); + paraMap.put(Constants.KSETTING_OAUTH_CONSUMER_SECRET, null); + paraMap.put(Constants.KSETTING_OAUTH_SIGNATURE_METHOD, null); + paraMap.put(Constants.KSETTING_OAUTH_VERSION, null); + + paraMap.put(Constants.KSETTING_CUSTOMHTTP_HEADER, null); + paraMap.put(Constants.KSETTING_TOKENID, null); + paraMap.put(Constants.KSETTING_DUMP_HEADER, "false"); + paraMap.put(Constants.KSETTING_RETURN_REQUEST_PAYLOAD, "false"); + + paraMap.put(Constants.KSETTING_TRUST_STORE_FILENAME, null); + String trustPassword = "admin"; + paraMap.put(Constants.KSETTING_TRUST_STORE_PASSWORD, trustPassword); + paraMap.put(Constants.KSETTING_KEY_STORE_FILENAME, null); + String keyPassword = "admin"; + paraMap.put(Constants.KSETTING_KEY_STORE_PASSWD, keyPassword); + paraMap.put(Constants.KDEFAULT_DISABLE_SSL, "false"); + paraMap.put(Constants.KSETTING_SKIP_SENDING, "true"); WebResource webResource = mock(WebResource.class); WebResource.Builder webResourceBuilder = mock(WebResource.Builder.class); @@ -123,9 +182,119 @@ public class RestApiCallNodeTest { try { Mockito.doNothing().when(webResourceBuilder).method("post"); when(webResource.accept(anyString())).thenReturn(webResourceBuilder); + rest.sendRequest(paraMap, ctx, 1); + } catch (Exception e) { + System.out.println("Exception " + e); + } + } + + @Test + public void restApiCallNodeTestHttpResponse() { + RestapiCallNode rest = spy(RestapiCallNode.class); + RestConfContext ctx = new RestConfContext(); + Map paraMap = new HashMap<>(); + paraMap.put(Constants.KDEFAULT_TEMP_FILENAME, null); + paraMap.put(Constants.KSETTING_REST_API_URL, "https://127.0.0.1:8080/rest/sample"); + paraMap.put(Constants.KSETTING_HTTP_METHOD, "post"); + paraMap.put(Constants.KSETTING_RESP_PREFIX, "responsePrefix"); + paraMap.put(Constants.KSETTING_SKIP_SENDING, "false"); + paraMap.put(Constants.KSETTING_SSE_CONNECT_URL, null); + paraMap.put(Constants.KSETTING_FORMAT, "json"); + + paraMap.put(Constants.KSETTING_REST_UNAME, null); + paraMap.put(Constants.KSETTING_REST_PASSWD, null); + paraMap.put(Constants.KDEFAULT_REQUESTBODY, null); + paraMap.put(Constants.KSETTING_AUTH_TYPE, "unspecified"); + paraMap.put(Constants.KSETTING_CONTENT_TYPE, "application/json"); + paraMap.put(Constants.KSETTING_OAUTH_CONSUMER_KEY, null); + paraMap.put(Constants.KSETTING_OAUTH_CONSUMER_SECRET, null); + paraMap.put(Constants.KSETTING_OAUTH_SIGNATURE_METHOD, null); + paraMap.put(Constants.KSETTING_OAUTH_VERSION, null); + + paraMap.put(Constants.KSETTING_CUSTOMHTTP_HEADER, null); + paraMap.put(Constants.KSETTING_TOKENID, null); + paraMap.put(Constants.KSETTING_DUMP_HEADER, "false"); + paraMap.put(Constants.KSETTING_RETURN_REQUEST_PAYLOAD, "false"); + + paraMap.put(Constants.KSETTING_TRUST_STORE_FILENAME, null); + String trustPassword = "admin"; + paraMap.put(Constants.KSETTING_TRUST_STORE_PASSWORD, trustPassword); + paraMap.put(Constants.KSETTING_KEY_STORE_FILENAME, null); + String keyPassword = "admin"; + paraMap.put(Constants.KSETTING_KEY_STORE_PASSWD, keyPassword); + paraMap.put(Constants.KDEFAULT_DISABLE_SSL, "false"); + paraMap.put(Constants.KSETTING_SKIP_SENDING, "true"); + + WebResource webResource = mock(WebResource.class); + WebResource.Builder webResourceBuilder = mock(WebResource.Builder.class); + ClientResponse clientResponse = mock(ClientResponse.class); + HttpResponse response = new HttpResponse(); + response.code = 200; + response.body = "{\"prop2\"=\"value\", \"prop1\"=\"value\"}";; + response.message = "Some message"; + response.headers = new MultivaluedHashMap<>(); + response.headers.add("connection", "close"); + response.headers.add("content-encoding", "gzip"); + try { + Mockito.doNothing().when(webResourceBuilder).method("post"); + when(webResource.accept(anyString())).thenReturn(webResourceBuilder); + doReturn(response).when(rest).sendHttpRequest(any(), any()); rest.sendRequest(paraMap, ctx, 1); - }catch (Exception e){} + } catch (Exception e) { + System.out.println("Exception " + e); + } } + @Test + public void restApiCallNodeTestWithSsl() { + RestapiCallNode rest = new RestapiCallNode(); + RestConfContext ctx = new RestConfContext(); + Map paraMap = new HashMap<>(); + paraMap.put(Constants.KDEFAULT_TEMP_FILENAME, null); + paraMap.put(Constants.KSETTING_REST_API_URL, "https://127.0.0.1:8080/rest/sample"); + paraMap.put(Constants.KSETTING_HTTP_METHOD, "post"); + paraMap.put(Constants.KSETTING_RESP_PREFIX, "responsePrefix"); + paraMap.put(Constants.KSETTING_SKIP_SENDING, "false"); + paraMap.put(Constants.KSETTING_SSE_CONNECT_URL, null); + paraMap.put(Constants.KSETTING_FORMAT, "json"); + + paraMap.put(Constants.KSETTING_REST_UNAME, null); + paraMap.put(Constants.KSETTING_REST_PASSWD, null); + paraMap.put(Constants.KDEFAULT_REQUESTBODY, null); + + paraMap.put(Constants.KSETTING_AUTH_TYPE, "unspecified"); + paraMap.put(Constants.KSETTING_CONTENT_TYPE, "application/json"); + paraMap.put(Constants.KSETTING_OAUTH_CONSUMER_KEY, null); + paraMap.put(Constants.KSETTING_OAUTH_CONSUMER_SECRET, null); + paraMap.put(Constants.KSETTING_OAUTH_SIGNATURE_METHOD, null); + paraMap.put(Constants.KSETTING_OAUTH_VERSION, null); + + paraMap.put(Constants.KSETTING_CUSTOMHTTP_HEADER, null); + paraMap.put(Constants.KSETTING_TOKENID, null); + paraMap.put(Constants.KSETTING_DUMP_HEADER, "false"); + paraMap.put(Constants.KSETTING_RETURN_REQUEST_PAYLOAD, "false"); + paraMap.put(Constants.KSETTING_SKIP_SENDING, "true"); + + paraMap.put(Constants.KSETTING_TRUST_STORE_FILENAME, "src/test/resources/truststore"); + String trustPassword = "vestest"; + paraMap.put(Constants.KSETTING_TRUST_STORE_PASSWORD, trustPassword); + paraMap.put(Constants.KSETTING_KEY_STORE_FILENAME, "src/test/resources/keystore"); + String keyPassword = "vestest"; + paraMap.put(Constants.KSETTING_KEY_STORE_PASSWD, keyPassword); + paraMap.put(Constants.KDEFAULT_DISABLE_SSL, "false"); + + WebResource webResource = mock(WebResource.class); + WebResource.Builder webResourceBuilder = mock(WebResource.Builder.class); + ClientResponse clientResponse = mock(ClientResponse.class); + + try { + Mockito.doNothing().when(webResourceBuilder).method("post"); + when(webResource.accept(anyString())).thenReturn(webResourceBuilder); + + rest.sendRequest(paraMap, ctx, 1); + } catch (Exception e) { + System.out.println("Exception " + e); + } + } } \ 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 index 00b07f8..c8bfe48 100644 --- a/src/test/java/org/onap/dcae/common/RestConfContextTest.java +++ b/src/test/java/org/onap/dcae/common/RestConfContextTest.java @@ -20,10 +20,13 @@ package org.onap.dcae.common; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import org.junit.Test; -import org.onap.dcae.common.RestConfContext; -import static org.junit.Assert.*; + public class RestConfContextTest { @@ -47,6 +50,7 @@ public class RestConfContextTest { RestConfContext restConfContext = new RestConfContext(); restConfContext.setAttribute(key,value); restConfContext.setAttribute(key1,value1); - assertTrue(restConfContext.getAttributeKeySet().contains(key) && restConfContext.getAttributeKeySet().contains(key1)); + 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 index f05541f..d34e508 100644 --- a/src/test/java/org/onap/dcae/common/XmlJsonUtilTest.java +++ b/src/test/java/org/onap/dcae/common/XmlJsonUtilTest.java @@ -20,15 +20,13 @@ package org.onap.dcae.common; -import org.json.XML; -import org.junit.Test; +import static org.junit.Assert.assertEquals; import java.util.HashMap; -import java.util.HashSet; import java.util.Map; -import java.util.Set; +import org.junit.Test; + -import static org.junit.Assert.assertEquals; public class XmlJsonUtilTest { @@ -43,29 +41,33 @@ public class XmlJsonUtilTest { mm.put("result.output", "xml2json"); mm.put("result.[", "start"); mm.put("result.]", "end"); - mm.put("result.list", "\n" + - " \n" + - " "); + mm.put("result.list", "\n" + + " \n" + + " "); try { String str = XmlJsonUtil.getXml(mm, var); assertEquals(str.startsWith("<"), true); String str2 = XmlJsonUtil.getJson(mm, var); assertEquals(str2.startsWith("{"), true); - }catch (Exception e) {} + } catch (Exception e) { + System.out.println("Exception " + e); + } } @Test public void removeEmptystructFromXml() { - String var = "\n" + - "t2\n" + - "bad\n" + - "200"; + String var = "\n" + + "t2\n" + + "bad\n" + + "200"; Map mm = new HashMap<>(); try { String str = XmlJsonUtil.removeEmptyStructXml(var); - }catch (Exception e) {} + } catch (Exception e) { + System.out.println("Exception " + e); + } } @Test @@ -75,14 +77,37 @@ public class XmlJsonUtilTest { try { String str = XmlJsonUtil.removeEmptyStructJson(var); - }catch (Exception e) {} + } catch (Exception e) { + System.out.println("Exception " + e); + } } @Test public void removeLastCommaJson() { - String var2 ="{\"name\":\"john\",\"age\":22,\"class\":\"mca\", \"data\":{}, \"arr\" : [\"some\" : {},],}"; + String var2 = "{\"name\":\"john\",\"age\":22,\"class\":\"mca\", \"data\":{}, \"arr\" : [\"some\" : {},],}"; try { String str = XmlJsonUtil.removeLastCommaJson(var2); - }catch (Exception e) {} + } catch (Exception e) { + System.out.println("Exception " + e); + } } + + @Test + public void getJsonOrXmlTest2() { + String var = "result"; + Map mm = new HashMap<>(); + + mm.put("result[0]", "{\"metaname\": \"remote-id\",\"metaval\": " + + "\"AC9.0234.0337\",\"resource-version\": \"1553802421110\"}"); + mm.put("result[1]", "{\"metaname\": \"remote-id\",\"metaval\": " + + "\"AC9.0234.0337\",\"resource-version\": \"1553802421110\"}"); + + try { + String str2 = XmlJsonUtil.getJson(mm, var); + assertEquals(str2.startsWith("["), true); + } catch (Exception e) { + System.out.println("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 index b005c89..5ca80c0 100644 --- a/src/test/java/org/onap/dcae/common/XmlParserTest.java +++ b/src/test/java/org/onap/dcae/common/XmlParserTest.java @@ -20,27 +20,26 @@ 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.*; +import org.junit.Test; public class XmlParserTest { @Test public void setAttribute() { - String convert = "\n" + - "t2\n" + - "200"; + 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) {} + } catch (Exception e) { + System.out.println("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 index 2865b75..79ac03b 100644 --- a/src/test/java/org/onap/dcae/common/publishing/DMaaPEventPublisherTest.java +++ b/src/test/java/org/onap/dcae/common/publishing/DMaaPEventPublisherTest.java @@ -18,6 +18,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.dcae.common.publishing; import static io.vavr.API.Option; @@ -40,14 +41,17 @@ public class DMaaPEventPublisherTest { private DMaaPEventPublisher eventPublisher; private CambriaBatchingPublisher cambriaPublisher; - private DMaaPPublishersCache DMaaPPublishersCache; + private DMaaPPublishersCache dmaapPublishersCache; + /** + * Setup before test. + */ @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)); + dmaapPublishersCache = mock(DMaaPPublishersCache.class); + when(dmaapPublishersCache.getPublisher(anyString())).thenReturn(Option(cambriaPublisher)); + eventPublisher = new DMaaPEventPublisher(dmaapPublishersCache, mock(Logger.class)); } @Test @@ -74,6 +78,6 @@ public class DMaaPEventPublisherTest { eventPublisher.sendEvent(event, STREAM_ID); // then - verify(DMaaPPublishersCache).closePublisherFor(STREAM_ID); + 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 index 2884e44..6f3696d 100644 --- a/src/test/java/org/onap/dcae/common/publishing/DMaaPPublishersCacheTest.java +++ b/src/test/java/org/onap/dcae/common/publishing/DMaaPPublishersCacheTest.java @@ -18,6 +18,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.dcae.common.publishing; import static io.vavr.API.List; @@ -43,22 +44,41 @@ import org.onap.dcae.common.publishing.DMaaPPublishersCache.OnPublisherRemovalLi public class DMaaPPublishersCacheTest { private String streamId1; - private Map dMaaPConfigs; - + private Map dmaapconfigs; + private Map dmaapconfigs2; + /** + * Setup before test. + */ @Before public void setUp() { streamId1 = "sampleStream1"; - dMaaPConfigs = Map("sampleStream1", new PublisherConfig(List("destination1"), "topic1")); + dmaapconfigs = Map("sampleStream1", new PublisherConfig(List("destination1"), "topic1")); + dmaapconfigs2 = Map("sampleStream1", new PublisherConfig(List("destination1"), + "topic1", "user", "pass")); + } @Test public void shouldReturnTheSameCachedInstanceOnConsecutiveRetrievals() { // given - DMaaPPublishersCache dMaaPPublishersCache = new DMaaPPublishersCache(dMaaPConfigs); + 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 shouldReturnTheSameCachedInstanceOnConsecutiveRetrievals2() { + // given + DMaaPPublishersCache dmaapPublishersCache = new DMaaPPublishersCache(dmaapconfigs2); // when - Option firstPublisher = dMaaPPublishersCache.getPublisher(streamId1); - Option secondPublisher = dMaaPPublishersCache.getPublisher(streamId1); + Option firstPublisher = dmaapPublishersCache.getPublisher(streamId1); + Option secondPublisher = dmaapPublishersCache.getPublisher(streamId1); // then assertSame("should return same instance", firstPublisher.get(), secondPublisher.get()); @@ -69,14 +89,14 @@ public class DMaaPPublishersCacheTest { // given CambriaBatchingPublisher cambriaPublisherMock1 = mock(CambriaBatchingPublisher.class); CambriaPublishersCacheLoader cacheLoaderMock = mock(CambriaPublishersCacheLoader.class); - DMaaPPublishersCache dMaaPPublishersCache = new DMaaPPublishersCache(cacheLoaderMock, + DMaaPPublishersCache dmaapPublishersCache = new DMaaPPublishersCache(cacheLoaderMock, new OnPublisherRemovalListener(), - dMaaPConfigs); + dmaapconfigs); when(cacheLoaderMock.load(streamId1)).thenReturn(cambriaPublisherMock1); // when - dMaaPPublishersCache.getPublisher(streamId1); - dMaaPPublishersCache.closePublisherFor(streamId1); + dmaapPublishersCache.getPublisher(streamId1); + dmaapPublishersCache.closePublisherFor(streamId1); // then verify(cambriaPublisherMock1).close(20, TimeUnit.SECONDS); @@ -84,12 +104,12 @@ public class DMaaPPublishersCacheTest { } @Test - public void shouldReturnNoneIfThereIsNoDMaaPConfigurationForGivenStreamID() { + public void shouldReturnNoneIfThereIsNoDmaaPConfigurationForGivenStreamId() { // given - DMaaPPublishersCache dMaaPPublishersCache = new DMaaPPublishersCache(dMaaPConfigs); + DMaaPPublishersCache dmaapPublishersCache = new DMaaPPublishersCache(dmaapconfigs); // then - assertTrue("should not exist", dMaaPPublishersCache.getPublisher("non-existing").isEmpty()); + assertTrue("should not exist", dmaapPublishersCache.getPublisher("non-existing").isEmpty()); } @@ -106,19 +126,22 @@ public class DMaaPPublishersCacheTest { 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, + + DMaaPPublishersCache dmaapPublishersCache = new DMaaPPublishersCache(cacheLoaderMock, new OnPublisherRemovalListener(), oldConfig); + final Map newConfig = Map(firstDomain, + new PublisherConfig(List("destination1"), "topic1"), + secondDomain, new PublisherConfig(List("destination2"), "topic2")); + when(cacheLoaderMock.load(firstDomain)).thenReturn(cambriaPublisherMock1); when(cacheLoaderMock.load(secondDomain)).thenReturn(cambriaPublisherMock2); - dMaaPPublishersCache.getPublisher(firstDomain); - dMaaPPublishersCache.getPublisher(secondDomain); + dmaapPublishersCache.getPublisher(firstDomain); + dmaapPublishersCache.getPublisher(secondDomain); // when - dMaaPPublishersCache.reconfigure(newConfig); + dmaapPublishersCache.reconfigure(newConfig); // then verify(cambriaPublisherMock2).close(20, TimeUnit.SECONDS); diff --git a/src/test/java/org/onap/dcae/common/publishing/JsonParserTest.java b/src/test/java/org/onap/dcae/common/publishing/JsonParserTest.java index f00df2c..54d0cfc 100644 --- a/src/test/java/org/onap/dcae/common/publishing/JsonParserTest.java +++ b/src/test/java/org/onap/dcae/common/publishing/JsonParserTest.java @@ -17,22 +17,30 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.dcae.common.publishing; -import java.util.Map; +import static org.junit.Assert.assertEquals; +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")); - } + @Test + public void convertToPropertiesTest() throws Exception { + String testJson = "{\"prop2\"=\"value\", \"prop1\"=\"value\"}"; + Map response = JsonParser.convertToProperties(testJson); + assertEquals("value", response.get("prop2")); + } + + @Test + public void convertToPropertiesTestwithArray() throws Exception { + String testJson = "{\"metadatum\": [{\"metaname\": \"remote-id\",\"metaval\": \"AC9.0234.0337\"," + + "\"resource-version\": \"1553802421110\"},{\"metaname\": \"svlan\",\"metaval\": \"100\"," + + "\"resource-version\": \"1553802421082\"}]}"; + Map response = JsonParser.convertToProperties(testJson); + assertEquals("100", response.get("metadatum[1].metaval")); + } } diff --git a/src/test/java/org/onap/dcae/controller/ConfigCBSSourceTest.java b/src/test/java/org/onap/dcae/controller/ConfigCBSSourceTest.java deleted file mode 100644 index b34d393..0000000 --- a/src/test/java/org/onap/dcae/controller/ConfigCBSSourceTest.java +++ /dev/null @@ -1,151 +0,0 @@ -/*- - * ============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\": 8080}"; - - 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/ConfigCbsSourceTest.java b/src/test/java/org/onap/dcae/controller/ConfigCbsSourceTest.java new file mode 100644 index 0000000..2c42e9e --- /dev/null +++ b/src/test/java/org/onap/dcae/controller/ConfigCbsSourceTest.java @@ -0,0 +1,153 @@ +/*- + * ============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\": 8080}"; + + 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 index 4130ceb..af87c30 100644 --- a/src/test/java/org/onap/dcae/controller/ConfigFilesFacadeTest.java +++ b/src/test/java/org/onap/dcae/controller/ConfigFilesFacadeTest.java @@ -19,16 +19,17 @@ * 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.assertJsonObjectsEqual; 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.TestingUtilities.readJsonFromFile; import io.vavr.collection.Map; import io.vavr.control.Try; @@ -39,14 +40,14 @@ import org.junit.Test; public class ConfigFilesFacadeTest { - private static final Path NON_EXISTENT = Paths.get("/non-existent"); + private static final Path NON_EXISTENT = Paths.get("/non-existent-file"); 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"); + Path temporaryFile = createTemporaryFile("temp_shouldReadPropertyFile","some.property=10"); // when ConfigFilesFacade configFilesFacade = new ConfigFilesFacade(temporaryFile, temporaryFile); @@ -63,22 +64,22 @@ public class ConfigFilesFacadeTest { @Test public void shouldReadDMaaPFile() { // given - Path temporaryFile = createTemporaryFile("{}"); + Path temporaryFile = createTemporaryFile("temp_shouldReadDMaaPFile","{}"); // when ConfigFilesFacade configFilesFacade = new ConfigFilesFacade(temporaryFile, temporaryFile); - Try dMaaPConfiguration = configFilesFacade.readDMaaPConfiguration(); + Try dmaapconfiguration = configFilesFacade.readDMaaPConfiguration(); // then - assertThat(dMaaPConfiguration.isSuccess()).isTrue(); - assertThat(dMaaPConfiguration.get().toString()).isEqualTo("{}"); + assertThat(dmaapconfiguration.isSuccess()).isTrue(); + assertThat(dmaapconfiguration.get().toString()).isEqualTo("{}"); } @Test public void shouldWriteDMaaPConf() { // given - Path temporaryFile = createTemporaryFile("{}"); + Path temporaryFile = createTemporaryFile("temp_shouldWriteDMaaPConf","{}"); JSONObject desiredConf = new JSONObject("{\"key\": 1}"); // when @@ -88,14 +89,14 @@ public class ConfigFilesFacadeTest { // then assertThat(propertiesConfigurations.isSuccess()).isTrue(); - assertJSONObjectsEqual(readJSONFromFile(temporaryFile), desiredConf); + assertJsonObjectsEqual(readJsonFromFile(temporaryFile), desiredConf); } @Test public void shouldWriteProperties() { // given - Path temporaryFile = createTemporaryFile("{}"); + Path temporaryFile = createTemporaryFile("temp_shouldWriteProperties", "{}"); // when ConfigFilesFacade configFilesFacade = new ConfigFilesFacade(temporaryFile, temporaryFile); diff --git a/src/test/java/org/onap/dcae/controller/ConfigLoaderIntegrationE2ETest.java b/src/test/java/org/onap/dcae/controller/ConfigLoaderIntegrationE2ETest.java index bcba7fb..be63b50 100644 --- a/src/test/java/org/onap/dcae/controller/ConfigLoaderIntegrationE2ETest.java +++ b/src/test/java/org/onap/dcae/controller/ConfigLoaderIntegrationE2ETest.java @@ -19,84 +19,58 @@ * 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.*; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyZeroInteractions; 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.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\": 8080, \"streams_publishes\": %s}}", dMaaPConf)); -// -// EventPublisher eventPublisherMock = mock(EventPublisher.class); -// -// RestConfCollector rs = 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 = 8080"); -// 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\": 8080, \"streams_publishes\": %s}}", dMaaPConf)); - EventPublisher eventPublisherMock = mock(EventPublisher.class); - ConfigFilesFacade configFilesFacade = new ConfigFilesFacade(dMaaPConfigFile, collectorPropertiesFile); - configFilesFacade.writeProperties(Map("collector.port", "8080")); - configFilesFacade.writeDMaaPConfiguration(dMaaPConf); - - ConfigLoader configLoader = new ConfigLoader(eventPublisherMock::reconfigure, configFilesFacade, ConfigSource::getAppConfig, () -> wiremockBasedEnvProps()); - configLoader.updateConfig(); - // then + try { + Path dmaapConfigFile = createTemporaryFile("temp_dmaapConfigFile", "{}"); + Path collectorPropertiesFile = createTemporaryFile("temp_collectorPropertiesFile", ""); + JSONObject dmaapConf = readJsonFromFile( + Paths.get("src/test/resources/testParseDMaaPCredentialsGen2.json")); + stubConsulToReturnLocalAddressOfCbs(); + stubCbsToReturnAppConfig(f("{\"collector.port\": 8080, \"streams_publishes\": %s}}", dmaapConf)); + EventPublisher eventPublisherMock = mock(EventPublisher.class); + ConfigFilesFacade configFilesFacade = new ConfigFilesFacade(dmaapConfigFile, collectorPropertiesFile); + configFilesFacade.writeProperties(Map("collector.port", "8080")); + configFilesFacade.writeDMaaPConfiguration(dmaapConf); - verifyZeroInteractions(eventPublisherMock); + ConfigLoader configLoader = new ConfigLoader(eventPublisherMock::reconfigure, + configFilesFacade, ConfigSource::getAppConfig, () -> wiremockBasedEnvProps()); + configLoader.updateConfig(); + // then - // when - JSONObject dMaaPConf2 = readJSONFromFile(Paths.get("src/test/resources/testParseDMaaPCredentialsGen2Temp.json")); - configFilesFacade.writeDMaaPConfiguration(dMaaPConf2); - configFilesFacade.writeProperties(Map("collector.port", "8081")); - configLoader.updateConfig(); + verifyZeroInteractions(eventPublisherMock); + // when + JSONObject dmaapConf2 = readJsonFromFile( + Paths.get("src/test/resources/testParseDMaaPCredentialsGen2Temp.json")); + configFilesFacade.writeDMaaPConfiguration(dmaapConf2); + configFilesFacade.writeProperties(Map("collector.port", "8081")); + configLoader.updateConfig(); + } catch (Exception e) { + System.out.println("Exception " + e); + } } } \ 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 index 7792b71..29c14e9 100644 --- a/src/test/java/org/onap/dcae/controller/ConfigParsingTest.java +++ b/src/test/java/org/onap/dcae/controller/ConfigParsingTest.java @@ -25,14 +25,11 @@ 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 static org.onap.dcae.TestingUtilities.assertJsonObjectsEqual; 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; @@ -43,16 +40,16 @@ 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 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); + root.put("streams_publishes", dmaapConf); - Option dMaaPConfig = ConfigParsing.getDMaaPConfig(root); + Option dmaapConfig = ConfigParsing.getDMaaPConfig(root); - assertThat(dMaaPConfig.isEmpty()).isFalse(); - assertJSONObjectsEqual(dMaaPConfig.get(), dMaaPConf); + assertThat(dmaapConfig.isEmpty()).isFalse(); + assertJsonObjectsEqual(dmaapConfig.get(), dmaapConf); } @Test @@ -60,18 +57,18 @@ public class ConfigParsingTest { JSONObject root = new JSONObject(); root.put("streams_publishes", 1); - Option dMaaPConfig = ConfigParsing.getDMaaPConfig(root); + Option dmaapConfig = ConfigParsing.getDMaaPConfig(root); - assertThat(dMaaPConfig.isEmpty()).isTrue(); + 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 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); + root.put("streams_publishes", dmaapConf); Map properties = ConfigParsing.getProperties(root); assertThat(properties).isEqualTo(Map("key1", "someProperty", "key2", "someProperty")); diff --git a/src/test/java/org/onap/dcae/controller/EnvPropertiesReaderTest.java b/src/test/java/org/onap/dcae/controller/EnvPropertiesReaderTest.java index 2e215a7..5fef321 100644 --- a/src/test/java/org/onap/dcae/controller/EnvPropertiesReaderTest.java +++ b/src/test/java/org/onap/dcae/controller/EnvPropertiesReaderTest.java @@ -19,6 +19,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.dcae.controller; import static io.vavr.API.Map; @@ -41,7 +42,7 @@ public class EnvPropertiesReaderTest { } @Test - public void shouldReturnEmptyOnMissingCBSName() { + public void shouldReturnEmptyOnMissingCbsName() { Map envs = Map( "CONSUL_HOST", "doesNotMatter", "HOSTNAME", "doesNotMatter"); @@ -49,7 +50,7 @@ public class EnvPropertiesReaderTest { } @Test - public void shouldReturnEmptyOnMissingVESAppName() { + public void shouldReturnEmptyOnMissingVesAppName() { Map envs = Map( "CONSUL_HOST", "doesNotMatter", "CONFIG_BINDING_SERVICE", "doesNotMatter"); diff --git a/src/test/java/org/onap/dcae/controller/EnvPropsTest.java b/src/test/java/org/onap/dcae/controller/EnvPropsTest.java index e9c194e..1276e6b 100644 --- a/src/test/java/org/onap/dcae/controller/EnvPropsTest.java +++ b/src/test/java/org/onap/dcae/controller/EnvPropsTest.java @@ -20,22 +20,25 @@ package org.onap.dcae.controller; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; +import static org.junit.Assert.assertEquals; + 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); + 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 index 1427438..e8e911a 100644 --- a/src/test/java/org/onap/dcae/restapi/ApiAuthInterceptionTest.java +++ b/src/test/java/org/onap/dcae/restapi/ApiAuthInterceptionTest.java @@ -21,8 +21,19 @@ package org.onap.dcae.restapi; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import io.vavr.collection.HashMap; import io.vavr.collection.Map; +import java.io.IOException; +import java.io.PrintWriter; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + + import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; @@ -35,15 +46,6 @@ 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 { -- cgit 1.2.3-korg