diff options
Diffstat (limited to 'pnf-sim-lightweight/src/test/java')
16 files changed, 1604 insertions, 0 deletions
diff --git a/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/message/JSONObjectFactoryTest.java b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/message/JSONObjectFactoryTest.java new file mode 100644 index 0000000..da41afd --- /dev/null +++ b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/message/JSONObjectFactoryTest.java @@ -0,0 +1,95 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.pnfsimulator.message; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.onap.pnfsimulator.message.MessageConstants.EVENT_ID; +import static org.onap.pnfsimulator.message.MessageConstants.INTERNAL_HEADER_FIELDS; +import static org.onap.pnfsimulator.message.MessageConstants.LAST_EPOCH_MICROSEC; +import static org.onap.pnfsimulator.message.MessageConstants.NOTIFICATION_FIELDS_VERSION; +import static org.onap.pnfsimulator.message.MessageConstants.NOTIFICATION_FIELDS_VERSION_VALUE; +import static org.onap.pnfsimulator.message.MessageConstants.PNF_LAST_SERVICE_DATE; +import static org.onap.pnfsimulator.message.MessageConstants.PNF_MANUFACTURE_DATE; +import static org.onap.pnfsimulator.message.MessageConstants.PNF_REGISTRATION_FIELDS_VERSION; +import static org.onap.pnfsimulator.message.MessageConstants.PNF_REGISTRATION_FIELDS_VERSION_VALUE; +import static org.onap.pnfsimulator.message.MessageConstants.PRIORITY; +import static org.onap.pnfsimulator.message.MessageConstants.PRIORITY_NORMAL; +import static org.onap.pnfsimulator.message.MessageConstants.REPORTING_ENTITY_NAME; +import static org.onap.pnfsimulator.message.MessageConstants.SEQUENCE; +import static org.onap.pnfsimulator.message.MessageConstants.SEQUENCE_NUMBER; +import static org.onap.pnfsimulator.message.MessageConstants.SOURCE_NAME; +import static org.onap.pnfsimulator.message.MessageConstants.START_EPOCH_MICROSEC; +import static org.onap.pnfsimulator.message.MessageConstants.TIME_ZONE_OFFSET; +import static org.onap.pnfsimulator.message.MessageConstants.VERSION; +import static org.onap.pnfsimulator.message.MessageConstants.VERSION_NUMBER; +import static org.onap.pnfsimulator.message.MessageConstants.VES_EVENT_LISTENER_VERSION; +import static org.onap.pnfsimulator.message.MessageConstants.VES_EVENT_LISTENER_VERSION_NUMBER; +import org.json.JSONObject; +import org.junit.jupiter.api.Test; + +public class JSONObjectFactoryTest { + + @Test + public void generateConstantCommonEventHeader_shouldCreateProperly(){ + JSONObject commonEventHeader = JSONObjectFactory.generateConstantCommonEventHeader(); + assertEquals(11,commonEventHeader.toMap().size()); + assertTrue(commonEventHeader.has(EVENT_ID)); + assertTrue(commonEventHeader.has(TIME_ZONE_OFFSET)); + assertTrue(commonEventHeader.has(LAST_EPOCH_MICROSEC)); + assertTrue(commonEventHeader.has(PRIORITY)); + assertTrue(commonEventHeader.has(SEQUENCE)); + assertTrue(commonEventHeader.has(START_EPOCH_MICROSEC)); + assertTrue(commonEventHeader.has(INTERNAL_HEADER_FIELDS)); + assertTrue(commonEventHeader.has(VERSION)); + assertTrue(commonEventHeader.has(SOURCE_NAME)); + assertTrue(commonEventHeader.has(REPORTING_ENTITY_NAME)); + assertEquals(commonEventHeader.get(PRIORITY),PRIORITY_NORMAL); + assertEquals(commonEventHeader.get(SEQUENCE),SEQUENCE_NUMBER); + assertEquals(commonEventHeader.get(VERSION),VERSION_NUMBER); + assertEquals(commonEventHeader.get(VES_EVENT_LISTENER_VERSION),VES_EVENT_LISTENER_VERSION_NUMBER); + } + + @Test + public void generateConstantPnfRegistrationFields_shouldCreateProperly(){ + JSONObject pnfRegistrationFields = JSONObjectFactory.generatePnfRegistrationFields(); + assertEquals(3,pnfRegistrationFields.toMap().size()); + assertTrue(pnfRegistrationFields.has(PNF_REGISTRATION_FIELDS_VERSION)); + assertEquals(pnfRegistrationFields.get(PNF_REGISTRATION_FIELDS_VERSION), PNF_REGISTRATION_FIELDS_VERSION_VALUE); + assertTrue(pnfRegistrationFields.has(PNF_LAST_SERVICE_DATE)); + assertTrue(pnfRegistrationFields.has(PNF_MANUFACTURE_DATE)); + } + + @Test + public void generateEventId_shouldCreateProperly(){ + String eventId = JSONObjectFactory.generateEventId(); + assertTrue(eventId.startsWith("FileReady_")); + } + + @Test + public void generateNotificationFields_shouldCreateProperly(){ + JSONObject notificationFields = JSONObjectFactory.generateNotificationFields(); + assertEquals(1,notificationFields.keySet().size()); + assertEquals(NOTIFICATION_FIELDS_VERSION_VALUE,notificationFields.get(NOTIFICATION_FIELDS_VERSION)); + + } + +} diff --git a/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/message/MessageProviderTest.java b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/message/MessageProviderTest.java new file mode 100644 index 0000000..0fa8a12 --- /dev/null +++ b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/message/MessageProviderTest.java @@ -0,0 +1,122 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.pnfsimulator.message; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.onap.pnfsimulator.message.MessageConstants.COMMON_EVENT_HEADER; +import static org.onap.pnfsimulator.message.MessageConstants.EVENT; +import static org.onap.pnfsimulator.message.MessageConstants.NOTIFICATION_FIELDS; +import static org.onap.pnfsimulator.message.MessageConstants.PNF_REGISTRATION_FIELDS; +import java.util.Optional; +import org.json.JSONObject; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +public class MessageProviderTest { + + private static final String testParamsPnfRegistration = + "{\"pnfKey1\": \"pnfVal1\",\"pnfKey2\": \"pnfVal2\",\"pnfKey3\": \"pnfVal3\",\"pnfKey4\": \"pnfVal4\"}"; + + private static final String testParamsNotification = + "{\"notKey1\": \"notVal1\",\"notKey2\": \"notVal2\",\"notKey3\": \"notVal3\",\"notKey4\": \"notVal4\"}"; + + private static MessageProvider messageProvider; + + @BeforeAll + public static void setup() { + messageProvider = new MessageProvider(); + } + + @Test + public void createMessage_should_throw_when_given_empty_arguments() { + assertThrows(IllegalArgumentException.class, + () -> messageProvider.createMessage(new JSONObject(), Optional.empty(), Optional.empty()), + "Params object cannot be null"); + } + + @Test + public void createMessage_should_create_constant_message_when_no_params_specified() { + JSONObject message = messageProvider.createMessage(new JSONObject(), Optional.ofNullable(new JSONObject()), + Optional.ofNullable(new JSONObject())); + JSONObject event = message.getJSONObject(EVENT); + + JSONObject commonEventHeader = event.getJSONObject(COMMON_EVENT_HEADER); + JSONObject pnfRegistrationFields = event.getJSONObject(PNF_REGISTRATION_FIELDS); + JSONObject notificationFields = event.getJSONObject(NOTIFICATION_FIELDS); + + JSONObject expectedCommonEventHeader = JSONObjectFactory.generateConstantCommonEventHeader(); + JSONObject expectedPnfRegistrationFields = JSONObjectFactory.generatePnfRegistrationFields(); + JSONObject expectedNotificationFields = JSONObjectFactory.generateNotificationFields(); + + expectedCommonEventHeader + .toMap() + .forEach((key, val) -> assertTrue(commonEventHeader.has(key), + () -> String.format("Key %s is not present", key))); + + expectedPnfRegistrationFields + .toMap() + .forEach((key, val) -> assertTrue(pnfRegistrationFields.has(key), + () -> String.format("Key %s is not present", key))); + + expectedNotificationFields + .toMap() + .forEach((key, val) -> assertTrue(notificationFields.has(key), + () -> String.format("Key %s is not present", key))); + } + + @Test + public void createMessage_should_throw_exception_when_params_specified_as_empty() { + assertThrows(IllegalArgumentException.class, + () -> messageProvider.createMessage(new JSONObject(), Optional.empty(), + Optional.empty())); + } + + @Test + public void createMessage_should_add_specified_params_to_valid_subobjects_with_event_pnf_registration() { + JSONObject message = messageProvider + .createMessage(new JSONObject(), Optional.of(new JSONObject(testParamsPnfRegistration)), Optional.empty()); + JSONObject event = message.getJSONObject(EVENT); + + JSONObject commonEventHeader = event.getJSONObject(COMMON_EVENT_HEADER); + assertEquals(13, commonEventHeader.keySet().size()); + + JSONObject pnfRegistrationFields = event.getJSONObject(PNF_REGISTRATION_FIELDS); + assertEquals("pnfVal1", pnfRegistrationFields.getString("pnfKey1")); + assertEquals("pnfVal2", pnfRegistrationFields.getString("pnfKey2")); + } + + @Test + public void createMessage_should_add_specified_params_to_valid_subobjects_with_event_notification() { + JSONObject message = messageProvider + .createMessage(new JSONObject(), Optional.empty(), Optional.of(new JSONObject(testParamsNotification))); + JSONObject event = message.getJSONObject(EVENT); + + JSONObject commonEventHeader = event.getJSONObject(COMMON_EVENT_HEADER); + assertEquals(12, commonEventHeader.keySet().size()); + + JSONObject notificationFields = event.getJSONObject(NOTIFICATION_FIELDS); + assertEquals("notVal1", notificationFields.getString("notKey1")); + assertEquals("notVal2", notificationFields.getString("notKey2")); + } + +} diff --git a/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/netconfmonitor/NetconfConfigurationCheckingTaskTest.java b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/netconfmonitor/NetconfConfigurationCheckingTaskTest.java new file mode 100644 index 0000000..df5a13d --- /dev/null +++ b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/netconfmonitor/NetconfConfigurationCheckingTaskTest.java @@ -0,0 +1,95 @@ +/// * +// * ============LICENSE_START======================================================= +// * PNF-REGISTRATION-HANDLER +// * ================================================================================ +// * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. +// * ================================================================================ +// * Licensed under the Apache License, Version 2.0 (the "License"); +// * you may not use this file except in compliance with the License. +// * You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. +// * ============LICENSE_END========================================================= +// */ +// +// package org.onap.pnfsimulator.netconfmonitor; +// +// import static org.mockito.ArgumentMatchers.any; +// import static org.mockito.Mockito.never; +// import static org.mockito.Mockito.verify; +// import static org.mockito.Mockito.when; +// +// import com.tailf.jnc.JNCException; +// import java.io.IOException; +// import org.junit.jupiter.api.BeforeEach; +// import org.junit.jupiter.api.Test; +// import org.mockito.Mock; +// import org.mockito.MockitoAnnotations; +// import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationCache; +// import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationReader; +// import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationWriter; +// +// class NetconfConfigurationCheckingTaskTest { +// +// private NetconfConfigurationCheckingTask checkingTask; +// +// @Mock +// private NetconfConfigurationReader reader; +// @Mock +// private NetconfConfigurationWriter writer; +// @Mock +// private NetconfConfigurationCache cache; +// +// @BeforeEach +// void setup() { +// MockitoAnnotations.initMocks(this); +// checkingTask = new NetconfConfigurationCheckingTask(reader, writer, cache); +// } +// +// @Test +// void run_should_update_configuration_when_changed() throws IOException, JNCException { +// String configuration = "newConfiguration"; +// when(reader.read()).thenReturn(configuration); +// when(cache.getConfiguration()).thenReturn("oldConfiguration"); +// +// checkingTask.run(); +// +// verify(reader).read(); +// verify(cache).getConfiguration(); +// verify(writer).writeToFile(configuration); +// verify(cache).update(configuration); +// } +// +// @Test +// void run_should_not_update_configuration_when_same() throws IOException, JNCException { +// String configuration = "configuration"; +// when(reader.read()).thenReturn(configuration); +// when(cache.getConfiguration()).thenReturn("configuration"); +// +// checkingTask.run(); +// +// verify(reader).read(); +// verify(cache).getConfiguration(); +// verify(writer, never()).writeToFile(configuration); +// verify(cache, never()).update(configuration); +// } +// +// @Test +// void run_should_not_take_any_action_when_failed_to_read_configuration() throws IOException, +/// JNCException { +// when(reader.read()).thenThrow(new IOException()); +// +// checkingTask.run(); +// +// verify(reader).read(); +// verify(cache, never()).getConfiguration(); +// verify(writer, never()).writeToFile(any()); +// verify(cache, never()).update(any()); +// } +// } diff --git a/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorServiceConfigurationTest.java b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorServiceConfigurationTest.java new file mode 100644 index 0000000..3ff234b --- /dev/null +++ b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorServiceConfigurationTest.java @@ -0,0 +1,72 @@ +/// * +// * ============LICENSE_START======================================================= +// * PNF-REGISTRATION-HANDLER +// * ================================================================================ +// * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. +// * ================================================================================ +// * Licensed under the Apache License, Version 2.0 (the "License"); +// * you may not use this file except in compliance with the License. +// * You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. +// * ============LICENSE_END========================================================= +// */ +// +// package org.onap.pnfsimulator.netconfmonitor; +// +// import static org.junit.jupiter.api.Assertions.assertNotNull; +// import static org.mockito.ArgumentMatchers.any; +// import static org.mockito.Mockito.doReturn; +// import static org.mockito.Mockito.mock; +// import static org.mockito.Mockito.spy; +// import static org.mockito.Mockito.verify; +// +// import com.tailf.jnc.JNCException; +// import com.tailf.jnc.NetconfSession; +// import java.io.IOException; +// import org.junit.jupiter.api.BeforeEach; +// import org.junit.jupiter.api.Test; +// import org.mockito.Mock; +// +// class NetconfMonitorServiceConfigurationTest { +// +// private NetconfMonitorServiceConfiguration configuration; +// +// @Mock +// private NetconfSession netconfSession; +// +// @BeforeEach +// void setup() { +// netconfSession = mock(NetconfSession.class); +// configuration = spy(new NetconfMonitorServiceConfiguration()); +// } +// +// @Test +// void readNetconfConfiguration() throws IOException, JNCException { +// doReturn(netconfSession).when(configuration).createNetconfSession(any()); +// +// assertNotNull(configuration.configurationReader()); +// verify(configuration).createNetconfSession(any()); +// } +// +// @Test +// void configurationCacheIsNotNull() { +// assertNotNull(configuration.configurationCache()); +// } +// +// @Test +// void netconfConfigurationWriterIsNotNull() { +// assertNotNull(configuration.netconfConfigurationWriter()); +// } +// +// @Test +// void timerIsNotNull() { +// assertNotNull(configuration.timer()); +// } +// } diff --git a/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorServiceTest.java b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorServiceTest.java new file mode 100644 index 0000000..f8690c5 --- /dev/null +++ b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/netconfmonitor/NetconfMonitorServiceTest.java @@ -0,0 +1,73 @@ +/// * +// * ============LICENSE_START======================================================= +// * PNF-REGISTRATION-HANDLER +// * ================================================================================ +// * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. +// * ================================================================================ +// * Licensed under the Apache License, Version 2.0 (the "License"); +// * you may not use this file except in compliance with the License. +// * You may obtain a copy of the License at +// * +// * http://www.apache.org/licenses/LICENSE-2.0 +// * +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an "AS IS" BASIS, +// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// * See the License for the specific language governing permissions and +// * limitations under the License. +// * ============LICENSE_END========================================================= +// */ +// +// package org.onap.pnfsimulator.netconfmonitor; +// +// import static org.mockito.ArgumentMatchers.anyString; +// import static org.mockito.Mockito.any; +// import static org.mockito.Mockito.anyLong; +// import static org.mockito.Mockito.doNothing; +// import static org.mockito.Mockito.times; +// import static org.mockito.Mockito.verify; +// import static org.mockito.Mockito.when; +// +// import com.tailf.jnc.JNCException; +// import java.io.IOException; +// import java.util.Timer; +// import org.junit.jupiter.api.BeforeEach; +// import org.junit.jupiter.api.Test; +// import org.mockito.Mock; +// import org.mockito.MockitoAnnotations; +// import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationCache; +// import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationReader; +// import org.onap.pnfsimulator.netconfmonitor.netconf.NetconfConfigurationWriter; +// +// class NetconfMonitorServiceTest { +// +// private NetconfMonitorService service; +// +// @Mock +// private Timer timer; +// @Mock +// private NetconfConfigurationReader reader; +// @Mock +// private NetconfConfigurationWriter writer; +// @Mock +// private NetconfConfigurationCache cache; +// +// @BeforeEach +// void setup() { +// MockitoAnnotations.initMocks(this); +// service = new NetconfMonitorService(timer, reader, writer, cache); +// } +// +// @Test +// void startNetconfService() throws IOException, JNCException { +// when(reader.read()).thenReturn("message"); +// doNothing().when(writer).writeToFile(anyString()); +// doNothing().when(cache).update(anyString()); +// +// service.start(); +// +// verify(cache, times(1)).update(anyString()); +// verify(writer, times(1)).writeToFile(anyString()); +// verify(timer, times(1)).scheduleAtFixedRate(any(), anyLong(), anyLong()); +// } +// } diff --git a/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationCacheTest.java b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationCacheTest.java new file mode 100644 index 0000000..56f62ac --- /dev/null +++ b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationCacheTest.java @@ -0,0 +1,38 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.pnfsimulator.netconfmonitor.netconf; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +public class NetconfConfigurationCacheTest { + + private static final String CONFIGURATION = "sampleConfiguration"; + + @Test + void changeConfigurationAfterUpdate() { + NetconfConfigurationCache configurationCache = new NetconfConfigurationCache(); + configurationCache.update(CONFIGURATION); + + assertEquals(CONFIGURATION, configurationCache.getConfiguration()); + } +}
\ No newline at end of file diff --git a/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationReaderTest.java b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationReaderTest.java new file mode 100644 index 0000000..65b2bc3 --- /dev/null +++ b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationReaderTest.java @@ -0,0 +1,70 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.pnfsimulator.netconfmonitor.netconf; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.tailf.jnc.Element; +import com.tailf.jnc.JNCException; +import com.tailf.jnc.NetconfSession; +import com.tailf.jnc.NodeSet; +import java.io.IOException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +class NetconfConfigurationReaderTest { + + private static final String NETCONF_MODEL_PATH = ""; + private static final String EXPECTED_STRING_XML = "<?xml version=\"1.0\"?>"; + private NetconfConfigurationReader reader; + + @Mock + private NetconfSession netconfSession; + @Mock + private NodeSet nodeSet; + @Mock + private Element element; + + @BeforeEach + void setup() { + MockitoAnnotations.initMocks(this); + reader = new NetconfConfigurationReader(netconfSession, NETCONF_MODEL_PATH); + } + + @Test + void properlyReadXML() throws IOException, JNCException { + when(netconfSession.getConfig(anyString())).thenReturn(nodeSet); + when(nodeSet.first()).thenReturn(element); + when(element.toXMLString()).thenReturn(EXPECTED_STRING_XML); + + String result = reader.read(); + + verify(netconfSession).getConfig(anyString()); + verify(nodeSet).first(); + verify(element).toXMLString(); + assertEquals(EXPECTED_STRING_XML, result); + } +}
\ No newline at end of file diff --git a/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationWriterTest.java b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationWriterTest.java new file mode 100644 index 0000000..2baee21 --- /dev/null +++ b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/netconfmonitor/netconf/NetconfConfigurationWriterTest.java @@ -0,0 +1,67 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.pnfsimulator.netconfmonitor.netconf; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import org.apache.commons.io.FileUtils; +import org.junit.Rule; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.migrationsupport.rules.EnableRuleMigrationSupport; +import org.junit.rules.TemporaryFolder; + +@EnableRuleMigrationSupport +class NetconfConfigurationWriterTest { + + private static final String TEST_CONFIGURATION = "test-configuration"; + + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Test + void writeToFile_should_write_sample_config_when_directory_exists() throws IOException { + File file = temporaryFolder.newFolder("temp"); + NetconfConfigurationWriter configurationWriter = new NetconfConfigurationWriter(file.getPath()); + + configurationWriter.writeToFile(TEST_CONFIGURATION); + + File[] files = file.listFiles(); + assertEquals(1, files.length); + + String content = FileUtils.readFileToString(files[0], "UTF-8"); + assertEquals(TEST_CONFIGURATION, content); + } + + @Test + void writeToFile_should_not_write_config_when_directory_doesnt_exist() { + String logFolderPath = "/not/existing/logs"; + NetconfConfigurationWriter configurationWriter = new NetconfConfigurationWriter(logFolderPath); + + configurationWriter.writeToFile(TEST_CONFIGURATION); + + assertFalse(Files.exists(Paths.get(logFolderPath))); + } +}
\ No newline at end of file diff --git a/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/rest/SimulatorControllerTest.java b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/rest/SimulatorControllerTest.java new file mode 100644 index 0000000..215cee0 --- /dev/null +++ b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/rest/SimulatorControllerTest.java @@ -0,0 +1,226 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.pnfsimulator.rest; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.onap.pnfsimulator.simulator.TestMessages.VALID_COMMON_EVENT_HEADER_PARAMS; +import static org.onap.pnfsimulator.simulator.TestMessages.VALID_NOTIFICATION_PARAMS; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.pnfsimulator.FileProvider; +import org.onap.pnfsimulator.simulator.Simulator; +import org.onap.pnfsimulator.simulator.SimulatorFactory; +import org.onap.pnfsimulator.simulator.client.RestTemplateAdapter; +import org.onap.pnfsimulator.simulator.validation.JSONValidator; +import org.onap.pnfsimulator.simulator.validation.NoRopFilesException; +import org.onap.pnfsimulator.simulator.validation.ValidationException; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +class SimulatorControllerTest { + + private static final String START_URL = "/simulator/start"; + private static final String STOP_URL = "/simulator/stop"; + private static final String STATUS_URL = "/simulator/status"; + private static final String JSON_MSG_EXPRESSION = "$.message"; + private static final String JSON_STATUS_EXPRESSION = "$.simulatorStatus"; + private static final String TEST_VES_URL = "http://localhost:10000/eventListener/v7"; + private static final String TEST_XNF_URL = "sftp://onap:pano@10.11.0.68" + "/"; + private static final String PROPER_JSON = "{\n" + + " \"simulatorParams\": {\n" + + " \"testDuration\": \"10\",\n" + + " \"messageInterval\": \"1\"\n" + + " },\n" + + " \"commonEventHeaderParams\": {\n" + + " \"eventName\": \"val11\",\n" + + " \"nfNamingCode\": \"val12\",\n" + + " \"nfcNamingCode\": \"val13\",\n" + + " \"sourceName\": \"val14\",\n" + + " \"sourceId\": \"val15\",\n" + + " \"reportingEntityName\": \"val16\",\n" + + " },\n" + + + " \"pnfRegistrationParams\": {\n" + + " \"SerialNumber\": \"val1\",\n" + + " \"VendorName\": \"val2\",\n" + + " \"OamIpv4Address\": \"val3\",\n" + + " \"OamIpv6Address\": \"val4\",\n" + + " \"Family\": \"val5\",\n" + + " \"ModelNumber\": \"val6\",\n" + + " \"SoftwareVersion\": \"val7\",\n" + + " }\n" + + "}"; + private static final String WRONG_JSON = "{\n" + + " \"mes\": {\n" + + " \"vesServerUrl\": \"http://10.154.187.70:8080/eventListener/v5\",\n" + + " \"testDuration\": \"10\",\n" + + " \"messageInterval\": \"1\"\n" + + " },\n" + + " \"messageParams\": {\n" + + " \"sourceName\": \"val12\",\n" + + " \"sourceId\": \"val13\",\n" + + " \"reportingEntityName\": \"val14\"\n" + + " }\n" + + "}\n"; + + private MockMvc mockMvc; + + @InjectMocks + private SimulatorController controller; + + @Mock + private SimulatorFactory factory; + @Mock + private JSONValidator validator; + + private Simulator simulator; + + private FileProvider fileProvider = mock(FileProvider.class); + + private void createSampleFileList() { + List<String> fileList = new ArrayList<>(); + fileList.add("A20190401.1608+0000-1622+0000_excl-eeiwbue-perf-large-pnf-sim-lw-1.xml.gz"); + fileList.add("A20190401.1623+0000-1637+0000_excl-eeiwbue-perf-large-pnf-sim-lw-1.xml.gz"); + + try { + doReturn(fileList).when(fileProvider).getFiles(); + } catch (NoRopFilesException e) { + e.printStackTrace(); + } + } + + @BeforeEach + void setup() { + MockitoAnnotations.initMocks(this); + createSampleFileList(); + simulator = createEndlessSimulator(); + mockMvc = MockMvcBuilders + .standaloneSetup(controller) + .build(); + } + + private Simulator createEndlessSimulator() { + return spy(Simulator.builder() + .withCustomRestTemplateAdapter(mock(RestTemplateAdapter.class)) + .withCommonEventHeaderParams(VALID_COMMON_EVENT_HEADER_PARAMS) + .withPnfRegistrationParams(Optional.empty()) + .withNotificationParams(VALID_NOTIFICATION_PARAMS) + .withVesUrl(TEST_VES_URL) + .withXnfUrl(TEST_XNF_URL) + .withFileProvider(fileProvider) + .withInterval(Duration.ofMinutes(1)) + .build()); + } + + @Test + void wrongJSONFormatOnStart() throws Exception { + when(factory.create(any(),any(), any(),any())).thenReturn(simulator); + doThrow(new ValidationException("")).when(validator).validate(anyString(), anyString()); + + mockMvc.perform(post("/simulator/start").content(WRONG_JSON)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.message").value("Cannot start simulator - Json format " + + "is not compatible with schema definitions")); + verify(validator).validate(anyString(), anyString()); + } + + @Test + void startSimulatorProperly() throws Exception { + startSimulator(); + + verify(validator).validate(anyString(), anyString()); + verify(factory).create(any(),any(), any(),any()); + verify(simulator).start(); + } + + @Test + void notStartWhenAlreadyRunning() throws Exception { + startSimulator(); + + mockMvc + .perform(post(START_URL).content(PROPER_JSON)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath(JSON_MSG_EXPRESSION).value("Cannot start simulator since it's already running")); + } + + @Test + void stopSimulatorWhenRunning() throws Exception { + startSimulator(); + + mockMvc + .perform(post(STOP_URL)) + .andExpect(status().isOk()) + .andExpect(jsonPath(JSON_MSG_EXPRESSION).value("Simulator successfully stopped")); + } + + @Test + void getNotRunningMessageWhenOff() throws Exception { + mockMvc + .perform(post(STOP_URL)) + .andExpect(status().isBadRequest()) + .andExpect(jsonPath(JSON_MSG_EXPRESSION).value("Cannot stop simulator, because it's not running")); + } + + @Test + void getRunningStatusWhenOn() throws Exception { + startSimulator(); + + mockMvc + .perform(get(STATUS_URL)) + .andExpect(status().isOk()) + .andExpect(jsonPath(JSON_STATUS_EXPRESSION).value("RUNNING")); + } + + @Test + void getNotRunningStatusWhenOff() throws Exception { + mockMvc + .perform(get(STATUS_URL)) + .andExpect(status().isOk()) + .andExpect(jsonPath(JSON_STATUS_EXPRESSION).value("NOT RUNNING")); + } + + private void startSimulator() throws Exception { + when(factory.create(any(), any(), any(),any())).thenReturn(simulator); + + mockMvc + .perform(post(START_URL).content(PROPER_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath(JSON_MSG_EXPRESSION).value("Simulator started")); + } +}
\ No newline at end of file diff --git a/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/rest/util/DateUtilTest.java b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/rest/util/DateUtilTest.java new file mode 100644 index 0000000..99b9af7 --- /dev/null +++ b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/rest/util/DateUtilTest.java @@ -0,0 +1,38 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.pnfsimulator.rest.util; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import org.junit.jupiter.api.Test; + +class DateUtilTest { + + @Test + void getFormattedDate() { + Calendar currentCalendar = Calendar.getInstance(); + String expectedResult = String.valueOf(currentCalendar.get(Calendar.YEAR)); + + assertEquals(expectedResult, DateUtil.getTimestamp(new SimpleDateFormat("yyyy"))); + } +}
\ No newline at end of file diff --git a/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/rest/util/ResponseBuilderTest.java b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/rest/util/ResponseBuilderTest.java new file mode 100644 index 0000000..59e1e3b --- /dev/null +++ b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/rest/util/ResponseBuilderTest.java @@ -0,0 +1,65 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.pnfsimulator.rest.util; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +public class ResponseBuilderTest { + + + private static final HttpStatus SAMPLE_STATUS = HttpStatus.OK; + + @Test + void response_should_have_empty_body_when_built_immediately() { + ResponseEntity responseEntity = ResponseBuilder.status(SAMPLE_STATUS).build(); + + assertAll( + () -> assertEquals(responseEntity.getStatusCode(), SAMPLE_STATUS), + () -> assertNull(responseEntity.getBody()) + ); + } + + @Test + void builder_should_set_response_status_and_body() { + String key = "key"; + String value = "value"; + ResponseEntity response = ResponseBuilder + .status(SAMPLE_STATUS) + .put(key, value) + .build(); + + Map<String, Object> body = (Map<String, Object>) response.getBody(); + + assertAll( + () -> assertEquals(SAMPLE_STATUS, response.getStatusCode()), + () -> assertEquals(value, body.get(key)) + ); + } + + +}
\ No newline at end of file diff --git a/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/simulator/SimulatorFactoryTest.java b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/simulator/SimulatorFactoryTest.java new file mode 100644 index 0000000..d8e60c1 --- /dev/null +++ b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/simulator/SimulatorFactoryTest.java @@ -0,0 +1,66 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.pnfsimulator.simulator; + +import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.onap.pnfsimulator.simulator.TestMessages.INVALID_SIMULATOR_PARAMS; +import static org.onap.pnfsimulator.simulator.TestMessages.VALID_COMMON_EVENT_HEADER_PARAMS; +import static org.onap.pnfsimulator.simulator.TestMessages.VALID_NOTIFICATION_PARAMS; +import static org.onap.pnfsimulator.simulator.TestMessages.VALID_PNF_REGISTRATION_PARAMS; +import static org.onap.pnfsimulator.simulator.TestMessages.VALID_SIMULATOR_PARAMS; +import java.util.Optional; +import org.json.JSONException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class SimulatorFactoryTest { + + + private SimulatorFactory simulatorFactory; + + @BeforeEach + void setUp() { + simulatorFactory = new SimulatorFactory(); + } + + @Test + void should_successfully_create_simulator_given_valid_pnf_registration_params() { + assertNotNull(simulatorFactory.create(VALID_SIMULATOR_PARAMS, VALID_COMMON_EVENT_HEADER_PARAMS, + VALID_PNF_REGISTRATION_PARAMS, Optional.empty())); + } + + @Test + void should_successfully_create_simulator_given_valid_notification_params_and_valid_output_message() { + assertNotNull(simulatorFactory.create(VALID_SIMULATOR_PARAMS, VALID_COMMON_EVENT_HEADER_PARAMS, + Optional.empty(), VALID_NOTIFICATION_PARAMS)); + } + + @Test + void should_throw_given_invalid_simulator_params() { + assertThrows( + JSONException.class, + () -> simulatorFactory.create(INVALID_SIMULATOR_PARAMS, VALID_COMMON_EVENT_HEADER_PARAMS, + VALID_PNF_REGISTRATION_PARAMS, VALID_NOTIFICATION_PARAMS)); + } +} + + diff --git a/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/simulator/SimulatorTest.java b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/simulator/SimulatorTest.java new file mode 100644 index 0000000..1f15c01 --- /dev/null +++ b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/simulator/SimulatorTest.java @@ -0,0 +1,204 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.pnfsimulator.simulator; + +import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTimeout; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.onap.pnfsimulator.simulator.TestMessages.INVALID_NOTIFICATION_PARAMS; +import static org.onap.pnfsimulator.simulator.TestMessages.INVALID_PNF_REGISTRATION_PARAMS_1; +import static org.onap.pnfsimulator.simulator.TestMessages.INVALID_PNF_REGISTRATION_PARAMS_2; +import static org.onap.pnfsimulator.simulator.TestMessages.INVALID_PNF_REGISTRATION_PARAMS_3; +import static org.onap.pnfsimulator.simulator.TestMessages.VALID_COMMON_EVENT_HEADER_PARAMS; +import static org.onap.pnfsimulator.simulator.TestMessages.VALID_NOTIFICATION_PARAMS; +import static org.onap.pnfsimulator.simulator.TestMessages.VALID_PNF_REGISTRATION_PARAMS; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; +import org.mockito.Mockito; +import org.onap.pnfsimulator.FileProvider; +import org.onap.pnfsimulator.simulator.client.RestTemplateAdapter; +import org.onap.pnfsimulator.simulator.validation.NoRopFilesException; +import org.onap.pnfsimulator.simulator.validation.ValidationException; + +public class SimulatorTest { + + private static final String TEST_VES_URL = "http://localhost:10000/eventListener/v7"; + private static final String TEST_XNF_URL = "sftp://onap:pano@10.11.0.68" + "/"; + private FileProvider fileProvider = mock(FileProvider.class); + + private void createSampleFileList() { + List<String> fileList = new ArrayList<>(); + fileList.add("A20190401.1608+0000-1622+0000_excl-eeiwbue-perf-large-pnf-sim-lw-1.xml.gz"); + fileList.add("A20190401.1623+0000-1637+0000_excl-eeiwbue-perf-large-pnf-sim-lw-1.xml.gz"); + + try { + doReturn(fileList).when(fileProvider).getFiles(); + } catch (NoRopFilesException e) { + e.printStackTrace(); + } + } + + @Test + void builder_should_create_endless_simulator_when_duration_not_specified() { + Simulator simulator = Simulator + .builder() + .withDuration(Duration.ofSeconds(1)) + .withVesUrl(TEST_VES_URL).build(); + + assertFalse(simulator.isEndless()); + + simulator = Simulator + .builder() + .withVesUrl(TEST_VES_URL).build(); + + assertTrue(simulator.isEndless()); + } + + @Test + void simulator_should_stop_when_interrupted() { + createSampleFileList(); + + RestTemplateAdapter httpClientMock = Mockito.mock(RestTemplateAdapter.class); + Simulator simulator = Simulator.builder() + .withInterval(Duration.ofSeconds(1)) + .withCustomRestTemplateAdapter(httpClientMock) + .withCommonEventHeaderParams(VALID_COMMON_EVENT_HEADER_PARAMS) + .withPnfRegistrationParams(Optional.empty()) + .withNotificationParams(VALID_NOTIFICATION_PARAMS) + .withVesUrl(TEST_VES_URL) + .withXnfUrl(TEST_XNF_URL) + .withCustomRestTemplateAdapter(httpClientMock) + .withFileProvider(fileProvider).build(); + + simulator.start(); + simulator.interrupt(); + + assertTimeout(Duration.ofSeconds(1), (Executable) simulator::join); + } + + @Test + void should_throw_noropfiles_exception_given_empty_filelist() { + Simulator simulator = Simulator.builder() + .withDuration(Duration.ofMillis(100)) + .withInterval(Duration.ofMillis(100)) + .withCommonEventHeaderParams(VALID_COMMON_EVENT_HEADER_PARAMS) + .withPnfRegistrationParams(VALID_PNF_REGISTRATION_PARAMS) + .withNotificationParams(Optional.empty()) + .withVesUrl(TEST_VES_URL) + .withXnfUrl(TEST_XNF_URL) + .withFileProvider(new FileProvider()).build(); + simulator.run(); + Exception e = simulator.getThrownException(); + assertTrue(e instanceof NoRopFilesException); + } + + @Test + void should_throw_validation_exception_given_invalid_params() { + createSampleFileList(); + + Simulator simulator = Simulator.builder() + .withDuration(Duration.ofMillis(100)) + .withInterval(Duration.ofMillis(100)) + .withCommonEventHeaderParams(VALID_COMMON_EVENT_HEADER_PARAMS) + .withPnfRegistrationParams(INVALID_PNF_REGISTRATION_PARAMS_1) + .withNotificationParams(Optional.empty()) + .withVesUrl(TEST_VES_URL) + .withXnfUrl(TEST_XNF_URL) + .withFileProvider(fileProvider).build(); + simulator.run(); + Exception e = simulator.getThrownException(); + assertTrue(e instanceof ValidationException); + + simulator = Simulator.builder() + .withDuration(Duration.ofMillis(100)) + .withInterval(Duration.ofMillis(100)) + .withCommonEventHeaderParams(VALID_COMMON_EVENT_HEADER_PARAMS) + .withPnfRegistrationParams(INVALID_PNF_REGISTRATION_PARAMS_2) + .withNotificationParams(Optional.empty()) + .withVesUrl(TEST_VES_URL) + .withXnfUrl(TEST_XNF_URL) + .withFileProvider(fileProvider).build(); + simulator.run(); + e = simulator.getThrownException(); + assertTrue(e instanceof ValidationException); + + simulator = Simulator.builder() + .withDuration(Duration.ofMillis(100)) + .withInterval(Duration.ofMillis(100)) + .withCommonEventHeaderParams(VALID_COMMON_EVENT_HEADER_PARAMS) + .withPnfRegistrationParams(INVALID_PNF_REGISTRATION_PARAMS_3) + .withNotificationParams(Optional.empty()) + .withVesUrl(TEST_VES_URL) + .withXnfUrl(TEST_XNF_URL) + .withFileProvider(fileProvider).build(); + simulator.run(); + e = simulator.getThrownException(); + assertTrue(e instanceof ValidationException); + + simulator = Simulator.builder() + .withDuration(Duration.ofMillis(100)) + .withInterval(Duration.ofMillis(100)) + .withCommonEventHeaderParams(VALID_COMMON_EVENT_HEADER_PARAMS) + .withPnfRegistrationParams(VALID_PNF_REGISTRATION_PARAMS) + .withNotificationParams(INVALID_NOTIFICATION_PARAMS) + .withVesUrl(TEST_VES_URL) + .withXnfUrl(TEST_XNF_URL) + .withFileProvider(fileProvider).build(); + simulator.run(); + e = simulator.getThrownException(); + assertTrue(e instanceof ValidationException); + } + + @Test + void simulator_should_send_fileready_message() { + createSampleFileList(); + + RestTemplateAdapter httpClientMock = Mockito.mock(RestTemplateAdapter.class); + Simulator simulator = Simulator.builder() + .withDuration(Duration.ofMillis(100)) + .withInterval(Duration.ofMillis(100)) + .withCommonEventHeaderParams(VALID_COMMON_EVENT_HEADER_PARAMS) + .withPnfRegistrationParams(Optional.empty()) + .withNotificationParams(VALID_NOTIFICATION_PARAMS) + .withVesUrl(TEST_VES_URL) + .withXnfUrl(TEST_XNF_URL) + .withCustomRestTemplateAdapter(httpClientMock) + .withFileProvider(fileProvider).build(); + simulator.run(); + Exception e = simulator.getThrownException(); + assertNull(e); + + assertTimeout(Duration.ofMillis(150), (Executable) simulator::join); + verify(httpClientMock, times(1)).send(anyString(), eq(TEST_VES_URL)); + } +} + diff --git a/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/simulator/TestMessages.java b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/simulator/TestMessages.java new file mode 100644 index 0000000..d92b3c2 --- /dev/null +++ b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/simulator/TestMessages.java @@ -0,0 +1,116 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.pnfsimulator.simulator; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Optional; +import org.json.JSONObject; + +public final class TestMessages { + + static final JSONObject VALID_SIMULATOR_PARAMS = new JSONObject(getContent("validSimulatorParams.json")); + public static final JSONObject VALID_COMMON_EVENT_HEADER_PARAMS = new JSONObject(getContent("validCommonEventHeaderParams.json")); + static final Optional<JSONObject> VALID_PNF_REGISTRATION_PARAMS = Optional + .of(new JSONObject(getContent("validPnfRegistrationParams.json"))); + public static final Optional<JSONObject> VALID_NOTIFICATION_PARAMS = Optional + .of(new JSONObject(getContent("validNotificationParams.json"))); + + static final JSONObject INVALID_SIMULATOR_PARAMS = new JSONObject( + "{\n" + + " \"vesServerUrl\": \"http://10.42.111.42:8080/eventListener/v5\",\n" + + " \"messageInterval\": \"1\"\n" + + "}"); + + + static final Optional<JSONObject> INVALID_PNF_REGISTRATION_PARAMS_1 = Optional.of(new JSONObject( + "{\n" + + " \"pnfSerialNumber\": \"val1\",\n" + + " \"pnfVendorName\": \"val2\",\n" + + " \"pnfFamily\": \"val5\",\n" + + " \"pnfModelNumber\": \"val6\",\n" + + " \"pnfSoftwareVersion\": \"val7\",\n" + + " \"pnfType\": \"val8\",\n" + + " \"eventName\": \"val9\",\n" + + " \"nfNamingCode\": \"val10\",\n" + + " \"nfcNamingCode\": \"val11\",\n" + + " \"sourceName\": \"val12\",\n" + + " \"sourceId\": \"val13\",\n" + + " \"reportingEntityName\": \"val14\"\n" + + "}")); + + static final Optional<JSONObject> INVALID_PNF_REGISTRATION_PARAMS_2 = Optional.of(new JSONObject( + "{\n" + + " \"pnfVendorName\": \"val2\",\n" + + " \"pnfOamIpv4Address\": \"val3\",\n" + + " \"pnfOamIpv6Address\": \"val4\",\n" + + " \"pnfFamily\": \"val5\",\n" + + " \"pnfModelNumber\": \"val6\",\n" + + " \"pnfSoftwareVersion\": \"val7\",\n" + + " \"pnfType\": \"val8\",\n" + + " \"eventName\": \"val9\",\n" + + " \"nfNamingCode\": \"val10\",\n" + + " \"nfcNamingCode\": \"val11\",\n" + + " \"sourceName\": \"val12\",\n" + + " \"sourceId\": \"val13\",\n" + + " \"reportingEntityName\": \"val14\"\n" + + "}")); + + static final Optional<JSONObject> INVALID_PNF_REGISTRATION_PARAMS_3 = Optional.of(new JSONObject( + "{\n" + + " \"pnfSerialNumber\": \"val1\",\n" + + " \"pnfOamIpv4Address\": \"val3\",\n" + + " \"pnfFamily\": \"val5\",\n" + + " \"pnfModelNumber\": \"val6\",\n" + + " \"pnfSoftwareVersion\": \"val7\",\n" + + " \"pnfType\": \"val8\",\n" + + " \"eventName\": \"val9\",\n" + + " \"nfNamingCode\": \"val10\",\n" + + " \"nfcNamingCode\": \"val11\",\n" + + " \"sourceName\": \"val12\",\n" + + " \"sourceId\": \"val13\",\n" + + " \"reportingEntityName\": \"val14\"\n" + + "}")); + + static final Optional<JSONObject> INVALID_NOTIFICATION_PARAMS = Optional.of(new JSONObject( + "{\n" + + " \"mother\": \"val1\",\n" + + " \"father\": \"val3\",\n" + + "}")); + + + private TestMessages() { + } + + private static String getContent(String fileName) { + try { + String pathAsString = TestMessages.class.getResource(fileName).getPath(); + StringBuilder stringBuilder = new StringBuilder(); + Files.readAllLines(Paths.get(pathAsString)).forEach(line -> { + stringBuilder.append(line); + }); + return stringBuilder.toString(); + } catch (IOException e) { + throw new RuntimeException(String.format("Cannot read JSON file %s", fileName)); + } + } +} diff --git a/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/simulator/client/RestTemplateAdapterImplTest.java b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/simulator/client/RestTemplateAdapterImplTest.java new file mode 100644 index 0000000..d423222 --- /dev/null +++ b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/simulator/client/RestTemplateAdapterImplTest.java @@ -0,0 +1,134 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.pnfsimulator.simulator.client; + +import org.mockito.Mock; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.notNull; +import static org.mockito.Mockito.verify; +import static org.mockito.MockitoAnnotations.initMocks; + +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpEntity; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class RestTemplateAdapterImplTest { + + private RestTemplateAdapter adapter; + + @Mock + private RestTemplate restTemplate; + @Mock + ResponseEntity<String> response; + + @BeforeEach + void setup() { + initMocks(this); + adapter = new RestTemplateAdapterImpl(restTemplate); + } + + @Test + void send_should_successfully_send_request_given_valid_http_url() + throws HttpClientErrorException { + + String content = "test-msg"; + String urlHttp = "http://valid-url"; + + when( + restTemplate.postForEntity( + (String) notNull(), + (HttpEntity) notNull(), + eq(String.class) + ) + ).thenReturn(response); + + adapter.send(content, urlHttp); + + verify( + restTemplate, times(1)).postForEntity( + (String) notNull(), + (HttpEntity) notNull(), + eq(String.class) + ); + verify(response).getStatusCode(); + } + + @Test + void send_should_successfully_send_request_given_valid_https_url() + throws HttpClientErrorException { + + String content = "test-msg"; + String urlHttps = "https://valid-url"; + + when( + restTemplate.postForEntity( + (String) notNull(), + (HttpEntity) notNull(), + eq(String.class) + ) + ).thenReturn(response); + + adapter.send(content, urlHttps); + + verify( + restTemplate, times(1)).postForEntity( + (String) notNull(), + (HttpEntity) notNull(), + eq(String.class) + ); + verify(response).getStatusCode(); + } + + @Test + void send_should_not_send_request_given_invalid_url() + throws HttpClientErrorException { + + String content = "test-msg"; + String url = "http://invalid-url"; + + doThrow( + new HttpClientErrorException(HttpStatus.BAD_REQUEST)).when( + restTemplate).postForEntity( + (String) notNull(), + (HttpEntity) notNull(), + eq(String.class) + ); + + adapter.send(content, url); + + verify( + restTemplate, times(1)).postForEntity( + (String) notNull(), + (HttpEntity) notNull(), + eq(String.class) + ); + verify(response, never()).getStatusCode(); + } +} diff --git a/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/simulator/validation/JSONValidatorTest.java b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/simulator/validation/JSONValidatorTest.java new file mode 100644 index 0000000..30dfe06 --- /dev/null +++ b/pnf-sim-lightweight/src/test/java/org/onap/pnfsimulator/simulator/validation/JSONValidatorTest.java @@ -0,0 +1,123 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 NOKIA Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.pnfsimulator.simulator.validation; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +import com.github.fge.jsonschema.core.exceptions.InvalidSchemaException; +import com.github.fge.jsonschema.core.exceptions.ProcessingException; +import java.io.IOException; +import java.net.URL; +import org.json.JSONObject; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class JSONValidatorTest { + + private final static String VALID_SCHEMA_NAME = "valid-test-schema.json"; + private final static String INVALID_SCHEMA_NAME = "invalid-test-schema.json"; + + private JSONValidator validator; + + @BeforeEach + void setUp() { + validator = new JSONValidator(); + } + + @Test + void validate_should_not_throw_given_valid_json() throws ProcessingException, IOException, ValidationException { + validator.validate(getValidJsonString(), getResourcePath(VALID_SCHEMA_NAME)); + } + + @Test + void validate_should_not_throw_when_optional_parameter_missing() + throws ProcessingException, IOException, ValidationException { + + String invalidJsonString = new JSONObject() + .put("key1", "value1") + .put("key2", "value2") + .toString(); + + validator.validate(invalidJsonString, getResourcePath(VALID_SCHEMA_NAME)); + } + + @Test + void validate_should_throw_when_mandatory_parameter_missing() { + + String invalidJsonString = new JSONObject() + .put("key1", "value1") + .put("key3", "value3") + .toString(); + + assertThrows( + ValidationException.class, + () -> validator.validate(invalidJsonString, getResourcePath(VALID_SCHEMA_NAME))); + } + + @Test + void validate_should_throw_when_invalid_json_format() { + String invalidJsonString = "{" + + "\"key1\": \"value1\"" + + "\"key2\": \"value2" + + "}"; + + assertThrows( + IOException.class, + () -> validator.validate(invalidJsonString, getResourcePath(VALID_SCHEMA_NAME))); + } + + @Test + void validate_should_throw_when_invalid_schema_format() { + assertThrows( + InvalidSchemaException.class, + () -> validator.validate(getValidJsonString(), getResourcePath(INVALID_SCHEMA_NAME))); + } + + @Test + void validate_should_throw_when_invalid_schema_path() { + + assertThrows( + IOException.class, + () -> validator.validate(getValidJsonString(), "/not/existing/path/schema.json")); + } + + private String getResourcePath(String schemaFileName) { + URL result = getClass() + .getClassLoader() + .getResource(schemaFileName); + + if (result == null) { + throw new IllegalArgumentException("Given file doesn't exist"); + } else { + return result + .toString() + .replace("file:", ""); + } + } + + private String getValidJsonString() { + return new JSONObject() + .put("key1", "value1") + .put("key2", "value2") + .put("key3", "value3") + .toString(); + } +}
\ No newline at end of file |