diff options
Diffstat (limited to 'services/appc-dmaap-service/appc-event-listener-bundle/src/test/java')
29 files changed, 2947 insertions, 0 deletions
diff --git a/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/AbstractListenerTest.java b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/AbstractListenerTest.java new file mode 100644 index 000000000..a47175c02 --- /dev/null +++ b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/AbstractListenerTest.java @@ -0,0 +1,152 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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.appc.listener; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyLong; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Properties; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; + +import java.util.concurrent.TimeUnit; +import org.junit.Before; +import org.junit.Test; +import org.onap.appc.listener.AbstractListener; +import org.onap.appc.listener.ListenerProperties; + +public class AbstractListenerTest { + + private DummyListener listener; + private ListenerProperties props; + + @Before + public void setup() throws Exception { + Properties regularProps = new Properties(); + regularProps.load(getClass().getResourceAsStream("/org/onap/appc/default.properties")); + props = new ListenerProperties("", regularProps); + listener = new DummyListener(props); + } + + @Test + public void stop_should_shutdown_executor() { + + EventHandler mockEventHandler = mock(EventHandler.class); + listener.setEventHandler(mockEventHandler); + + Thread thread = new Thread(listener); + thread.start(); + + assertTrue(thread.isAlive()); + assertTrue(listener.getRun()); + assertFalse(listener.getExecutor().isShutdown()); + assertFalse(listener.getExecutor().isTerminated()); + + listener.stop(); + + assertFalse(listener.getRun()); + assertTrue(listener.getExecutor().isShutdown()); + assertTrue(listener.getExecutor().isTerminated()); + + verify(mockEventHandler).closeClients(); + + } + + @Test + public void stopNow_should_clear_executors_queue_and_call_stop() throws InterruptedException { + EventHandler mockEventHandler = mock(EventHandler.class); + listener.setEventHandler(mockEventHandler); + + ThreadPoolExecutor mockExecutor = mock(ThreadPoolExecutor.class); + BlockingQueue<Runnable> mockBlockingQueue = mock(BlockingQueue.class); + listener.setExecutor(mockExecutor); + when(mockExecutor.getQueue()).thenReturn(mockBlockingQueue); + + Thread thread = new Thread(listener); + thread.start(); + + assertTrue(thread.isAlive()); + assertTrue(listener.getRun()); + + listener.stopNow(); + + assertFalse(listener.getRun()); + verify(mockExecutor).shutdown(); + verify(mockExecutor).awaitTermination(anyLong(), any(TimeUnit.class)); + verify(mockBlockingQueue).clear(); + verify(mockEventHandler).closeClients(); + } + + @Test + public void getBenchmark_result_should_contain_listenerId() { + String out = listener.getBenchmark(); + assertNotNull(out); + assertTrue(out.contains(listener.getListenerId())); + } + + @Test + public void getListenerId_should_return_properties_prefix_by_default() { + assertEquals(props.getPrefix(), listener.getListenerId()); + listener.setListenerId("newId"); + assertEquals("newId", listener.getListenerId()); + } + + + private class DummyListener extends AbstractListener { + + DummyListener(ListenerProperties props) { + super(props); + } + + boolean getRun() { + return run.get(); + } + + public ThreadPoolExecutor getExecutor() { + return executor; + } + + void setEventHandler(EventHandler eventHandler){ + dmaap = eventHandler; + } + + void setExecutor(ThreadPoolExecutor executor){ + this.executor = executor; + } + + @Override + public void run() { + + while (run.get()) { + } + } + } +} diff --git a/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/AppcEventListenerActivatorTest.java b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/AppcEventListenerActivatorTest.java new file mode 100644 index 000000000..0dc1d4d3f --- /dev/null +++ b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/AppcEventListenerActivatorTest.java @@ -0,0 +1,80 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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.appc.listener; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import org.junit.Test; +import org.mockito.Mockito; + +import static org.mockito.Mockito.doReturn; + +import org.onap.appc.listener.AppcEventListenerActivator; + +public class AppcEventListenerActivatorTest { + + @Test + public void testStartStopDefaultProperties() { + AppcEventListenerActivator appc = new AppcEventListenerActivator(); + try { + appc.start(); + Thread.sleep(1000); + appc.stop(); + } catch (Exception e) { + e.printStackTrace(); + fail(e.getMessage()); + } + assertNotNull(appc.getName()); + } + + @Test + public void testStartStopEmptyProperties() { + InputStream input = getClass().getResourceAsStream("/org/onap/appc/empty.properties"); + Properties props = new Properties(); + try { + props.load(input); + } catch (IOException e) { + e.printStackTrace(); + } + + AppcEventListenerActivator appc = new AppcEventListenerActivator(); + AppcEventListenerActivator spyAppc = Mockito.spy(appc); + doReturn(props).when(spyAppc).getProperties(); + + try { + spyAppc.start(); + Thread.sleep(1000); + spyAppc.stop(); + } catch (Exception e) { + e.printStackTrace(); + fail(e.getMessage()); + } + assertNotNull(spyAppc.getName()); + } +} diff --git a/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/conv/ConverterTest.java b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/conv/ConverterTest.java new file mode 100644 index 000000000..037f91a6e --- /dev/null +++ b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/conv/ConverterTest.java @@ -0,0 +1,143 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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.appc.listener.LCM.conv; + +import static org.junit.Assert.assertEquals; +import static org.onap.appc.listener.TestUtil.JSON_INPUT_BODY_STR; +import static org.onap.appc.listener.TestUtil.JSON_OUTPUT_BODY_STR; +import static org.onap.appc.listener.TestUtil.buildDmaapIncomingMessage; +import static org.onap.appc.listener.TestUtil.buildDmaapOutgoingMessage; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import org.junit.Test; +import org.onap.appc.listener.LCM.model.DmaapIncomingMessage; +import org.onap.appc.listener.LCM.model.DmaapOutgoingMessage; +import org.onap.appc.listener.util.Mapper; +import org.onap.ccsdk.sli.core.sli.SvcLogicException; + +public class ConverterTest { + + private static final String EXPECTED_DMAAP_OUTGOING_MESSAGE_AS_JSON_STRING = + "{\"body\":{\"output\":{\"common-header\":" + + "{\"timestamp\":\"2016-08-03T08:50:18.97Z\",\"api-ver\":\"1\",\"flags\":{\"force\":\"TRUE\",\"ttl\":\"9900\"}," + + "\"sub-request-id\":\"1\",\"request-id\":\"123\",\"originator-id\":\"1\"},\"locked\":\"test-locked\",\"" + + "status\":{\"message\":\"test message\",\"code\":200}}},\"cambria.partition\":\"MSO\",\"rpc-name\":\"test\"}"; + + @Test(expected = IllegalArgumentException.class) + public void convertJsonNodeToDmaapOutgoingMessage_should_throw_when_given_null_arguments() { + + Converter.convertJsonNodeToDmaapOutgoingMessage(null, null); + } + + @Test + public void convertJsonNodeToDmaapOutgoingMessage_should_convert_to_outgoing_message() { + + DmaapIncomingMessage message = new DmaapIncomingMessage(); + message.setRpcName("test"); + message.setCorrelationID("test-1"); + message.setVersion("v1"); + JsonNode jsonNode = Mapper.toJsonNodeFromJsonString(JSON_INPUT_BODY_STR); + message.setBody(jsonNode); + + DmaapOutgoingMessage result = Converter.convertJsonNodeToDmaapOutgoingMessage(message, jsonNode); + + assertEquals("test", result.getRpcName()); + assertEquals("test-1", result.getCorrelationID()); + assertEquals("v1", result.getVersion()); + assertEquals(jsonNode, result.getBody()); + } + + @Test(expected = IllegalArgumentException.class) + public void convertDmaapOutgoingMessageToJsonString_should_throw_when_given_null_arguments() + throws JsonProcessingException { + + Converter.convertDmaapOutgoingMessageToJsonString(null); + } + + @Test + public void convertDmaapOutgoingMessageToJsonString_should_return_converted_json_string() + throws JsonProcessingException { + + DmaapOutgoingMessage message = new DmaapOutgoingMessage(); + message.setRpcName("test"); + JsonNode jsonNode = Mapper.toJsonNodeFromJsonString(JSON_OUTPUT_BODY_STR); + message.setBody(jsonNode); + + assertEquals(EXPECTED_DMAAP_OUTGOING_MESSAGE_AS_JSON_STRING, + Converter.convertDmaapOutgoingMessageToJsonString(message)); + } + + @Test(expected = IllegalArgumentException.class) + public void buildDmaapOutgoingMessageWithUnexpectedErrorTest_should_throw_given_null_arguments() + throws JsonProcessingException { + + Converter.buildDmaapOutgoingMessageWithUnexpectedError(null, null); + } + + @Test + public void buildDmaapOutgoingMessageWithUnexpectedErrorTest_should_build_valid_outgoing_message() + throws JsonProcessingException { + + DmaapIncomingMessage dmaapIncomingMessage = buildDmaapIncomingMessage(); + String errMsg = "TestException"; + DmaapOutgoingMessage dmaapOutgoingMessage = Converter + .buildDmaapOutgoingMessageWithUnexpectedError(dmaapIncomingMessage, new Exception(errMsg)); + int code = dmaapOutgoingMessage.getBody().get("output").get("status").get("code").asInt(); + String value = dmaapOutgoingMessage.getBody().get("output").get("status").get("value").asText(); + assertEquals(200, code); + assertEquals(errMsg, value); + } + + + @Test(expected = IllegalArgumentException.class) + public void extractRequestIdWithSubId_should_throw_given_null_argument() throws SvcLogicException { + + Converter.extractRequestIdWithSubId(null); + } + + @Test + public void extractRequestIdWithSubIdTest_should_extract_id_with_subDd() throws SvcLogicException { + DmaapIncomingMessage dmaapIncomingMessage = buildDmaapIncomingMessage(); + + String requestIdWithSubId = Converter.extractRequestIdWithSubId(dmaapIncomingMessage.getBody()); + assertEquals("123-1", requestIdWithSubId); + } + + + @Test(expected = IllegalArgumentException.class) + public void extractStatusCode_should_throw_given_null_argument() { + Converter.extractStatusCode(null); + } + + + @Test + public void extractStatusCode_should_extract_valid_status_code() { + DmaapOutgoingMessage dmaapOutgoingMessage = buildDmaapOutgoingMessage(); + Integer statusCode = Converter.extractStatusCode(dmaapOutgoingMessage.getBody()); + assertEquals(200L, statusCode.longValue()); + } + + +} diff --git a/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/impl/ListenerImplTest.java b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/impl/ListenerImplTest.java new file mode 100644 index 000000000..900e9c5fc --- /dev/null +++ b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/impl/ListenerImplTest.java @@ -0,0 +1,97 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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.appc.listener.LCM.impl; + +import static org.junit.Assert.fail; + +import java.util.Properties; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.onap.appc.listener.Listener; +import org.onap.appc.listener.ListenerProperties; +import org.onap.appc.listener.demo.impl.ListenerImpl; + +@Ignore +public class ListenerImplTest { + + private static final String PROP_FILE = "/org/onap/appc/default.properties"; + + private Listener listener; + private Properties props; + + @Before + public void setup() { + props = new Properties(); + try { + props.load(getClass().getResourceAsStream(PROP_FILE)); + props.setProperty("topic.read", "DCAE-CLOSED-LOOP-EVENTS-DEV1510SIM"); + } catch (Exception e) { + e.printStackTrace(); + fail("Failed to setup test: " + e.getMessage()); + } + listener = new ListenerImpl(new ListenerProperties("appc.ClosedLoop", props)); + } + + @Test + public void testRun() { + try { + Thread t = new Thread(listener); + t.start(); + + Thread.sleep(5000); + + listener.stopNow(); + + System.out.println(listener.getBenchmark()); + + } catch (Exception e) { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + @Test + public void printSampleData() { + try { + props.setProperty("threads.queuesize.min", "1"); + props.setProperty("threads.queuesize.max", "1"); + props.setProperty("threads.poolsize.min", "1"); + props.setProperty("threads.poolsize.max", "1"); + + Thread t = new Thread(listener); + t.start(); + + Thread.sleep(2000); + + listener.stop(); + + System.out.println(listener.getBenchmark()); + + } catch (Exception e) { + e.printStackTrace(); + fail(e.getMessage()); + } + } +} diff --git a/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/impl/WorkerImplTest.java b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/impl/WorkerImplTest.java new file mode 100644 index 000000000..e6d08fba7 --- /dev/null +++ b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/impl/WorkerImplTest.java @@ -0,0 +1,78 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2018 Nokia Solutions and Networks + * ============================================================================= + * 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.appc.listener.LCM.impl; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.onap.appc.listener.TestUtil.JSON_OUTPUT_BODY_STR; +import static org.onap.appc.listener.TestUtil.buildDmaapMessage; + +import com.fasterxml.jackson.databind.JsonNode; +import org.junit.Test; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.listener.EventHandler; +import org.onap.appc.listener.LCM.operation.ProviderOperations; +import org.onap.appc.listener.util.Mapper; + +public class WorkerImplTest { + + private EventHandler mockEventHandler = mock(EventHandler.class); + private ProviderOperations mockProviderOperations = mock(ProviderOperations.class); + + + @Test(expected = IllegalStateException.class) + public void should_throw_when_one_of_worker_fields_is_null() { + + WorkerImpl worker = new WorkerImpl(null, mockEventHandler, mockProviderOperations); + worker.run(); + } + + @Test + public void should_post_error_message_to_dmaap_on_exception() throws APPCException { + + when(mockProviderOperations.topologyDG(anyString(), any(JsonNode.class))) + .thenThrow(new RuntimeException("test exception")); + + WorkerImpl worker = new WorkerImpl(buildDmaapMessage(), mockEventHandler, mockProviderOperations); + worker.run(); + + verify(mockEventHandler).postStatus(anyString(), anyString()); + } + + + @Test + public void should_post_message_to_dmaap_on_successful_run() throws APPCException { + + JsonNode testOutputJsonNode = Mapper.toJsonNodeFromJsonString(JSON_OUTPUT_BODY_STR); + when(mockProviderOperations.topologyDG(anyString(), any(JsonNode.class))) + .thenReturn(testOutputJsonNode); + + WorkerImpl worker = new WorkerImpl(buildDmaapMessage(), mockEventHandler, mockProviderOperations); + worker.run(); + + verify(mockEventHandler).postStatus(anyString(), anyString()); + } +} diff --git a/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/model/ActionIdentifiersTest.java b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/model/ActionIdentifiersTest.java new file mode 100644 index 000000000..4c826b2d2 --- /dev/null +++ b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/model/ActionIdentifiersTest.java @@ -0,0 +1,70 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2018 Nokia Solutions and Networks + * ============================================================================= + * 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.appc.listener.LCM.model; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; + +public class ActionIdentifiersTest { + + private ActionIdentifiers actionIdentifiers; + + + @Before + public void setup(){ + actionIdentifiers = new ActionIdentifiers(); + } + + @Test + public void should_set_properties(){ + + actionIdentifiers.setServiceInstanceId("test-instance-id"); + actionIdentifiers.setVnfID("test-vnf-id"); + actionIdentifiers.setVnfcName("test-name"); + actionIdentifiers.setVserverId("test-vserver-id"); + + + assertEquals("test-instance-id", actionIdentifiers.getServiceInstanceId()); + assertEquals("test-vnf-id", actionIdentifiers.getVnfID()); + assertEquals("test-name", actionIdentifiers.getVnfcName()); + assertEquals("test-vserver-id", actionIdentifiers.getVserverId()); + } + + @Test + public void should_initialize_parameters_from_constructor(){ + + actionIdentifiers.setServiceInstanceId("test-instance-id"); + actionIdentifiers.setVnfID("test-vnf-id"); + actionIdentifiers.setVnfcName("test-name"); + actionIdentifiers.setVserverId("test-vserver-id"); + + ActionIdentifiers testObject = new ActionIdentifiers(actionIdentifiers); + + assertEquals("test-instance-id", testObject.getServiceInstanceId()); + assertEquals("test-vnf-id", testObject.getVnfID()); + assertEquals("test-name", testObject.getVnfcName()); + assertEquals("test-vserver-id", testObject.getVserverId()); + } +} diff --git a/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/model/CommonHeaderTest.java b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/model/CommonHeaderTest.java new file mode 100644 index 000000000..7e834b28e --- /dev/null +++ b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/model/CommonHeaderTest.java @@ -0,0 +1,91 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2018 Nokia Solutions and Networks + * ============================================================================= + * 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.appc.listener.LCM.model; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +import java.util.HashMap; +import java.util.Map; +import org.junit.Before; +import org.junit.Test; + +public class CommonHeaderTest { + + private CommonHeader commonHeader; + + @Before + public void setup() { + commonHeader = new CommonHeader(); + } + + @Test + public void should_set_properties() { + + commonHeader.setTimeStamp("test-timestamp"); + commonHeader.setApiVer("test-api-version"); + commonHeader.setOriginatorId("test-originator-id"); + commonHeader.setRequestID("test-request-id"); + commonHeader.setSubRequestId("test-subrequest-id"); + + Map<String, String> flags = new HashMap<>(); + flags.put("key1", "flag1"); + flags.put("key2", "flag2"); + flags.put("key3", "flag3"); + + commonHeader.setFlags(flags); + + assertEquals("test-timestamp", commonHeader.getTimeStamp()); + assertEquals("test-api-version", commonHeader.getApiVer()); + assertEquals("test-originator-id", commonHeader.getOriginatorId()); + assertEquals("test-request-id", commonHeader.getRequestID()); + assertEquals("test-subrequest-id", commonHeader.getSubRequestId()); + assertEquals(flags, commonHeader.getFlags()); + } + + @Test + public void should_initialize_parameters_from_constructor() { + + commonHeader.setTimeStamp("test-timestamp"); + commonHeader.setApiVer("test-api-version"); + commonHeader.setOriginatorId("test-originator-id"); + commonHeader.setRequestID("test-request-id"); + commonHeader.setSubRequestId("test-subrequest-id"); + + Map<String, String> flags = new HashMap<>(); + flags.put("key1", "flag1"); + flags.put("key2", "flag2"); + flags.put("key3", "flag3"); + + commonHeader.setFlags(flags); + + CommonHeader testObject = new CommonHeader(commonHeader); + + assertNotEquals(commonHeader.getTimeStamp(), testObject.getTimeStamp()); + assertEquals(commonHeader.getApiVer(), testObject.getApiVer()); + assertEquals(commonHeader.getOriginatorId(), testObject.getOriginatorId()); + assertEquals(commonHeader.getRequestID(), testObject.getRequestID()); + assertEquals(commonHeader.getSubRequestId(), testObject.getSubRequestId()); + assertEquals(commonHeader.getFlags(), testObject.getFlags()); + } +} diff --git a/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/model/DmaapIncomingMessageTest.java b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/model/DmaapIncomingMessageTest.java new file mode 100644 index 000000000..40b88e5df --- /dev/null +++ b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/model/DmaapIncomingMessageTest.java @@ -0,0 +1,70 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2018 Nokia Solutions and Networks + * ============================================================================= + * 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.appc.listener.LCM.model; + +import static org.junit.Assert.assertEquals; +import static org.onap.appc.listener.TestUtil.JSON_INPUT_BODY_STR; + +import com.fasterxml.jackson.databind.JsonNode; +import org.junit.Before; +import org.junit.Test; +import org.onap.appc.listener.util.Mapper; + +public class DmaapIncomingMessageTest { + + private DmaapIncomingMessage dmaapIncomingMessage; + + @Before + public void setup() { + dmaapIncomingMessage = new DmaapIncomingMessage(); + } + + @Test + public void should_set_default_cambria_partition_when_initialized() { + + assertEquals("APP-C", dmaapIncomingMessage.getCambriaPartition()); + } + + @Test + public void toString_should_return_valid_string_representation() { + JsonNode jsonNode = Mapper.toJsonNodeFromJsonString(JSON_INPUT_BODY_STR); + + dmaapIncomingMessage.setVersion("test-version"); + dmaapIncomingMessage.setType("test-type"); + dmaapIncomingMessage.setCorrelationID("test-correlation-id"); + dmaapIncomingMessage.setCambriaPartition("test-cambria-partition"); + dmaapIncomingMessage.setRpcName("test-rpc-name"); + dmaapIncomingMessage.setBody(jsonNode); + + assertEquals("DmaapIncomingMessage{DmaapMessage{" + + "version='" + dmaapIncomingMessage.getVersion() + '\'' + + ", type='" + dmaapIncomingMessage.getType() + '\'' + + ", correlationId='" + dmaapIncomingMessage.getCorrelationID() + '\'' + + ", cambriaPartition='" + dmaapIncomingMessage.getCambriaPartition() + '\'' + + ", rpcName='" + dmaapIncomingMessage.getRpcName() + '\'' + + ", body=" + dmaapIncomingMessage.getBody() + + "}}", dmaapIncomingMessage.toString()); + } + + +} diff --git a/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/model/DmaapMessageTest.java b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/model/DmaapMessageTest.java new file mode 100644 index 000000000..0c204df88 --- /dev/null +++ b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/model/DmaapMessageTest.java @@ -0,0 +1,83 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2018 Nokia Solutions and Networks + * ============================================================================= + * 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.appc.listener.LCM.model; + +import static org.junit.Assert.assertEquals; +import static org.onap.appc.listener.TestUtil.JSON_INPUT_BODY_STR; + +import com.fasterxml.jackson.databind.JsonNode; +import org.junit.Before; +import org.junit.Test; +import org.onap.appc.listener.util.Mapper; + +public class DmaapMessageTest { + + private DmaapMessage dmaapMessage; + + @Before + public void setup() { + dmaapMessage = new DmaapMessage(); + } + + @Test + public void should_set_properties() { + + JsonNode jsonNode = Mapper.toJsonNodeFromJsonString(JSON_INPUT_BODY_STR); + + dmaapMessage.setVersion("test-version"); + dmaapMessage.setType("test-type"); + dmaapMessage.setCorrelationID("test-correlation-id"); + dmaapMessage.setCambriaPartition("test-cambria-partition"); + dmaapMessage.setRpcName("test-rpc-name"); + dmaapMessage.setBody(jsonNode); + + assertEquals("test-version", dmaapMessage.getVersion()); + assertEquals("test-type", dmaapMessage.getType()); + assertEquals("test-correlation-id", dmaapMessage.getCorrelationID()); + assertEquals("test-cambria-partition", dmaapMessage.getCambriaPartition()); + assertEquals("test-rpc-name", dmaapMessage.getRpcName()); + assertEquals(jsonNode, dmaapMessage.getBody()); + } + + @Test + public void toString_should_return_valid_string_representation() { + JsonNode jsonNode = Mapper.toJsonNodeFromJsonString(JSON_INPUT_BODY_STR); + + dmaapMessage.setVersion("test-version"); + dmaapMessage.setType("test-type"); + dmaapMessage.setCorrelationID("test-correlation-id"); + dmaapMessage.setCambriaPartition("test-cambria-partition"); + dmaapMessage.setRpcName("test-rpc-name"); + dmaapMessage.setBody(jsonNode); + + assertEquals("DmaapMessage{" + + "version='" + dmaapMessage.getVersion() + '\'' + + ", type='" + dmaapMessage.getType() + '\'' + + ", correlationId='" + dmaapMessage.getCorrelationID() + '\'' + + ", cambriaPartition='" + dmaapMessage.getCambriaPartition() + '\'' + + ", rpcName='" + dmaapMessage.getRpcName() + '\'' + + ", body=" + dmaapMessage.getBody() + + '}', dmaapMessage.toString()); + } +} + diff --git a/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/model/DmaapOutgoingMessageTest.java b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/model/DmaapOutgoingMessageTest.java new file mode 100644 index 000000000..d3f72ee50 --- /dev/null +++ b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/model/DmaapOutgoingMessageTest.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2018 Nokia Solutions and Networks + * ============================================================================= + * 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.appc.listener.LCM.model; + +import static org.junit.Assert.assertEquals; +import static org.onap.appc.listener.TestUtil.JSON_INPUT_BODY_STR; + +import com.fasterxml.jackson.databind.JsonNode; +import org.junit.Before; +import org.junit.Test; +import org.onap.appc.listener.util.Mapper; + +public class DmaapOutgoingMessageTest { + + private DmaapOutgoingMessage dmaapOutgoingMessage; + + @Before + public void setup() { + dmaapOutgoingMessage = new DmaapOutgoingMessage(); + } + + @Test + public void should_set_default_cambria_partition_when_initialized() { + + assertEquals("MSO", dmaapOutgoingMessage.getCambriaPartition()); + } + + @Test + public void toString_should_return_valid_string_representation() { + JsonNode jsonNode = Mapper.toJsonNodeFromJsonString(JSON_INPUT_BODY_STR); + + dmaapOutgoingMessage.setVersion("test-version"); + dmaapOutgoingMessage.setType("test-type"); + dmaapOutgoingMessage.setCorrelationID("test-correlation-id"); + dmaapOutgoingMessage.setCambriaPartition("test-cambria-partition"); + dmaapOutgoingMessage.setRpcName("test-rpc-name"); + dmaapOutgoingMessage.setBody(jsonNode); + + assertEquals("DmaapOutgoingMessage{DmaapMessage{" + + "version='" + dmaapOutgoingMessage.getVersion() + '\'' + + ", type='" + dmaapOutgoingMessage.getType() + '\'' + + ", correlationId='" + dmaapOutgoingMessage.getCorrelationID() + '\'' + + ", cambriaPartition='" + dmaapOutgoingMessage.getCambriaPartition() + '\'' + + ", rpcName='" + dmaapOutgoingMessage.getRpcName() + '\'' + + ", body=" + dmaapOutgoingMessage.getBody() + + "}}", dmaapOutgoingMessage.toString()); + } +} diff --git a/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/model/InputBodyTest.java b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/model/InputBodyTest.java new file mode 100644 index 000000000..21a95955c --- /dev/null +++ b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/model/InputBodyTest.java @@ -0,0 +1,78 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2018 Nokia Solutions and Networks + * ============================================================================= + * Modifications Copyright (C) 2019 IBM. + * ============================================================================= + * 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.appc.listener.LCM.model; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.onap.appc.listener.TestUtil.buildActionIdentifiers; +import static org.onap.appc.listener.TestUtil.buildCommonHeader; + +import org.junit.Before; +import org.junit.Test; + +public class InputBodyTest { + + private InputBody inputBody; + + @Before + public void setup() { + inputBody = new InputBody(); + } + + @Test + public void should_set_properties() { + + CommonHeader testCommonHeader = buildCommonHeader(); + ActionIdentifiers testActionIdentifiers = buildActionIdentifiers(); + + inputBody.setCommonHeader(testCommonHeader); + inputBody.setActionIdentifiers(testActionIdentifiers); + inputBody.setAction("test-action"); + inputBody.setPayload("{\"payload\": \"value\""); + + assertEquals(testCommonHeader, inputBody.getCommonHeader()); + assertEquals(testActionIdentifiers, inputBody.getActionIdentifiers()); + assertEquals("test-action", inputBody.getAction()); + assertEquals("{\"payload\": \"value\"", inputBody.getPayload()); + } + + @Test + public void should_verify_if_is_valid() { + + assertFalse(inputBody.isValid()); + inputBody.setCommonHeader(buildCommonHeader()); + assertTrue(inputBody.isValid()); + } + + @Test + public void testPayLoadAsString() + { + inputBody.setPayloadAsString("payload"); + assertEquals("payload", inputBody.getPayload()); + } + + +} diff --git a/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/model/OutputBodyTest.java b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/model/OutputBodyTest.java new file mode 100644 index 000000000..27913284b --- /dev/null +++ b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/model/OutputBodyTest.java @@ -0,0 +1,95 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2018 Nokia Solutions and Networks + * ============================================================================= + * 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.appc.listener.LCM.model; + +import static junit.framework.TestCase.assertNotNull; +import static org.junit.Assert.assertEquals; +import static org.onap.appc.listener.TestUtil.buildCommonHeader; + +import java.util.HashMap; +import java.util.Map; +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Test; + +public class OutputBodyTest { + + private OutputBody outputBody; + + @Before + public void setup() { + outputBody = new OutputBody(); + } + + @Test + public void should_set_properties() { + + CommonHeader testCommonHeader = buildCommonHeader(); + ResponseStatus testResponseStatus = new ResponseStatus(200, "OK"); + + outputBody.setHeader(testCommonHeader); + outputBody.setStatus(testResponseStatus); + outputBody.setLocked("test-locked"); + outputBody.setPayload("{\"payload\": \"value\""); + + assertEquals(testCommonHeader, outputBody.getHeader()); + assertEquals(testResponseStatus, outputBody.getStatus()); + assertEquals("test-locked", outputBody.getLocked()); + assertEquals("{\"payload\": \"value\"", outputBody.getPayload()); + } + + + @Test + public void should_inherit_input_body_header_when_initialized_from_constructor() { + + InputBody testInputBody = new InputBody(); + CommonHeader testCommonHeader = buildCommonHeader(); + testInputBody.setCommonHeader(testCommonHeader); + + outputBody = new OutputBody(testInputBody); + + assertNotNull(outputBody.getHeader()); + assertEquals(testCommonHeader.getFlags(), outputBody.getHeader().getFlags()); + assertEquals(testCommonHeader.getSubRequestId(), outputBody.getHeader().getSubRequestId()); + assertEquals(testCommonHeader.getRequestID(), outputBody.getHeader().getRequestID()); + assertEquals(testCommonHeader.getOriginatorId(), outputBody.getHeader().getOriginatorId()); + assertEquals(testCommonHeader.getApiVer(), outputBody.getHeader().getApiVer()); + } + + @Test + public void toResponse_should_convert_to_json_object() { + CommonHeader testCommonHeader = buildCommonHeader(); + ResponseStatus testResponseStatus = new ResponseStatus(200, "OK"); + + outputBody.setHeader(testCommonHeader); + outputBody.setStatus(testResponseStatus); + outputBody.setLocked("test-locked"); + outputBody.setPayload("{\"payload\": \"value\""); + + JSONObject response = outputBody.toResponse(); + assertNotNull(response); + + assertEquals("test-locked", response.get("locked")); + assertEquals("{\"payload\": \"value\"", response.get("payload")); + } +} diff --git a/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/model/ResponseStatusTest.java b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/model/ResponseStatusTest.java new file mode 100644 index 000000000..1283643bf --- /dev/null +++ b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/model/ResponseStatusTest.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2018 Nokia Solutions and Networks + * ============================================================================= + * 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.appc.listener.LCM.model; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; + +public class ResponseStatusTest { + + private ResponseStatus responseStatus; + + @Before + public void setup() { + responseStatus = new ResponseStatus(); + } + + @Test + public void should_set_properties() { + + responseStatus.setCode(200); + responseStatus.setValue("OK"); + + assertEquals(Integer.valueOf(200), responseStatus.getCode()); + assertEquals("OK", responseStatus.getValue()); + } + + @Test + public void should_initialize_parameters_from_constructor() { + responseStatus = new ResponseStatus(200, "OK"); + + assertEquals(Integer.valueOf(200), responseStatus.getCode()); + assertEquals("OK", responseStatus.getValue()); + } +} diff --git a/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/operation/GenericProviderOperationsRequestFormatterTest.java b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/operation/GenericProviderOperationsRequestFormatterTest.java new file mode 100644 index 000000000..a6d1bb9d1 --- /dev/null +++ b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/operation/GenericProviderOperationsRequestFormatterTest.java @@ -0,0 +1,93 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2018 Nokia Solutions and Networks + * ============================================================================= + * 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.appc.listener.LCM.operation; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.onap.appc.listener.TestUtil.JSON_OUTPUT_BODY_STR; + +import com.fasterxml.jackson.databind.JsonNode; +import java.net.MalformedURLException; +import java.net.URL; +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.listener.LCM.model.InputBody; +import org.onap.appc.listener.LCM.model.ResponseStatus; +import org.onap.appc.listener.util.Mapper; + +public class GenericProviderOperationsRequestFormatterTest { + + private static final String INVALID_JSON_OUTPUT_BODY_STR = + "{\"output\":{\"common-header\":{\"timestamp\":\"2016-08-03T08:50:18.97Z\"," + + "\"api-ver\":\"1\",\"flags\":{\"force\":\"TRUE\",\"ttl\":\"9900\"},\"sub-request-id\":\"1\"," + + "\"request-id\":\"123\",\"originator-id\":\"1\"}}}"; + + private GenericProviderOperationRequestFormatter requestFormatter; + + + @Before + public void setup() { + requestFormatter = new GenericProviderOperationRequestFormatter(); + } + + @Test + public void should_build_path() throws MalformedURLException { + String result = requestFormatter.buildPath(new URL("http://127.0.0.1/abc/def"), "test"); + assertEquals("/abc/def:test", result); + } + + @Test + public void should_build_request_json() { + InputBody inputBody = new InputBody(); + inputBody.setPayload("\"key1\": \"value1\", \"key2\": \"value2\""); + + assertEquals("{\"input\": {\"payload\":\"\\\"key1\\\": \\\"value1\\\", \\\"key2\\\": \\\"value2\\\"\"}}", + requestFormatter.buildRequest(inputBody)); + } + + @Test(expected = APPCException.class) + public void should_throw_when_invalid_json() throws APPCException { + + JsonNode jsonNode = Mapper.toJsonNodeFromJsonString(INVALID_JSON_OUTPUT_BODY_STR); + requestFormatter.getResponseStatus(jsonNode); + } + + @Test + public void should_extract_response_status() throws APPCException { + + JsonNode jsonNode = Mapper.toJsonNodeFromJsonString(JSON_OUTPUT_BODY_STR); + ResponseStatus status = requestFormatter.getResponseStatus(jsonNode); + + assertEquals("test message", status.getValue()); + assertEquals(Integer.valueOf(200), status.getCode()); + } + + @Test + public void should_return_extract_locked_field() throws APPCException { + + assertNull(requestFormatter.getLocked(new JSONObject(INVALID_JSON_OUTPUT_BODY_STR))); + assertEquals("test-locked", requestFormatter.getLocked(new JSONObject(JSON_OUTPUT_BODY_STR))); + } +} diff --git a/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/operation/ProviderOperationsTest.java b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/operation/ProviderOperationsTest.java new file mode 100644 index 000000000..fc6c14d16 --- /dev/null +++ b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM/operation/ProviderOperationsTest.java @@ -0,0 +1,136 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2018 Nokia Solutions and Networks + * ============================================================================= + * 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.appc.listener.LCM.operation; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import org.apache.commons.codec.binary.Base64; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.Socket; +import java.net.SocketException; +import java.security.KeyManagementException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.UnrecoverableKeyException; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.StatusLine; +import org.apache.http.client.HttpClient; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.listener.LCM.operation.ProviderOperations.MySSLSocketFactory; + +public class ProviderOperationsTest { + + private ProviderOperations providerOperations; + private MySSLSocketFactory socketFactory; + + @Mock + private KeyStore mockKeyStore; + + + @Before + public void setup() + throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException { + + providerOperations = + new ProviderOperations("http://127.0.0.1", "test_user", "test_password"); + socketFactory = new MySSLSocketFactory(mockKeyStore); + } + + @Test + public void setAuthentication_should_return_null_given_null_arguments() { + String newAuthentication = providerOperations.setAuthentication(null, null); + assertNull(newAuthentication); + } + + @Test + public void should_set_properties() { + providerOperations.setUrl("hp://123.1.2.3"); + assertEquals("http://127.0.0.1", providerOperations.getUrl()); + providerOperations.setUrl("http://123.1.2.3"); + assertEquals("http://123.1.2.3", providerOperations.getUrl()); + + String newAuthentication = providerOperations.setAuthentication("new_user", "new_password"); + String authStr = "new_user:new_password"; + assertEquals(new String(Base64.encodeBase64(authStr.getBytes())), newAuthentication); + } + + @Test + public void isSucceeded_should_resolve_status_codes() { + + assertFalse(ProviderOperations.isSucceeded(null)); + assertFalse(ProviderOperations.isSucceeded(200)); + assertTrue(ProviderOperations.isSucceeded(100)); + assertTrue(ProviderOperations.isSucceeded(400)); + } + + @Test(expected = APPCException.class) + public void topologyDG_should_throw_given_null_message() throws APPCException { + + providerOperations.topologyDG("test-rpc-name", null); + } + + @Test(expected = SocketException.class) + public void sslSocketFactory_should_throw_when_socket_not_connected() throws IOException { + Socket socket = socketFactory.createSocket(); + assertNotNull(socket); + + socketFactory.createSocket(socket, "127.0.0.1", 123, true); + } + + //TODO write some test cases for topologyDG method + @Test + public void testBuildPostRequest() throws JsonProcessingException, IOException, APPCException { + String jsonString = "{\"output\":{\"status\":{\"code\":\"200\",\"message\":\"TEST_MESSAGE\"}}}"; + providerOperations = Mockito.spy( + new ProviderOperations("http://127.0.0.1", "test_user", "test_password")); + HttpClient httpClient = Mockito.mock(HttpClient.class); + HttpResponse httpResponse = Mockito.mock(HttpResponse.class); + StatusLine statusLine = Mockito.mock(StatusLine.class); + Mockito.when(statusLine.getStatusCode()).thenReturn(200); + Mockito.when(httpResponse.getStatusLine()).thenReturn(statusLine); + HttpEntity httpEntity = Mockito.mock(HttpEntity.class); + InputStream inputStream = new ByteArrayInputStream(jsonString.getBytes()); + Mockito.when(httpEntity.getContent()).thenReturn(inputStream); + Mockito.when(httpResponse.getEntity()).thenReturn(httpEntity); + Mockito.when(httpClient.execute(Mockito.any())).thenReturn(httpResponse); + Mockito.when(providerOperations.getHttpClient()).thenReturn(httpClient); + ObjectMapper mapper = new ObjectMapper(); + JsonNode jsonNode = mapper.readTree(jsonString); + assertEquals(ObjectNode.class, providerOperations.topologyDG(null, jsonNode).getClass()); + } +} diff --git a/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM1607/model/TestJsonGenericMessages.java b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM1607/model/TestJsonGenericMessages.java new file mode 100644 index 000000000..b17789115 --- /dev/null +++ b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/LCM1607/model/TestJsonGenericMessages.java @@ -0,0 +1,101 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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.appc.listener.LCM1607.model; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Assert; +import org.junit.Test; +import org.onap.appc.listener.util.Mapper; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + + +public class TestJsonGenericMessages {/* + + @Test + public void serializeIncomingMessage() { + + final String expectedJson = "{\"CommonHeader\":{\"TimeStamp\":\"2016-05-02 19:50:37.09\",\"TransactionID\":\"1\",\"APIver\":\"1.01\",\"RequestTrack\":[\"1\",\"4\",\"12\",\"3\"],\"Flags\":null,\"SubrequestID\":null,\"OriginatorID\":\"2\"},\"Payload\":\"{ \\\"command\\\": \\\"start\\\", \\\"target-id\\\": \\\"111\\\", \\\"flag10\\\": {\\\"object-1\\\": {\\\"key-1\\\": \\\"key\\\", \\\"value-1\\\": \\\"value\\\" }} }\",\"Action\":\"CONFIGURE\",\"ObjectID\":\"200\",\"TargetID\":\"100\"}"; + InputBody msg = createIncomingMessage(); + + String json = Mapper.toJsonObject(msg).toString(); + //System.out.println(json); + Assert.assertEquals(expectedJson, json); + } + + @Test + public void deserializeIncomingMessage() throws IOException { + final String originalJson = "{\"CommonHeader\":{\"TimeStamp\":\"2016-05-02 19:50:37.09\",\"TransactionID\":\"1\",\"Flags\":{\"FORCE\":\"Y\",\"TTL\":\"12\"},\"SubrequestID\":\"2345\",\"OriginatorID\":\"2\",\"APIver\":\"1.01\"}, \"Payload\": \" \\\"Graceful\\\" : \\\"Yes\\\" \",\"Action\":\"CONFIGURE\",\"ObjectID\":\"200\",\"TargetID\":\"100\"}"; + + ObjectMapper mapper = new ObjectMapper(); + InputBody msg = mapper.readValue(originalJson, InputBody.class); + + Assert.assertNotNull(msg); + Assert.assertEquals("2016-05-02 19:50:37.09", msg.getCommonHeader().getTimeStamp()); + Assert.assertEquals("1", msg.getCommonHeader().getRequestID()); + Assert.assertEquals("1.01", msg.getCommonHeader().getApiVer()); + Assert.assertEquals("200", msg.getObjectId()); + Assert.assertEquals("100", msg.getTargetId()); + Assert.assertEquals(" \"Graceful\" : \"Yes\" ", msg.getPayload()); + Assert.assertEquals("CONFIGURE", msg.getAction()); + + } + + @Test + public void serializeResponseMessage() { + InputBody imsg = createIncomingMessage(); + OutputBody omsg = new OutputBody(imsg); + omsg.setStatus(new ResponseStatus("200", "OK")); + + String json = Mapper.toJsonObject(omsg).toString(); + System.out.println(json); + //Assert.assertEquals(expectedJson, json); + Assert.assertNotEquals("", json); + + } + + private InputBody createIncomingMessage() { + InputBody msg = new InputBody(); + CommonHeader rh = new CommonHeader(); + rh.setTimeStamp("2016-05-02 19:50:37.09"); + rh.setApiVer("1.01"); + rh.setRequestID("1"); + rh.setOriginatorId("2"); + + + Map<String, String> flags = new HashMap<>(); + flags.put("FORCE", "Y"); + flags.put("TTL", "12"); + + msg.setCommonHeader(rh); + msg.setAction("CONFIGURE"); + msg.setTargetId("100"); + msg.setObjectId("200"); + msg.setPayloadAsString("{ \"command\": \"start\", \"target-id\": \"111\", \"flag10\": {\"object-1\": {\"key-1\": \"key\", \"value-1\": \"value\" }} }"); + return msg; + } +*/ +} diff --git a/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/ListenerPropertiesTest.java b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/ListenerPropertiesTest.java new file mode 100644 index 000000000..c83555c50 --- /dev/null +++ b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/ListenerPropertiesTest.java @@ -0,0 +1,156 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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.appc.listener; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.Properties; + +import org.junit.Before; +import org.junit.Test; +import org.onap.appc.adapter.factory.MessageService; +import org.onap.appc.listener.AbstractListener; +import org.onap.appc.listener.ListenerProperties; +import org.onap.appc.listener.ListenerProperties.KEYS; + +public class ListenerPropertiesTest { + + private Properties good, bad, both; + private String prefix; + + private ListenerProperties props; + + @Before + public void setup() { + prefix = "test"; + good = new Properties(); + bad = new Properties(); + both = new Properties(); + + good.setProperty(String.format("%s.%s", prefix, "a"), "1"); + good.setProperty(String.format("%s.%s", prefix, "a.b"), "2"); + good.setProperty(String.format("%s.%s", prefix, "a.b.c"), "3"); + + bad.setProperty(prefix, "NA"); + bad.setProperty(prefix + ".", "NA"); + bad.setProperty(String.format("%s.%s", prefix + "x", "bad"), "NA"); + bad.setProperty(String.format("%s.%s", "x" + prefix, "bad"), "NA"); + + for (String key : good.stringPropertyNames()) { + both.put(key, good.getProperty(key)); + } + for (String key : bad.stringPropertyNames()) { + both.put(key, bad.getProperty(key)); + } + + props = new ListenerProperties(prefix, both); + } + + @Test + public void testConstructor() { + props = new ListenerProperties(prefix, good); + assertEquals(prefix, props.getPrefix()); + assertEquals(good.size(), props.getProperties().size()); + + props = new ListenerProperties(prefix, bad); + assertEquals(prefix, props.getPrefix()); + assertTrue(props.getProperties().isEmpty()); + + props = new ListenerProperties(prefix, both); + assertEquals(prefix, props.getPrefix()); + assertEquals(good.size(), props.getProperties().size()); + + for (Object val : props.getProperties().values()) { + assertFalse("NA".equals(val.toString())); + } + + assertTrue(props.toString().contains(prefix)); + } + + @Test + public void testGetClass() { + assertNull(props.getListenerClass()); + props.setListenerClass(AbstractListener.class); + assertNotNull(props.getListenerClass()); + assertEquals(AbstractListener.class, props.getListenerClass()); + } + + @Test + public void testMessageServices() { + // Hardcode count so tests must be updated when values are added + assertEquals(1, MessageService.values().length); + + // Bad Input + MessageService def = MessageService.DMaaP; + assertEquals(def, MessageService.parse(null)); + assertEquals(def, MessageService.parse("")); + assertEquals(def, MessageService.parse("NotDMaaP")); + + // DMaaP case sensitivity + assertEquals(MessageService.DMaaP, MessageService.parse("dmaap")); + assertEquals(MessageService.DMaaP, MessageService.parse("DMAAP")); + assertEquals(MessageService.DMaaP, MessageService.parse("DMaaP")); + } + + @Test + public void testKeys() { + // Hardcode count so tests must be updated when values are added + assertEquals(19, ListenerProperties.KEYS.values().length); + + Properties tmp = new Properties(); + try { + tmp.load(getClass().getResourceAsStream("/org/onap/appc/default.properties")); + } catch (Exception e) { + fail("Could not load properties to test"); + } + String realPrefix = tmp.getProperty("test.prefix"); + assertNotNull(realPrefix); + props = new ListenerProperties(realPrefix, tmp); + + for (KEYS key : ListenerProperties.KEYS.values()) { + assertNotNull(key.getFullProp(realPrefix)); + assertNotNull(props.getProperty(key)); + assertNotNull(props.getProperty(key.getPropertySuffix())); + } + } + + @Test + public void testDisabled() throws Exception { + assertFalse(props.isDisabled()); + props.getProperties().put(KEYS.DISABLED.getPropertySuffix(), "TRUE"); + assertTrue(props.isDisabled()); + props.getProperties().put(KEYS.DISABLED.getPropertySuffix(), "N/A"); + assertFalse(props.isDisabled()); + props.getProperties().put(KEYS.DISABLED.getPropertySuffix(), "fAlse"); + assertFalse(props.isDisabled()); + props.getProperties().remove(KEYS.DISABLED.getPropertySuffix()); + assertFalse(props.isDisabled()); + } + +} diff --git a/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/TestUtil.java b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/TestUtil.java new file mode 100644 index 000000000..f28ad83b5 --- /dev/null +++ b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/TestUtil.java @@ -0,0 +1,82 @@ +package org.onap.appc.listener; + +import com.fasterxml.jackson.databind.JsonNode; +import java.util.HashMap; +import java.util.Map; +import org.onap.appc.listener.LCM.model.ActionIdentifiers; +import org.onap.appc.listener.LCM.model.CommonHeader; +import org.onap.appc.listener.LCM.model.DmaapIncomingMessage; +import org.onap.appc.listener.LCM.model.DmaapMessage; +import org.onap.appc.listener.LCM.model.DmaapOutgoingMessage; +import org.onap.appc.listener.util.Mapper; + +public class TestUtil { + + public static final String JSON_INPUT_BODY_STR = + "{\"input\":{ \"common-header\": { \"timestamp\": \"2016-08-03T08:50:18.97Z\", " + + "\"api-ver\": \"1\", \"originator-id\": \"1\", \"request-id\": \"123\", \"sub-request-id\": \"1\", " + + "\"flags\": { \"force\":\"TRUE\", \"ttl\":\"9900\" } }, \"action\": \"Stop\", " + + "\"action-identifiers\": { \"vnf-id\": \"TEST\" } }}"; + + public static final String JSON_OUTPUT_BODY_STR = + "{\"output\":{\"common-header\":{\"timestamp\":\"2016-08-03T08:50:18.97Z\"," + + "\"api-ver\":\"1\",\"flags\":{\"force\":\"TRUE\",\"ttl\":\"9900\"},\"sub-request-id\":\"1\"," + + "\"request-id\":\"123\",\"originator-id\":\"1\"},\"locked\": \"test-locked\", " + + "\"status\":{\"message\":\"test message\",\"code\":200}}}"; + + public static DmaapMessage buildDmaapMessage() { + + DmaapMessage dmaapMessage = new DmaapMessage(); + dmaapMessage.setRpcName("test"); + JsonNode jsonNode = Mapper.toJsonNodeFromJsonString(JSON_INPUT_BODY_STR); + dmaapMessage.setBody(jsonNode); + return dmaapMessage; + } + + public static DmaapIncomingMessage buildDmaapIncomingMessage() { + DmaapIncomingMessage dmaapIncomingMessage = new DmaapIncomingMessage(); + dmaapIncomingMessage.setRpcName("test"); + JsonNode jsonNode = Mapper.toJsonNodeFromJsonString(JSON_INPUT_BODY_STR); + dmaapIncomingMessage.setBody(jsonNode); + return dmaapIncomingMessage; + + } + + public static DmaapOutgoingMessage buildDmaapOutgoingMessage() { + DmaapOutgoingMessage dmaapOutgoingMessage = new DmaapOutgoingMessage(); + dmaapOutgoingMessage.setRpcName("test"); + JsonNode jsonNode = Mapper.toJsonNodeFromJsonString(JSON_OUTPUT_BODY_STR); + dmaapOutgoingMessage.setBody(jsonNode); + return dmaapOutgoingMessage; + + } + + public static CommonHeader buildCommonHeader() { + + CommonHeader commonHeader = new CommonHeader(); + commonHeader.setTimeStamp("test-timestamp"); + commonHeader.setApiVer("test-api-version"); + commonHeader.setOriginatorId("test-originator-id"); + commonHeader.setRequestID("test-request-id"); + commonHeader.setSubRequestId("test-subrequest-id"); + + Map<String, String> flags = new HashMap<>(); + flags.put("key1", "flag1"); + flags.put("key2", "flag2"); + flags.put("key3", "flag3"); + + commonHeader.setFlags(flags); + return commonHeader; + } + + public static ActionIdentifiers buildActionIdentifiers() { + + ActionIdentifiers actionIdentifiers = new ActionIdentifiers(); + actionIdentifiers.setServiceInstanceId("test-instance-id"); + actionIdentifiers.setVnfID("test-vnf-id"); + actionIdentifiers.setVnfcName("test-name"); + actionIdentifiers.setVserverId("test-vserver-id"); + + return actionIdentifiers; + } +} diff --git a/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/demo/impl/TestProviderOperations.java b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/demo/impl/TestProviderOperations.java new file mode 100644 index 000000000..55b0f2cb6 --- /dev/null +++ b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/demo/impl/TestProviderOperations.java @@ -0,0 +1,129 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.demo.impl; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Mockito.when; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.StatusLine; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.HttpClient; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.mockito.internal.util.reflection.Whitebox; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.listener.demo.model.Action; +import org.onap.appc.listener.demo.model.CommonMessage.CommonHeader; +import org.onap.appc.listener.demo.model.CommonMessage.Payload; +import org.onap.appc.listener.demo.model.IncomingMessage; +import org.onap.appc.listener.util.HttpClientUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(HttpClientUtil.class) +public class TestProviderOperations { + + private ProviderOperations providerOperations; + private IncomingMessage message; + private URL url; + private CommonHeader commonHeader; + private Payload payload; + private HttpClient httpClient; + private HttpResponse httpResponse; + private StatusLine statusLine; + private HttpEntity httpEntity; + private InputStream inputStream; + private String reponseMessage; + + @Before + public void setUp() throws Exception { + reponseMessage = "{\"output\":{\"common-response-header\":{\"success\":true,\"reason\":\"\"}}}"; + providerOperations = new ProviderOperations(); + PowerMockito.mockStatic(HttpClientUtil.class); + httpClient = PowerMockito.mock(HttpClient.class); + httpResponse = PowerMockito.mock(HttpResponse.class); + statusLine = PowerMockito.mock(StatusLine.class); + httpEntity = PowerMockito.mock(HttpEntity.class); + inputStream = new ByteArrayInputStream(reponseMessage.getBytes(StandardCharsets.UTF_8)); + message = Mockito.mock(IncomingMessage.class); + url = PowerMockito.mock(URL.class); + commonHeader = Mockito.mock(CommonHeader.class); + payload = Mockito.mock(Payload.class); + when(message.getAction()).thenReturn(Action.Evacuate); + when(message.getHeader()).thenReturn(commonHeader); + when(message.getPayload()).thenReturn(payload); + when(HttpClientUtil.getHttpClient("http")).thenReturn(httpClient); + when(httpClient.execute(anyObject())).thenReturn(httpResponse); + when(httpResponse.getStatusLine()).thenReturn(statusLine); + when(statusLine.getStatusCode()).thenReturn(200); + when(httpResponse.getEntity()).thenReturn(httpEntity); + when(httpEntity.getContent()).thenReturn(inputStream); + Whitebox.setInternalState(url, "protocol", "http"); + Whitebox.setInternalState(providerOperations, "url", url); + } + + @Test + public void testTopologyDG() throws APPCException, ClientProtocolException, IOException { + assertTrue(ProviderOperations.topologyDG(message)); + } + + @Test + public void testTopologyDGWithBaseAuth() + throws APPCException, ClientProtocolException, IOException { + ProviderOperations.setAuthentication("user", "password"); + ProviderOperations.setUrl("http://localhost:8080"); + assertTrue(ProviderOperations.topologyDG(message)); + } + + @Test(expected = APPCException.class) + public void testTopologyDGFail() throws APPCException, ClientProtocolException, IOException { + reponseMessage = + "{\"output\":{\"common-response-header\":{\"success\":false,\"reason\":\"\"}}}"; + inputStream = new ByteArrayInputStream(reponseMessage.getBytes(StandardCharsets.UTF_8)); + when(httpEntity.getContent()).thenReturn(inputStream); + ProviderOperations.topologyDG(message); + } + + @Test(expected = APPCException.class) + public void testTopologyDGInvalidResponse() + throws APPCException, ClientProtocolException, IOException { + reponseMessage = "{\"output\":{\"common-response-header\":{\"succss\":false,\"reason\":\"\"}}}"; + inputStream = new ByteArrayInputStream(reponseMessage.getBytes(StandardCharsets.UTF_8)); + when(httpEntity.getContent()).thenReturn(inputStream); + ProviderOperations.topologyDG(message); + } + + @Test(expected = APPCException.class) + public void testTopologyDGWithInvalidHttp() + throws APPCException, ClientProtocolException, IOException { + when(statusLine.getStatusCode()).thenReturn(500); + ProviderOperations.topologyDG(message); + } +} diff --git a/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/demo/impl/TestWorkerImpl.java b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/demo/impl/TestWorkerImpl.java new file mode 100644 index 000000000..e3f889c5e --- /dev/null +++ b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/demo/impl/TestWorkerImpl.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.appc.listener.demo.impl; + +import static org.mockito.Matchers.anyObject; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.times; + +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.listener.EventHandler; +import org.onap.appc.listener.demo.model.CommonMessage.CommonHeader; +import org.onap.appc.listener.demo.model.IncomingMessage; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(ProviderOperations.class) +public class TestWorkerImpl { + + private WorkerImpl workerImplSpy; + private IncomingMessage message; + private EventHandler dmaap; + + @Before + public void setUp() { + message = Mockito.mock(IncomingMessage.class); + dmaap = Mockito.mock(EventHandler.class); + workerImplSpy = Mockito.spy(new WorkerImpl(message, dmaap)); + } + + @Test + public void testRun() throws APPCException { + CommonHeader commonHeader = Mockito.mock(CommonHeader.class); + when(message.getHeader()).thenReturn(commonHeader); + when(commonHeader.getRequestID()).thenReturn("requestId"); + PowerMockito.mockStatic(ProviderOperations.class); + PowerMockito.when(ProviderOperations.topologyDG(anyObject())).thenReturn(true); + workerImplSpy.run(); + verify(workerImplSpy, times(1)).run(); + } + + @Test + public void testRunElseCase() throws APPCException { + CommonHeader commonHeader = Mockito.mock(CommonHeader.class); + when(message.getHeader()).thenReturn(commonHeader); + when(commonHeader.getRequestID()).thenReturn("requestId"); + when(message.toJson()).thenReturn(new JSONObject()); + PowerMockito.mockStatic(ProviderOperations.class); + PowerMockito.when(ProviderOperations.topologyDG(anyObject())).thenReturn(false); + workerImplSpy.run(); + verify(workerImplSpy, times(1)).run(); + } + + @Test + public void testRunWithException() throws APPCException { + CommonHeader commonHeader = Mockito.mock(CommonHeader.class); + when(message.getHeader()).thenReturn(commonHeader); + when(commonHeader.getRequestID()).thenReturn("requestId"); + workerImplSpy.run(); + verify(workerImplSpy, times(1)).run(); + } +} diff --git a/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/demo/model/OutgoingMessageTest.java b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/demo/model/OutgoingMessageTest.java new file mode 100644 index 000000000..b2838cb77 --- /dev/null +++ b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/demo/model/OutgoingMessageTest.java @@ -0,0 +1,91 @@ +/* + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2019 Ericsson + * ================================================================================ + * 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.appc.listener.demo.model; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import java.io.IOException; +import java.net.InetAddress; +import java.net.UnknownHostException; +import org.apache.commons.io.IOUtils; +import org.hamcrest.CoreMatchers; +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.onap.appc.listener.util.Mapper; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(Mapper.class) +public class OutgoingMessageTest { + + private IncomingMessage incomingMessage; + + @Before + public void setup() throws IOException { + String incomingStr = IOUtils.toString(getClass().getResourceAsStream("/IncomingMessagedemo.txt"), "UTF-8"); + incomingMessage = Mapper.mapOne(incomingStr, IncomingMessage.class); + } + + @Test + public void testOutgoingMessage() throws UnknownHostException { + InetAddress mockInetAddress = Mockito.mock(InetAddress.class); + Mockito.when(mockInetAddress.getCanonicalHostName()).thenReturn("TEST_CANONICAL_HOSTNAME"); + OutgoingMessage outgoingMessage = Mockito.spy(new OutgoingMessage(incomingMessage)); + PowerMockito.when(outgoingMessage.getLocalHost()).thenReturn(mockInetAddress); + outgoingMessage.updateResponseTime(); + assertEquals("appc@TEST_CANONICAL_HOSTNAME", outgoingMessage.generateFrom()); + } + + @Test + public void testOutgoingMessageUnknowHost() throws UnknownHostException { + OutgoingMessage outgoingMessage = Mockito.spy(new OutgoingMessage(incomingMessage)); + PowerMockito.when(outgoingMessage.getLocalHost()).thenThrow(new UnknownHostException()); + assertEquals("appc@UnknownHost", outgoingMessage.generateFrom()); + } + + @Test + public void testJson() { + PowerMockito.mockStatic(Mapper.class); + JSONObject mockObject = Mockito.mock(JSONObject.class); + PowerMockito.when(Mapper.toJsonObject(Mockito.any())).thenReturn(mockObject); + OutgoingMessage outgoingMessage = Mockito.spy(new OutgoingMessage(incomingMessage)); + assertEquals(mockObject, outgoingMessage.toResponse()); + } + + @Test + public void testSetResponse() { + OutgoingMessage outgoingMessage = new OutgoingMessage(incomingMessage); + outgoingMessage.setResponse(null); + assertEquals(new OutgoingMessage.OutStatus().getValue(), outgoingMessage.getStatus().getValue()); + outgoingMessage.setResponse(Status.ACCEPTED); + assertEquals("100", outgoingMessage.getStatus().getCode()); + outgoingMessage.setResponse(Status.FAILURE); + assertEquals("500", outgoingMessage.getStatus().getCode()); + outgoingMessage.setResponse(Status.SUCCESS); + assertEquals("400", outgoingMessage.getStatus().getCode()); + } +} diff --git a/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/demo/model/TestCommonMessage.java b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/demo/model/TestCommonMessage.java new file mode 100644 index 000000000..341492f26 --- /dev/null +++ b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/demo/model/TestCommonMessage.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2019 IBM. + * ================================================================================ + * 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.appc.listener.demo.model; + +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Collection; + +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Test; + +public class TestCommonMessage { + + private CommonMessage commonMessage; + private CommonMessage.Payload payload; + + @Before + public void setUp() { + commonMessage = new CommonMessage(); + payload = new CommonMessage.Payload(); + } + + @Test + public void testToJson() { + assertTrue(commonMessage.toJson() instanceof JSONObject); + } + +} diff --git a/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/demo/model/TestEnums.java b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/demo/model/TestEnums.java new file mode 100644 index 000000000..2dbbdd64d --- /dev/null +++ b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/demo/model/TestEnums.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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.appc.listener.demo.model; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import org.junit.Test; +import org.onap.appc.listener.demo.model.Action; +import org.onap.appc.listener.demo.model.Status; + +public class TestEnums { + + @Test + public void testAction() { + assertEquals(Action.Rebuild, Action.toAction("Rebuild")); + assertEquals(Action.Restart, Action.toAction("restart")); + assertEquals(Action.Migrate, Action.toAction("MIGRATE")); + assertEquals(Action.Evacuate, Action.toAction("Evacuate")); + assertNull(Action.toAction("Unknown")); + assertNull(Action.toAction(null)); + + assertEquals(6, Action.values().length); + } + + @Test + public void testStatus() { + + assertEquals(Status.ACCEPTED, Status.toStatus("accepted")); + assertEquals(Status.SUCCESS, Status.toStatus("SuCcEsS")); + assertEquals(Status.FAILURE, Status.toStatus("Failure")); + assertNull(Status.toStatus("Unknown")); + assertNull(Status.toStatus(null)); + + assertEquals(3, Status.values().length); + + } + +} diff --git a/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/demo/model/TestIncomingMessage.java b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/demo/model/TestIncomingMessage.java new file mode 100644 index 000000000..d8d0986ce --- /dev/null +++ b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/demo/model/TestIncomingMessage.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2019 IBM. + * ================================================================================ + * 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.appc.listener.demo.model; + +import static org.junit.Assert.assertEquals; + +import org.junit.Before; +import org.junit.Test; + +public class TestIncomingMessage { + + private IncomingMessage incomingMessage; + + @Before + public void setUp() { + incomingMessage = new IncomingMessage(); + } + + @Test + public void testToOutgoing() { + String expected = "{\"Status\":{\"Value\":null,\"Code\":null}}"; + assertEquals(expected, incomingMessage.toOutgoing(null)); + expected = "{\"Status\":{\"Value\":\""+Status.ACCEPTED.getValue()+"\",\"Code\":\"100\"}}"; + assertEquals(expected, incomingMessage.toOutgoing(Status.ACCEPTED)); + } + +} diff --git a/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/demo/model/TestMessages.java b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/demo/model/TestMessages.java new file mode 100644 index 000000000..9cce23d95 --- /dev/null +++ b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/demo/model/TestMessages.java @@ -0,0 +1,199 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * Modification Copyright (C) 2018 IBM. + * ================================================================================ + * Modifications Copyright (C) 2019 Ericsson + * ============================================================================= + * 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.appc.listener.demo.model; + + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import java.util.ArrayList; +import java.util.Collection; +import org.apache.commons.io.IOUtils; +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.onap.appc.listener.demo.model.CommonMessage.Streams; +import org.onap.appc.listener.demo.model.IncomingMessage; +import org.onap.appc.listener.demo.model.OutgoingMessage; +import org.onap.appc.listener.demo.model.Status; +import org.onap.appc.listener.util.Mapper; + +public class TestMessages { + private IncomingMessage in; + private OutgoingMessage out; + + private String incomingStr; + private String outgoingStr; + + @Before + public void setup() { + try { + incomingStr = IOUtils.toString(getClass().getResourceAsStream("/IncomingMessagedemo.txt"), "UTF-8"); + outgoingStr = IOUtils.toString(getClass().getResourceAsStream("/OutgoingMessagedemo.txt"), "UTF-8"); + assertNotNull(incomingStr); + assertNotNull(outgoingStr); + + in = Mapper.mapOne(incomingStr, IncomingMessage.class); + + out = Mapper.mapOne(outgoingStr, OutgoingMessage.class); + + assertNotNull(in); + assertNotNull(out); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + // NOTE Test Mapper will be used to test an event from dmaap. + @Test + public void testGetterSetter() { + assertNotNull(in); + assertNotNull(in.getAction()); + assertNotNull(in.getHeader().getApiVer()); + assertNotNull(in.getHeader().getOriginatorId()); + assertNotNull(in.getHeader().getRequestID()); + assertNotNull(in.getHeader().getSubRequestId()); + assertNotNull(in.getHeader().getTimeStamp()); + + assertNotNull(out); + assertNotNull(out.getHeader().getApiVer()); + assertNotNull(out.getHeader().getOriginatorId()); + assertNotNull(out.getHeader().getRequestID()); + assertNotNull(out.getHeader().getSubRequestId()); + assertNotNull(out.getHeader().getTimeStamp()); + assertNotNull(out.getStatus().getCode()); + assertNotNull(out.getStatus().getValue()); + + } + + @Test + public void testGetRequest() + { + String request="testRequest"; + in.setRequest(request); + assertEquals(request, in.getRequest()); + } + + @Test + public void testIsValid() + { + assertEquals(true, in.isValid()); + } + + @Test + public void testTime() { + in.setStartTime(0); + assertEquals(0, in.getStartTime()); + } + + @Test + public void testPayload() { + CommonMessage.Payload payload = new CommonMessage.Payload(); + payload.setGenericVnfId("VNF_ID"); + CommonMessage.Streams streams = new CommonMessage.Streams(); + streams.setActiveStreams(7); + payload.setStreams(streams); + in.setPayload(payload); + assertEquals("VNF_ID", in.getPayload().getGenericVnfId()); + assertEquals("{\\\"streams\\\": {\\\"active-streams\\\": 7}}", + in.getPayload().getStreams()); + } + + @Test + @Ignore + public void testIncommingToOutgoing(){ + OutgoingMessage newOut; + newOut = Mapper.mapOne(in.toOutgoing(Status.ACCEPTED), OutgoingMessage.class); + assertNotNull(newOut); + assertNotNull(newOut.getHeader().getApiVer()); + assertNotNull(newOut.getHeader().getOriginatorId()); + assertNotNull(newOut.getHeader().getRequestID()); + assertNotNull(newOut.getHeader().getSubRequestId()); + assertNotNull(newOut.getHeader().getTimeStamp()); + assertNotNull(newOut.getStatus().getCode()); + assertNotNull(newOut.getStatus().getValue()); + } + + @Test + @Ignore + public void testToString() { + in = new IncomingMessage(); + assertNotNull(in.toString()); + String id = "test"; + //in.setId(id); + assertNotNull(in.toString()); + assertTrue(in.toString().contains(id)); + } + + @Test + @Ignore + public void testOutgoingUpdateTime() { + //String old = out.getResponseTime(); + out.updateResponseTime(); + //assertFalse(old.equals(out.getResponseTime())); + } + + // Testing for 1510 + @Test + @Ignore + public void testOutgoingToJson() { + // Message Set + String message = "MSG"; + //out.setMessage(message); + JSONObject json = out.toResponse(); + assertNotNull(json); + String respStr = json.getString("response"); + //assertTrue(respStr.contains(out.getResponse().getValue())); + + String msgStr = json.getString("message"); + assertNotNull(msgStr); + //assertFalse(msgStr.contains(out.getOriginalRequest())); // False for 1602 + //assertTrue(msgStr.contains(out.getMessage())); + + // Null Message + //out.setMessage(null); + json = out.toResponse(); + assertNotNull(json); + msgStr = json.getString("message"); + assertNotNull(msgStr); + //assertFalse(msgStr.contains(out.getOriginalRequest())); // False for 1602 + //assertTrue(msgStr.contains(out.getResponse().getValue())); + + // Echoing request + //assertNotNull(out.getOriginalRequest()); + } + + @Test + @Ignore + public void testOutgoingToString() { + String s = out.toString(); + //assertTrue(s.contains(out.getId())); + } +} diff --git a/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/impl/EventHandlerImplTest.java b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/impl/EventHandlerImplTest.java new file mode 100644 index 000000000..8f5ed6d74 --- /dev/null +++ b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/impl/EventHandlerImplTest.java @@ -0,0 +1,279 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ================================================================================ + * Modifications Copyright (C) 2019 Ericsson + * ============================================================================= + * 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.appc.listener.impl; + +import static com.google.common.collect.Lists.newArrayList; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.anyInt; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import java.io.IOException; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Properties; +import java.util.Set; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.runners.MockitoJUnitRunner; +import org.onap.appc.adapter.message.Consumer; +import org.onap.appc.adapter.message.Producer; +import org.onap.appc.listener.ListenerProperties; +import org.powermock.reflect.Whitebox; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +/** + * Test the ProviderAdapter implementation. + */ + +@RunWith(MockitoJUnitRunner.class) +public class EventHandlerImplTest { + + private TestEventHandlerImpl adapter; + private ListenerProperties properties; + + @Mock + private Producer mockProducer; + @Mock + private Consumer mockConsumer; + + private static final String PROP_FILE = "/org/onap/appc/default.properties"; + + private static final String MESSAGE_FILE = "/DCAEResponse.txt"; + + /** + * Setup the test environment. + */ + @Before + public void setup() { + Properties allProps = new Properties(); + try { + allProps.load(getClass().getResourceAsStream(PROP_FILE)); + allProps.remove("appc.ClosedLoop.topic.read.filter"); + properties = new ListenerProperties("appc.ClosedLoop", allProps); + } catch (IOException e) { + System.out.println("WARNING: Failed to load properties file: " + PROP_FILE); + } + adapter = new TestEventHandlerImpl(properties); + adapter.setConsumer(mockConsumer); + adapter.setProducer(mockProducer); + } + + @Test + public void testInitialProperties() { + assertEquals(properties.getProperty("topic.read"), adapter.getReadTopic()); + assertTrue(adapter.getWriteTopic().equals(properties.getProperty("topic.write"))); + assertEquals(properties.getProperty("client.name"), adapter.getClientName()); + assertEquals(properties.getProperty("client.name.id"), adapter.getClientId()); + + String hostStr = properties.getProperty("poolMembers"); + int hostCount = hostStr.length() > 0 ? hostStr.split(",").length : 0; + assertEquals(hostCount, adapter.getPool().size()); + } + + @Test + public void testGettersAndSetters() { + String readTopic = "read"; + String writeTopic = "write"; + String clientName = "APPC-TEST"; + String clientId = "00"; + String newHost = "google.com"; + + adapter.setReadTopic(readTopic); + assertEquals(readTopic, adapter.getReadTopic()); + + adapter.setWriteTopic(writeTopic); + assertEquals(writeTopic, adapter.getWriteTopic()); + + adapter.setClientName(clientName); + assertEquals(clientName, adapter.getClientName()); + + adapter.setClientId(clientId); + assertEquals(clientId, adapter.getClientId()); + + adapter.setCredentials("fake", "secret"); + adapter.clearCredentials(); + + int oldSize = adapter.getPool().size(); + adapter.addToPool(newHost); + assertEquals(oldSize + 1, adapter.getPool().size()); + assertTrue(adapter.getPool().contains(newHost)); + + adapter.removeFromPool(newHost); + assertEquals(oldSize, adapter.getPool().size()); + assertFalse(adapter.getPool().contains(newHost)); + + } + + @Test + public void getIncomingEvents_should_success_when_no_errors_encountered() { + + List<String> testResult = newArrayList("test-result1", "test-result2", "test-result3"); + when(mockConsumer.fetch(anyInt(), anyInt())).thenReturn(testResult); + + List<String> result = adapter.getIncomingEvents(5); + + for (int i = 0; i < testResult.size(); i++) { + assertEquals(testResult.get(i), result.get(i)); + } + } + + + @Test + public void postStatus_should_success_when_no_errors_encountered() { + + adapter.postStatus("test-partition", "test-event"); + verify(mockProducer).post("test-partition", "test-event"); + + adapter.postStatus("test-event"); + verify(mockProducer).post(null, "test-event"); + } + + + @Test + public void closeClients_should_close_producer_and_consumer() { + adapter.getIncomingEvents(5); + adapter.postStatus("test-partition", "test-event"); + + adapter.closeClients(); + verify(mockConsumer).close(); + verify(mockProducer).close(); + } + + @Test + public void testGetEvents() { + EventHandlerImpl adapter = new EventHandlerImpl(properties); + Consumer consumer = Mockito.mock(Consumer.class); + Mockito.when(consumer.fetch(Mockito.anyInt(), Mockito.anyInt())) + .thenReturn(new ArrayList<String>(Arrays.asList("TEST1"))); + Whitebox.setInternalState(adapter, "reader", consumer); + assertEquals("TEST1", adapter.getIncomingEvents().get(0)); + } + + @Test + public void testGetEventsClass() { + EventHandlerImpl adapter = new EventHandlerImpl(properties); + Consumer consumer = Mockito.mock(Consumer.class); + Mockito.when(consumer.fetch(Mockito.anyInt(), Mockito.anyInt())) + .thenReturn(new ArrayList<String>(Arrays.asList("1"))); + Whitebox.setInternalState(adapter, "reader", consumer); + assertEquals(Integer.valueOf(1), adapter.getIncomingEvents(Integer.class).get(0)); + } + + @Test + public void testSetters() { + EventHandlerImpl adapter = new EventHandlerImpl(properties); + adapter.setResponseProblemBlacklistTime("1"); + assertEquals("1", Whitebox.getInternalState(adapter, "responseProblemBlacklistTime")); + adapter.setServerProblemBlacklistTime("1"); + assertEquals("1", Whitebox.getInternalState(adapter, "serverProblemBlacklistTime")); + adapter.setDnsIssueBlacklistTime("1"); + assertEquals("1", Whitebox.getInternalState(adapter, "dnsIssueBlacklistTime")); + adapter.setIOExceptionBlacklistTime("1"); + assertEquals("1", Whitebox.getInternalState(adapter, "ioExceptionBlacklistTime")); + } + +// @Test + public void testRun() { + EventHandlerImpl adapter = new EventHandlerImpl(properties); + + // Runoff any old data + List<String> result = adapter.getIncomingEvents(); + assertNotNull(result); + + // Post new data + DummyObj data = new DummyObj(); + data.key = "value"; + adapter.postStatus(data.toJson()); + + // Wait to account for network delay + sleep(2000); + + // Get data back + List<DummyObj> result2 = adapter.getIncomingEvents(DummyObj.class); + assertNotNull(result2); +// assertEquals(1, result2.size()); + assertEquals(data.toJson(), result2.get(0).toJson()); + } + + private class TestEventHandlerImpl extends EventHandlerImpl { + + private Consumer mockConsumer; + private Producer mockProducer; + + private TestEventHandlerImpl(ListenerProperties props) { + super(props); + } + + @Override + protected Consumer getConsumer() { + return mockConsumer; + } + + @Override + protected Producer getProducer() { + return mockProducer; + } + + private void setConsumer(Consumer consumer) { + mockConsumer = consumer; + } + + private void setProducer(Producer producer) { + mockProducer = producer; + } + } + + @JsonSerialize + public static class DummyObj implements Serializable { + + @JsonProperty("request") // Call request for default filter + public String key; + + public DummyObj() { + } + + public String toJson() { + return String.format("{\"request\": \"%s\"}", key); + } + } + + private void sleep(long ms) { + try { + Thread.sleep(ms); + } catch (Exception e) { + return; + } + } +} diff --git a/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/impl/TestController.java b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/impl/TestController.java new file mode 100644 index 000000000..ccea14cef --- /dev/null +++ b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/impl/TestController.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ================================================================================ + * Modifications Copyright (C) 2019 Ericsson + * ============================================================================= + * Modifications Copyright (C) 2019 IBM + * ============================================================================= + * 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.appc.listener.impl; + +import static org.junit.Assert.assertTrue; + +import java.util.HashSet; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.Mockito; +import org.onap.appc.listener.Controller; +import org.onap.appc.listener.Listener; +import org.onap.appc.listener.ListenerProperties; +import org.onap.appc.listener.demo.impl.ListenerImpl; +import org.powermock.reflect.Whitebox; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class TestController { + + private ListenerProperties listenerProperties; + private Set<ListenerProperties> properties = Mockito.spy(new HashSet<>()); + private EELFLogger log = Mockito.spy(EELFManager.getInstance().getLogger(ControllerImpl.class)); + + @Rule + public ExpectedException expectedEx = ExpectedException.none(); + + @Test + public void testExceptionConstructor() { + listenerProperties = Mockito.mock(ListenerProperties.class); + properties.add(listenerProperties); + new ControllerImpl(properties); + Mockito.verify(properties).remove(Mockito.any()); + } + + @Test + public void testListeners() { + listenerProperties = Mockito.mock(ListenerProperties.class); + properties.add(listenerProperties); + assertTrue(new ControllerImpl(properties).getListeners() instanceof Map); + + } + + @Test + public void testStartException() throws NoSuchMethodException, SecurityException { + Properties props = new Properties(); + props.put("TEST", "TEST"); + listenerProperties = Mockito.spy(new ListenerProperties("TEST", props)); + listenerProperties.setListenerClass(Listener.class); + properties.add(listenerProperties); + ControllerImpl controllerImpl = new ControllerImpl(properties); + controllerImpl.start(); + Mockito.verify(listenerProperties, Mockito.times(2)).getListenerClass(); + } + + @Test + public void testStopException() throws NoSuchMethodException, SecurityException, InterruptedException { + Properties props = new Properties(); + props.put("TEST", "TEST"); + listenerProperties = Mockito.spy(new ListenerProperties("TEST", props)); + listenerProperties.setListenerClass(Listener.class); + properties.add(listenerProperties); + ControllerImpl controllerImpl = new ControllerImpl(properties); + //controllerImpl.start(); + Map<String, Listener> map = Whitebox.getInternalState(controllerImpl, "listeners"); + map.put("TEST", new ListenerImpl(listenerProperties)); + ThreadPoolExecutor executor = Mockito.mock(ThreadPoolExecutor.class); + Mockito.when(executor.awaitTermination(300, TimeUnit.SECONDS)).thenReturn(false); + Whitebox.setInternalState(controllerImpl, "executor", executor); + controllerImpl.stop(false); + Mockito.verify(executor).shutdown(); + } +} diff --git a/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/util/HttpClientUtilTest.java b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/util/HttpClientUtilTest.java new file mode 100644 index 000000000..084d51ed0 --- /dev/null +++ b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/util/HttpClientUtilTest.java @@ -0,0 +1,40 @@ +/* + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2019 Ericsson + * ================================================================================ + * 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.appc.listener.util; + +import static org.junit.Assert.assertTrue; +import org.apache.http.client.HttpClient; +import org.junit.Test; +import org.onap.appc.exceptions.APPCException; + +public class HttpClientUtilTest { + + @Test + public void testHttps() throws APPCException { + assertTrue(HttpClientUtil.getHttpClient("https") instanceof HttpClient); + } + + @Test + public void testHttp() throws APPCException { + assertTrue(HttpClientUtil.getHttpClient("http") instanceof HttpClient); + } +} diff --git a/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/util/TestMapper.java b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/util/TestMapper.java new file mode 100644 index 000000000..2a9483364 --- /dev/null +++ b/services/appc-dmaap-service/appc-event-listener-bundle/src/test/java/org/onap/appc/listener/util/TestMapper.java @@ -0,0 +1,135 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ================================================================================ + * Modifications Copyright (C) 2019 Ericsson + * ============================================================================= + * 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.appc.listener.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.appc.listener.util.Mapper; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +public class TestMapper { + + private String dummyJson = "{\"a\":\"%s\"}"; + private DummyObj dummyObj = new DummyObj(); + + @JsonSerialize + public static class DummyObj implements Serializable { + @JsonProperty("a") + public String a; + + public DummyObj() { + } + } + + @Before + public void setup() { + } + + @Test + public void testGetMapper() { + assertNotNull(Mapper.getMapper()); + } + + @Test + public void testToJsonObject() { + JSONObject out; + out = Mapper.toJsonObject("."); + assertNull(out); + + String value = "b"; + out = Mapper.toJsonObject(String.format(dummyJson, value)); + assertNotNull(out); + assertEquals(value, out.get("a")); + } + + @Test + public void testConstructor() { + // Only here for code coverage + Mapper m = new Mapper(); + assertNotNull(m); + } + + @Test + public void testMap() { + List<String> in = new ArrayList<String>(); + in.add(""); + in.add(null); + + List<DummyObj> out = Mapper.mapList(in, DummyObj.class); + assertNotNull(out); + assertTrue(out.isEmpty()); + + in.add(String.format(dummyJson, "1")); + in.add("{\"invalid\":\"yes\"}"); + in.add(String.format(dummyJson, "2")); + + out = Mapper.mapList(in, DummyObj.class); + assertNotNull(out); + assertEquals(2, out.size()); + assertEquals("1", out.get(0).a); + assertEquals("2", out.get(1).a); + } + + @Test + public void testToJsonString() { + JSONObject jsonObject = Mockito.mock(JSONObject.class); + assertTrue(Mapper.toJsonString(jsonObject).startsWith("Mock for JSONObject")); + } + + @Test + public void testToJsonStringNonJsonObject() { + assertEquals("\"TEST\"", Mapper.toJsonString("TEST")); + } + + @Test + public void testToJsonStringException() { + assertNull(Mapper.toJsonString(new Mapper())); + } + + @Test + public void testToJsonNodeFromJsonStringException() { + assertNull(Mapper.toJsonNodeFromJsonString("{{}")); + } + + @Test + public void testToJsonNode() { + assertTrue(Mapper.toJsonNode(dummyObj) instanceof JsonNode); + } +} |