diff options
Diffstat (limited to 'netconfsimulator/src/test/java/org/onap')
11 files changed, 1111 insertions, 0 deletions
diff --git a/netconfsimulator/src/test/java/org/onap/netconfsimulator/kafka/EmbeddedKafkaConfig.java b/netconfsimulator/src/test/java/org/onap/netconfsimulator/kafka/EmbeddedKafkaConfig.java new file mode 100644 index 0000000..5ddf2b2 --- /dev/null +++ b/netconfsimulator/src/test/java/org/onap/netconfsimulator/kafka/EmbeddedKafkaConfig.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * Simulator + * ================================================================================ + * Copyright (C) 2019 Nokia. 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.netconfsimulator.kafka; + + +import java.util.Map; +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; +import org.springframework.kafka.core.ConsumerFactory; +import org.springframework.kafka.core.DefaultKafkaConsumerFactory; +import org.springframework.kafka.core.DefaultKafkaProducerFactory; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.core.ProducerFactory; +import org.springframework.kafka.test.utils.KafkaTestUtils; + +import static org.onap.netconfsimulator.kafka.StoreServiceTest.embeddedKafka; + +@Configuration +class EmbeddedKafkaConfig { + + @Bean + KafkaTemplate<String, String> kafkaTemplate(){ + return new KafkaTemplate<>(producerFactory()); + } + + @Bean + @Autowired + ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory(ConsumerFactory<String, String> consumerFactory){ + ConcurrentKafkaListenerContainerFactory<String, String> containerFactory = new ConcurrentKafkaListenerContainerFactory<>(); + containerFactory.setConsumerFactory(consumerFactory); + return containerFactory; + } + + @Bean + ConsumerFactory<String, String> consumerFactory(){ + Map<String, Object> consumerProperties = + KafkaTestUtils.consumerProps("sender", "false", embeddedKafka.getEmbeddedKafka()); + consumerProperties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); + return new DefaultKafkaConsumerFactory<>(consumerProperties); + } + + private ProducerFactory<String, String> producerFactory() { + Map<String, Object> senderProperties = + KafkaTestUtils.senderProps(embeddedKafka.getEmbeddedKafka().getBrokersAsString()); + return new DefaultKafkaProducerFactory<>(senderProperties); + } + +} diff --git a/netconfsimulator/src/test/java/org/onap/netconfsimulator/kafka/StoreControllerTest.java b/netconfsimulator/src/test/java/org/onap/netconfsimulator/kafka/StoreControllerTest.java new file mode 100644 index 0000000..02eec12 --- /dev/null +++ b/netconfsimulator/src/test/java/org/onap/netconfsimulator/kafka/StoreControllerTest.java @@ -0,0 +1,86 @@ +/*- + * ============LICENSE_START======================================================= + * Simulator + * ================================================================================ + * Copyright (C) 2019 Nokia. 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.netconfsimulator.kafka; + +import java.time.Instant; +import java.util.List; +import org.assertj.core.api.Assertions; +import org.assertj.core.util.Lists; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import static org.mockito.Mockito.when; + +@RunWith(SpringJUnit4ClassRunner.class) +public class StoreControllerTest { + + private static final String MESSAGE_3 = "message 3"; + private static final String MESSAGE_2 = "message 2"; + private static final String MESSAGE_1 = "message 1"; + + private static final List<MessageDTO> ALL_MESSAGES = Lists.newArrayList(new MessageDTO(Instant.now().getEpochSecond(), MESSAGE_1), + new MessageDTO(Instant.now().getEpochSecond(), MESSAGE_2), + new MessageDTO(Instant.now().getEpochSecond(), MESSAGE_3)); + + @Mock + private StoreService service; + + @InjectMocks + private StoreController storeController; + + + @Test + public void lessShouldTakeAllMessagesTest() { + when(service.getLastMessages(3)).thenReturn(ALL_MESSAGES); + + List<MessageDTO> lessResponse = storeController.less(3); + + assertResponseContainsExpectedMessages(lessResponse, 3, MESSAGE_1, MESSAGE_2, MESSAGE_3); + } + + @Test + public void lessShouldTakeTwoMessagesTest() { + when(service.getLastMessages(2)).thenReturn(Lists.newArrayList(new MessageDTO(Instant.now().getEpochSecond(), MESSAGE_1))); + + List<MessageDTO> lessResult = storeController.less(2); + + assertResponseContainsExpectedMessages(lessResult, 1, MESSAGE_1); + } + + @Test + public void shouldGetAllMessages(){ + when(service.getAllMessages()).thenReturn(ALL_MESSAGES); + + List<MessageDTO> allMsgResult = storeController.getAllConfigurationChanges(); + + assertResponseContainsExpectedMessages(allMsgResult, 3, MESSAGE_1, MESSAGE_2, MESSAGE_3); + } + + private void assertResponseContainsExpectedMessages(List<MessageDTO> actualMessages, int expectedMessageCount, String... expectedMessages){ + Assertions.assertThat(actualMessages.stream().map(MessageDTO::getConfiguration)) + .hasSize(expectedMessageCount) + .containsExactly(expectedMessages); + } + +} diff --git a/netconfsimulator/src/test/java/org/onap/netconfsimulator/kafka/StoreServiceTest.java b/netconfsimulator/src/test/java/org/onap/netconfsimulator/kafka/StoreServiceTest.java new file mode 100644 index 0000000..fd36116 --- /dev/null +++ b/netconfsimulator/src/test/java/org/onap/netconfsimulator/kafka/StoreServiceTest.java @@ -0,0 +1,103 @@ +/*- + * ============LICENSE_START======================================================= + * Simulator + * ================================================================================ + * Copyright (C) 2019 Nokia. 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.netconfsimulator.kafka; + +import org.bitbucket.radistao.test.annotation.BeforeAllMethods; +import org.bitbucket.radistao.test.runner.BeforeAfterSpringTestRunner; +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.test.context.EmbeddedKafka; +import org.springframework.kafka.test.rule.EmbeddedKafkaRule; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(BeforeAfterSpringTestRunner.class) +@SpringBootTest(classes = {StoreService.class, EmbeddedKafkaConfig.class}) +@EmbeddedKafka +public class StoreServiceTest { + + private static final String MESSAGE_1 = "message1"; + private static final String MESSAGE_2 = "message2"; + private static final String MESSAGE_3 = "message3"; + + @ClassRule + public static EmbeddedKafkaRule embeddedKafka = new EmbeddedKafkaRule(1, true, 1, "config"); + + @Autowired + StoreService service; + + @Autowired + KafkaTemplate<String, String> kafkaTemplate; + + @BeforeAllMethods + public void setupBeforeAll() { + prepareProducer(); + } + + @Test + public void testShouldReturnAllAvailableMessages(){ + + List<MessageDTO> actualMessages = service.getAllMessages(); + + assertResponseContainsExpectedMessages(actualMessages, 3, MESSAGE_1, MESSAGE_2, MESSAGE_3); + } + + @Test + public void testShouldGetLastMessagesRespectingOffset(){ + + List<MessageDTO> wantedLastMsg = service.getLastMessages(1L); + + assertResponseContainsExpectedMessages(wantedLastMsg, 1, MESSAGE_3); + } + + @Test + public void testShouldGetAll3Messages() { + List<MessageDTO> wantedLastMsgs = service.getLastMessages(3L); + + assertResponseContainsExpectedMessages(wantedLastMsgs, 3, MESSAGE_1, MESSAGE_2, MESSAGE_3); + } + + private void prepareProducer(){ + kafkaTemplate.send("config", "message1"); + kafkaTemplate.send("config", "message2"); + kafkaTemplate.send("config", "message3"); + } + + private void assertResponseContainsExpectedMessages(List<MessageDTO> actualMessages, int expectedMessageCount, String... expectedMessages){ + assertThat(actualMessages.stream().map(MessageDTO::getConfiguration)) + .hasSize(expectedMessageCount) + .containsExactly(expectedMessages); + } + +} + + + + + + + diff --git a/netconfsimulator/src/test/java/org/onap/netconfsimulator/kafka/listener/KafkaListenerHandlerTest.java b/netconfsimulator/src/test/java/org/onap/netconfsimulator/kafka/listener/KafkaListenerHandlerTest.java new file mode 100644 index 0000000..fcb7266 --- /dev/null +++ b/netconfsimulator/src/test/java/org/onap/netconfsimulator/kafka/listener/KafkaListenerHandlerTest.java @@ -0,0 +1,87 @@ +/*- + * ============LICENSE_START======================================================= + * Simulator + * ================================================================================ + * Copyright (C) 2019 Nokia. 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.netconfsimulator.kafka.listener; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.MockitoAnnotations.initMocks; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.springframework.kafka.core.ConsumerFactory; +import org.springframework.kafka.listener.ContainerProperties; +import org.springframework.kafka.listener.KafkaMessageListenerContainer; +import org.springframework.kafka.listener.MessageListener; + +class KafkaListenerHandlerTest { + + private static final String CLIENT_ID_REGEX = "[0-9]{10,}"; + private static final String SAMPLE_TOPIC = "sampleTopic"; + + @Mock + private ConsumerFactory<String, String> consumerFactory; + + @Mock + private KafkaMessageListenerContainer<String, String> kafkaMessageListenerContainer; + + @Mock + private MessageListener messageListener; + + @BeforeEach + void setUp() { + initMocks(this); + } + + + @Test + void shouldProperlyCreateKafkaListener() { + KafkaListenerHandler kafkaListenerHandler = spy(new KafkaListenerHandler(consumerFactory)); + doReturn(kafkaMessageListenerContainer).when(kafkaListenerHandler) + .createListenerContainer(any(ContainerProperties.class), eq(SAMPLE_TOPIC)); + + KafkaListenerEntry kafkaListenerEntry = kafkaListenerHandler + .createKafkaListener(messageListener, SAMPLE_TOPIC); + + assertThat(kafkaListenerEntry.getListenerContainer()).isEqualTo(kafkaMessageListenerContainer); + assertThat(kafkaListenerEntry.getClientId()).matches(CLIENT_ID_REGEX); + } + + @Test + void shouldProperlyCreateContainer() { + KafkaListenerHandler kafkaListenerHandler = spy(new KafkaListenerHandler(consumerFactory)); + ContainerProperties containerProperties = new ContainerProperties(SAMPLE_TOPIC); + containerProperties.setMessageListener(mock(MessageListener.class)); + + KafkaMessageListenerContainer<String, String> listenerContainer = kafkaListenerHandler + .createListenerContainer(containerProperties, SAMPLE_TOPIC); + + ContainerProperties actualProperties = listenerContainer.getContainerProperties(); + assertThat(actualProperties.getTopics()).isEqualTo(containerProperties.getTopics()); + assertThat(actualProperties.getMessageListener()).isEqualTo(containerProperties.getMessageListener()); + } + + +} diff --git a/netconfsimulator/src/test/java/org/onap/netconfsimulator/netconfcore/NetconfControllerTest.java b/netconfsimulator/src/test/java/org/onap/netconfsimulator/netconfcore/NetconfControllerTest.java new file mode 100644 index 0000000..73fb627 --- /dev/null +++ b/netconfsimulator/src/test/java/org/onap/netconfsimulator/netconfcore/NetconfControllerTest.java @@ -0,0 +1,172 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 Nokia. 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.netconfsimulator.netconfcore; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +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 static org.mockito.MockitoAnnotations.initMocks; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.tailf.jnc.JNCException; +import java.io.IOException; +import java.nio.file.Files; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.onap.netconfsimulator.netconfcore.configuration.NetconfConfigurationService; +import org.onap.netconfsimulator.netconfcore.model.LoadModelResponse; +import org.onap.netconfsimulator.netconfcore.model.NetconfModelLoaderService; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.util.ResourceUtils; +import org.springframework.web.multipart.MultipartFile; + +class NetconfControllerTest { + + private MockMvc mockMvc; + + @Mock + private NetconfConfigurationService netconfService; + + @Mock + private NetconfModelLoaderService netconfModelLoaderService; + + @InjectMocks + private NetconfController controller; + + private static final String SAMPLE_CONFIGURATION = "<config xmlns=\"http://onap.org/pnf-simulator\" xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><itemValue1>11</itemValue1><itemValue2>22</itemValue2></config>"; + + @BeforeEach + void setUp() { + initMocks(this); + mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); + } + + @Test + void testShouldDigestMultipartFile() throws Exception { + byte[] bytes = + Files.readAllBytes(ResourceUtils.getFile("classpath:updatedConfig.xml").toPath()); + MockMultipartFile file = new MockMultipartFile("editConfigXml", bytes); + + mockMvc + .perform(MockMvcRequestBuilders.multipart("/netconf/edit-config").file(file)) + .andExpect(status().isAccepted()); + + verify(netconfService).editCurrentConfiguration(any(MultipartFile.class)); + } + + @Test + void testShouldThrowExceptionWhenEditConfigFileWithIncorrectNameProvided() throws Exception { + MockMultipartFile file = new MockMultipartFile("wrongName", new byte[0]); + + mockMvc + .perform(MockMvcRequestBuilders.multipart("/netconf/edit-config").file(file)) + .andExpect(status().isBadRequest()); + + verify(netconfService, never()).editCurrentConfiguration(any(MultipartFile.class)); + } + + @Test + void testShouldReturnCurrentConfiguration() throws Exception { + when(netconfService.getCurrentConfiguration()).thenReturn(SAMPLE_CONFIGURATION); + + String contentAsString = + mockMvc + .perform(get("/netconf/get")) + .andExpect(status().isOk()) + .andReturn() + .getResponse() + .getContentAsString(); + + verify(netconfService).getCurrentConfiguration(); + assertThat(contentAsString).isEqualTo(SAMPLE_CONFIGURATION); + } + + @Test + void testShouldReturnConfigurationForGivenPath() throws Exception { + when(netconfService.getCurrentConfiguration("sampleModel", "sampleContainer")) + .thenReturn(SAMPLE_CONFIGURATION); + + String contentAsString = + mockMvc + .perform(get("/netconf/get/sampleModel/sampleContainer")) + .andExpect(status().isOk()) + .andReturn() + .getResponse() + .getContentAsString(); + + verify(netconfService).getCurrentConfiguration("sampleModel", "sampleContainer"); + assertThat(contentAsString).isEqualTo(SAMPLE_CONFIGURATION); + } + + @Test + void testShouldRaiseBadRequestWhenConfigurationIsNotPresent() throws Exception { + when(netconfService.getCurrentConfiguration("sampleModel", "sampleContainer2")) + .thenThrow(new JNCException(JNCException.ELEMENT_MISSING, "/sampleModel:sampleContainer2")); + + String contentAsString = + mockMvc + .perform(get("/netconf/get/sampleModel/sampleContainer2")) + .andExpect(status().isBadRequest()) + .andReturn() + .getResponse() + .getContentAsString(); + + assertThat(contentAsString).isEqualTo("Element does not exists: /sampleModel:sampleContainer2"); + } + + @Test + void shouldThrowExceptionWhenNoConfigurationPresent() throws IOException, JNCException { + when(netconfService.getCurrentConfiguration()).thenThrow(JNCException.class); + + assertThatThrownBy(() -> mockMvc.perform(get("/netconf/get"))) + .hasRootCauseExactlyInstanceOf(JNCException.class); + } + + @Test + void testShouldDeleteYangModel() throws Exception { + String responseOkString = "Alles klar"; + String yangModelName = "someModel"; + LoadModelResponse loadModelResponse = new LoadModelResponse(200, responseOkString); + String uri = String.format("/netconf/model/%s", yangModelName); + when(netconfModelLoaderService.deleteYangModel(yangModelName)).thenReturn(loadModelResponse); + + String contentAsString = + mockMvc + .perform(delete(uri)) + .andExpect(status().isOk()) + .andReturn() + .getResponse() + .getContentAsString(); + + verify(netconfModelLoaderService).deleteYangModel(yangModelName); + assertThat(contentAsString).isEqualTo(responseOkString); + } +} diff --git a/netconfsimulator/src/test/java/org/onap/netconfsimulator/netconfcore/configuration/NetconfConfigurationEditorTest.java b/netconfsimulator/src/test/java/org/onap/netconfsimulator/netconfcore/configuration/NetconfConfigurationEditorTest.java new file mode 100644 index 0000000..371bdd8 --- /dev/null +++ b/netconfsimulator/src/test/java/org/onap/netconfsimulator/netconfcore/configuration/NetconfConfigurationEditorTest.java @@ -0,0 +1,69 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 Nokia. 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.netconfsimulator.netconfcore.configuration; + +import com.tailf.jnc.Element; +import com.tailf.jnc.JNCException; +import com.tailf.jnc.NetconfSession; +import com.tailf.jnc.XMLParser; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.netconfsimulator.netconfcore.configuration.NetconfConfigurationEditor; +import org.springframework.util.ResourceUtils; +import org.xml.sax.InputSource; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.nio.file.Files; + +import static org.mockito.Mockito.verify; +import static org.mockito.MockitoAnnotations.initMocks; + +class NetconfConfigurationEditorTest { + + @Mock + private NetconfSession session; + @Mock + private NetconfSessionHelper netconfSessionHelper; + + private NetconfConfigurationEditor editor; + + @BeforeEach + void setUp() throws IOException, JNCException { + initMocks(this); + NetconfConnectionParams params = null; + Mockito.when(netconfSessionHelper.createNetconfSession(params)).thenReturn(session); + editor = new NetconfConfigurationEditor(params, netconfSessionHelper); + } + + @Test + void testShouldEditConfigSuccessfully() throws IOException, JNCException { + byte[] bytes = + Files.readAllBytes(ResourceUtils.getFile("classpath:updatedConfig.xml").toPath()); + Element editConfigXml = new XMLParser().parse(new InputSource(new ByteArrayInputStream(bytes))); + + editor.editConfig(editConfigXml); + + verify(session).editConfig(editConfigXml); + } +} diff --git a/netconfsimulator/src/test/java/org/onap/netconfsimulator/netconfcore/configuration/NetconfConfigurationReaderTest.java b/netconfsimulator/src/test/java/org/onap/netconfsimulator/netconfcore/configuration/NetconfConfigurationReaderTest.java new file mode 100644 index 0000000..a0a15b9 --- /dev/null +++ b/netconfsimulator/src/test/java/org/onap/netconfsimulator/netconfcore/configuration/NetconfConfigurationReaderTest.java @@ -0,0 +1,94 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 Nokia. 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.netconfsimulator.netconfcore.configuration; + +import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.times; +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.Mockito; +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 NetconfSessionHelper netconfSessionHelper; + + @Mock + private NodeSet nodeSet; + + @Mock + private Element element; + + @BeforeEach + void setUp() throws IOException, JNCException { + MockitoAnnotations.initMocks(this); + NetconfConnectionParams params = null; + Mockito.when(netconfSessionHelper.createNetconfSession(params)).thenReturn(netconfSession); + reader = new NetconfConfigurationReader(params, netconfSessionHelper); + } + + @Test + void properlyReadXML() throws IOException, JNCException { + when(netconfSession.getConfig()).thenReturn(nodeSet); + when(nodeSet.toXMLString()).thenReturn(EXPECTED_STRING_XML); + + String result = reader.getRunningConfig(); + + verify(netconfSession).getConfig(); + verify(nodeSet).toXMLString(); + assertThat(result).isEqualTo(EXPECTED_STRING_XML); + } + + @Test + void shouldProperlyReadXmlByName() throws IOException, JNCException { + when(netconfSession.getConfig("/sample:test")).thenReturn(nodeSet); + when(nodeSet.first()).thenReturn(element); + when(element.toXMLString()).thenReturn(EXPECTED_STRING_XML); + + String result = reader.getRunningConfig("/sample:test"); + + verify(netconfSession).getConfig("/sample:test"); + verify(nodeSet, times(2)).first(); + verify(element).toXMLString(); + + assertThat(result).isEqualTo(EXPECTED_STRING_XML); + } + +} diff --git a/netconfsimulator/src/test/java/org/onap/netconfsimulator/netconfcore/configuration/NetconfConfigurationServiceTest.java b/netconfsimulator/src/test/java/org/onap/netconfsimulator/netconfcore/configuration/NetconfConfigurationServiceTest.java new file mode 100644 index 0000000..6da6572 --- /dev/null +++ b/netconfsimulator/src/test/java/org/onap/netconfsimulator/netconfcore/configuration/NetconfConfigurationServiceTest.java @@ -0,0 +1,102 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 Nokia. 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.netconfsimulator.netconfcore.configuration; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + +import com.tailf.jnc.Element; +import com.tailf.jnc.JNCException; +import java.io.IOException; +import java.nio.file.Files; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.util.ResourceUtils; + +class NetconfConfigurationServiceTest { + + @Mock + NetconfConfigurationReader reader; + + @Mock + NetconfConfigurationEditor editor; + + @InjectMocks + NetconfConfigurationService service; + + private static String CURRENT_CONFIG_XML_STRING = + "<config xmlns=\"http://onap.org/pnf-simulator\" xmlns:nc=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" + + " <itemValue1>100</itemValue1>\n" + + " <itemValue2>200</itemValue2>\n" + + "</config>\n"; + + @BeforeEach + void setUp() { + initMocks(this); + } + + @Test + void testShouldReturnCorrectCurrentConfiguration() throws IOException, JNCException { + String expectedConfiguration = CURRENT_CONFIG_XML_STRING; + when(reader.getRunningConfig()).thenReturn(CURRENT_CONFIG_XML_STRING); + + String actualCurrentConfiguration = service.getCurrentConfiguration(); + + assertThat(actualCurrentConfiguration).isEqualToIgnoringCase(expectedConfiguration); + } + + @Test + void testShouldThrowExceptionWhenCurrentConfigurationDoesNotExists() throws IOException, JNCException{ + when(reader.getRunningConfig()).thenThrow(JNCException.class); + + assertThatThrownBy(() -> service.getCurrentConfiguration()).isInstanceOf(JNCException.class); + } + + @Test + void testShouldEditConfigurationSuccessfully() throws IOException, JNCException{ + byte[] bytes = + Files.readAllBytes(ResourceUtils.getFile("classpath:updatedConfig.xml").toPath()); + MockMultipartFile editConfigXmlContent = new MockMultipartFile("editConfigXml", bytes); + ArgumentCaptor<Element> elementCaptor = ArgumentCaptor.forClass(Element.class); + doNothing().when(editor).editConfig(elementCaptor.capture()); + + service.editCurrentConfiguration(editConfigXmlContent); + + assertThat(elementCaptor.getValue().toXMLString()).isEqualTo(CURRENT_CONFIG_XML_STRING); + } + + @Test + void testShouldRaiseExceptionWhenMultipartFileIsInvalidXmlFile() throws IOException { + byte[] bytes = + Files.readAllBytes(ResourceUtils.getFile("classpath:invalidXmlFile.xml").toPath()); + MockMultipartFile editConfigXmlContent = new MockMultipartFile("editConfigXml", bytes); + + assertThatThrownBy(() -> service.editCurrentConfiguration(editConfigXmlContent)).isInstanceOf(JNCException.class); + } + +} diff --git a/netconfsimulator/src/test/java/org/onap/netconfsimulator/netconfcore/model/NetconfModelLoaderServiceTest.java b/netconfsimulator/src/test/java/org/onap/netconfsimulator/netconfcore/model/NetconfModelLoaderServiceTest.java new file mode 100644 index 0000000..a10876b --- /dev/null +++ b/netconfsimulator/src/test/java/org/onap/netconfsimulator/netconfcore/model/NetconfModelLoaderServiceTest.java @@ -0,0 +1,121 @@ +/*- + * ============LICENSE_START======================================================= + * Simulator + * ================================================================================ + * Copyright (C) 2019 Nokia. 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.netconfsimulator.netconfcore.model; + + +import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.StatusLine; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpRequestBase; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.web.multipart.MultipartFile; + +class NetconfModelLoaderServiceTest { + + @Mock + private HttpClient httpClient; + + private NetconfModelLoaderService modelLoaderService; + + @BeforeEach + void setUp() { + MockitoAnnotations.initMocks(this); + modelLoaderService = new NetconfModelLoaderService(httpClient); + } + + + @Test + void shouldSendMultipartToServer() throws IOException { + //given + String loadModelAddress = modelLoaderService.getBackendAddress(); + makeMockClientReturnStatusOk(httpClient, HttpPost.class); + ArgumentCaptor<HttpPost> postArgumentCaptor = ArgumentCaptor.forClass(HttpPost.class); + MultipartFile yangMmodel = mock(MultipartFile.class); + MultipartFile initialConfig = mock(MultipartFile.class); + String moduleName = "moduleName"; + when(yangMmodel.getInputStream()).thenReturn(getEmptyImputStream()); + when(initialConfig.getInputStream()).thenReturn(getEmptyImputStream()); + + //when + LoadModelResponse response = modelLoaderService.loadYangModel(yangMmodel, initialConfig, moduleName); + + //then + verify(httpClient).execute(postArgumentCaptor.capture()); + HttpPost sentPost = postArgumentCaptor.getValue(); + assertThat(response.getStatusCode()).isEqualTo(200); + assertThat(response.getMessage()).isEqualTo(""); + assertThat(sentPost.getURI().toString()).isEqualTo(loadModelAddress); + assertThat(sentPost.getEntity().getContentType().getElements()[0].getName()).isEqualTo("multipart/form-data"); + } + + @Test + void shouldSendDeleteRequestToServer() throws IOException { + //given + String yangModelName = "sampleModel"; + String deleteModelAddress = modelLoaderService.getDeleteAddress(yangModelName); + makeMockClientReturnStatusOk(httpClient, HttpDelete.class); + ArgumentCaptor<HttpDelete> deleteArgumentCaptor = ArgumentCaptor.forClass(HttpDelete.class); + + //when + LoadModelResponse response = modelLoaderService.deleteYangModel(yangModelName); + + //then + verify(httpClient).execute(deleteArgumentCaptor.capture()); + HttpDelete sendDelete = deleteArgumentCaptor.getValue(); + assertThat(response.getStatusCode()).isEqualTo(200); + assertThat(response.getMessage()).isEqualTo(""); + assertThat(sendDelete.getURI().toString()).isEqualTo(deleteModelAddress); + } + + private void makeMockClientReturnStatusOk(HttpClient client, + Class<? extends HttpRequestBase> httpMethodClass) throws IOException { + HttpResponse httpResponse = mock(HttpResponse.class); + StatusLine mockStatus = mock(StatusLine.class); + HttpEntity mockEntity = mock(HttpEntity.class); + + when(client.execute(any(httpMethodClass))).thenReturn(httpResponse); + when(httpResponse.getStatusLine()).thenReturn(mockStatus); + when(mockStatus.getStatusCode()).thenReturn(200); + when(httpResponse.getEntity()).thenReturn(mockEntity); + when(mockEntity.getContent()).thenReturn(getEmptyImputStream()); + } + + private InputStream getEmptyImputStream() { + return new ByteArrayInputStream("".getBytes()); + } + +} diff --git a/netconfsimulator/src/test/java/org/onap/netconfsimulator/websocket/NetconfEndpointTest.java b/netconfsimulator/src/test/java/org/onap/netconfsimulator/websocket/NetconfEndpointTest.java new file mode 100644 index 0000000..c1484d4 --- /dev/null +++ b/netconfsimulator/src/test/java/org/onap/netconfsimulator/websocket/NetconfEndpointTest.java @@ -0,0 +1,135 @@ +/*- + * ============LICENSE_START======================================================= + * Simulator + * ================================================================================ + * Copyright (C) 2019 Nokia. 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.netconfsimulator.websocket; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +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.mockito.MockitoAnnotations.initMocks; + +import java.util.Map; +import java.util.Optional; +import javax.websocket.CloseReason; +import javax.websocket.EndpointConfig; +import javax.websocket.RemoteEndpoint; +import javax.websocket.Session; +import org.apache.kafka.common.Metric; +import org.apache.kafka.common.MetricName; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.onap.netconfsimulator.kafka.listener.KafkaListenerEntry; +import org.onap.netconfsimulator.kafka.listener.KafkaListenerHandler; +import org.onap.netconfsimulator.websocket.message.NetconfMessageListener; +import org.springframework.kafka.core.ConsumerFactory; +import org.springframework.kafka.listener.AbstractMessageListenerContainer; + +import org.springframework.kafka.listener.ContainerProperties; +import org.springframework.kafka.listener.GenericMessageListener; + +class NetconfEndpointTest { + + + @Mock + private KafkaListenerHandler kafkaListenerHandler; + + @Mock + private Session session; + + @Mock + private EndpointConfig endpointConfig; + + @Mock + private RemoteEndpoint.Basic remoteEndpoint; + + + @BeforeEach + void setUp() { + initMocks(this); + } + + + @Test + void shouldCreateKafkaListenerWhenClientInitializeConnection() { + NetconfEndpoint netconfEndpoint = new NetconfEndpoint(kafkaListenerHandler); + AbstractMessageListenerContainer abstractMessageListenerContainer = getListenerContainer(); + when(session.getBasicRemote()).thenReturn(remoteEndpoint); + KafkaListenerEntry kafkaListenerEntry = new KafkaListenerEntry("sampleGroupId", + abstractMessageListenerContainer); + when(kafkaListenerHandler.createKafkaListener(any(NetconfMessageListener.class), eq("config"))) + .thenReturn(kafkaListenerEntry); + + netconfEndpoint.onOpen(session, endpointConfig); + + assertThat(netconfEndpoint.getEntry().get().getClientId()).isEqualTo("sampleGroupId"); + assertThat(netconfEndpoint.getEntry().get().getListenerContainer()).isEqualTo(abstractMessageListenerContainer); + + verify(abstractMessageListenerContainer).start(); + } + + + @Test + void shouldCloseListenerWhenClientDisconnects() { + NetconfEndpoint netconfEndpoint = new NetconfEndpoint(kafkaListenerHandler); + AbstractMessageListenerContainer abstractMessageListenerContainer = getListenerContainer(); + netconfEndpoint.setEntry( Optional.of(new KafkaListenerEntry("sampleGroupId", abstractMessageListenerContainer)) ); + + netconfEndpoint.onClose(session, mock(CloseReason.class)); + + verify(abstractMessageListenerContainer).stop(); + } + + class TestAbstractMessageListenerContainer extends AbstractMessageListenerContainer { + + + TestAbstractMessageListenerContainer(ContainerProperties containerProperties) { + super(mock(ConsumerFactory.class),containerProperties); + } + + @Override + protected void doStart() { + + } + + @Override + protected void doStop(Runnable callback) { + + } + + @Override + public Map<String, Map<MetricName, ? extends Metric>> metrics() { + return null; + } + } + + private AbstractMessageListenerContainer getListenerContainer() { + ContainerProperties containerProperties = new ContainerProperties("config"); + containerProperties.setGroupId("sample"); + containerProperties.setMessageListener(mock(GenericMessageListener.class)); + TestAbstractMessageListenerContainer testAbstractMessageListenerContainer = new TestAbstractMessageListenerContainer( + containerProperties); + return spy(testAbstractMessageListenerContainer); + } +} diff --git a/netconfsimulator/src/test/java/org/onap/netconfsimulator/websocket/message/NetconfMessageListenerTest.java b/netconfsimulator/src/test/java/org/onap/netconfsimulator/websocket/message/NetconfMessageListenerTest.java new file mode 100644 index 0000000..bb040d1 --- /dev/null +++ b/netconfsimulator/src/test/java/org/onap/netconfsimulator/websocket/message/NetconfMessageListenerTest.java @@ -0,0 +1,73 @@ +/*- + * ============LICENSE_START======================================================= + * Simulator + * ================================================================================ + * Copyright (C) 2019 Nokia. 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.netconfsimulator.websocket.message; + + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.verify; +import static org.mockito.MockitoAnnotations.initMocks; + +import java.io.IOException; +import javax.websocket.EncodeException; +import javax.websocket.RemoteEndpoint; +import org.apache.kafka.clients.consumer.ConsumerRecord; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.onap.netconfsimulator.kafka.model.KafkaMessage; + + +class NetconfMessageListenerTest { + + private static final ConsumerRecord<String, String> KAFKA_RECORD = new ConsumerRecord<>("sampleTopic", 0, 0, + "sampleKey", "sampleValue"); + + @Mock + private RemoteEndpoint.Basic remoteEndpoint; + + @InjectMocks + private NetconfMessageListener netconfMessageListener; + + + @BeforeEach + void setUp() { + initMocks(this); + } + + + @Test + void shouldProperlyParseAndSendConsumerRecord() throws IOException, EncodeException { + netconfMessageListener.onMessage(KAFKA_RECORD); + + verify(remoteEndpoint).sendObject(any(KafkaMessage.class)); + } + + + + @Test + void shouldNotPropagateEncodeException() throws IOException, EncodeException { + doThrow(new EncodeException("","")).when(remoteEndpoint).sendObject(any(KafkaMessage.class)); + + netconfMessageListener.onMessage(KAFKA_RECORD); + } +} |