diff options
author | Bogumil Zebek <bogumil.zebek@nokia.com> | 2021-03-09 12:54:38 +0100 |
---|---|---|
committer | Zebek Bogumil <bogumil.zebek@nokia.com> | 2021-03-10 09:31:58 +0100 |
commit | 4af5241ab25b0103d8ea680789aaf9a8696dfc75 (patch) | |
tree | 36ccae11ebf094aa1ddd65df309b7531ce0db1ff /src/test | |
parent | c9975cb96ba4e0208e72399ed80f909beb95d9d9 (diff) |
Move pnf simulator to the new repo
In the first phase we renamed project from pnf simulator to vesclient.
Next steps: package rename, update Readme.md, upgrade project dependencies.
Issue-ID: INT-1869
Signed-off-by: Bogumil Zebek<bogumil.zebek@nokia.com>
Change-Id: I7714792f9739eb746c9c533e8ef41b9618a3a1d9
Diffstat (limited to 'src/test')
51 files changed, 4687 insertions, 0 deletions
diff --git a/src/test/java/org/onap/pnfsimulator/event/EventDataServiceTest.java b/src/test/java/org/onap/pnfsimulator/event/EventDataServiceTest.java new file mode 100644 index 0000000..5ed51cc --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/event/EventDataServiceTest.java @@ -0,0 +1,133 @@ +/* + * ============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.pnfsimulator.event; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.hamcrest.collection.IsIterableContainingInOrder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeEach; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; + +public class EventDataServiceTest { + + @Mock + private EventDataRepository repositoryMock; + + @InjectMocks + private EventDataService service; + + private static EventData sampleEventData(String id, String template, + String patched, String input, String keywords) { + return EventData.builder() + .id(id) + .template(template) + .patched(patched) + .input(input) + .keywords(keywords) + .build(); + } + + @BeforeEach + void resetMocks() { + initMocks(this); + } + + @Test + void persistEventDataJsonObjectTest() { + JsonParser parser = new JsonParser(); + JsonObject template = parser.parse("{ \"bla1\": \"bla2\"}").getAsJsonObject(); + JsonObject patched = parser.parse("{ \"bla3\": \"bla4\"}").getAsJsonObject(); + JsonObject input = parser.parse("{ \"bla5\": \"bla6\"}").getAsJsonObject(); + JsonObject keywords = parser.parse("{ \"bla7\": \"bla8\"}").getAsJsonObject(); + ArgumentCaptor<EventData> argumentCaptor = ArgumentCaptor.forClass(EventData.class); + + service.persistEventData(template, patched, input, keywords); + + verify(repositoryMock).save(argumentCaptor.capture()); + EventData captured = argumentCaptor.getValue(); + + assertEquals(captured.getTemplate(), template.toString()); + assertEquals(captured.getPatched(), patched.toString()); + assertEquals(captured.getInput(), input.toString()); + assertEquals(captured.getKeywords(), keywords.toString()); + } + + @Test + void getAllEventsTest() { + + List<EventData> eventDataList = new ArrayList<>(); + EventData ed1 = sampleEventData("id1", "t1", "p1", "i1", "k1"); + EventData ed2 = sampleEventData("id2", "t2", "p2", "i2", "k2"); + eventDataList.add(ed1); + eventDataList.add(ed2); + + when(repositoryMock.findAll()).thenReturn(eventDataList); + List<EventData> actualList = service.getAllEvents(); + + assertEquals(eventDataList.size(), actualList.size()); + assertThat(actualList, IsIterableContainingInOrder.contains(ed1, ed2)); + } + + @Test + void findByIdPresentTest() { + String id = "some_object"; + EventData eventData = sampleEventData(id, "template", "patched", "input", "keywords"); + Optional<EventData> optional = Optional.of(eventData); + + when(repositoryMock.findById(id)).thenReturn(optional); + + Optional<EventData> actualOptional = service.getById(id); + assertTrue(actualOptional.isPresent()); + EventData actualObject = actualOptional.get(); + assertEquals(eventData.getId(), actualObject.getId()); + assertEquals(eventData.getTemplate(), actualObject.getTemplate()); + assertEquals(eventData.getPatched(), actualObject.getPatched()); + assertEquals(eventData.getInput(), actualObject.getInput()); + assertEquals(eventData.getKeywords(), actualObject.getKeywords()); + + } + + @Test + void findByIdNotPresentTest() { + String id = "some_object"; + Optional<EventData> optional = Optional.empty(); + + when(repositoryMock.findById(id)).thenReturn(optional); + + Optional<EventData> actualOptional = service.getById(id); + assertTrue(!actualOptional.isPresent()); + } +} diff --git a/src/test/java/org/onap/pnfsimulator/filesystem/InMemoryTemplateStorage.java b/src/test/java/org/onap/pnfsimulator/filesystem/InMemoryTemplateStorage.java new file mode 100644 index 0000000..b86a0f9 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/filesystem/InMemoryTemplateStorage.java @@ -0,0 +1,71 @@ +/*- + * ============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.pnfsimulator.filesystem; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import com.google.gson.JsonObject; +import org.onap.pnfsimulator.db.Storage; +import org.onap.pnfsimulator.template.Template; + +public class InMemoryTemplateStorage implements Storage<Template> { + + private List<Template> storage = new ArrayList<>(); + + @Override + public List<Template> getAll() { + return new ArrayList<>(storage); + } + + @Override + public Optional<Template> get(String name) { + return storage.stream().filter(template -> template.getId().equals(name)).findFirst(); + } + + @Override + public void persist(Template template) { + if (!storage.contains(template)) { + storage.add(template); + } + } + + @Override + public boolean tryPersistOrOverwrite(Template template, boolean overwrite) { + if (!storage.contains(template) || overwrite) { + storage.add(template); + return true; + } + return false; + } + + @Override + public void delete(String templateName) { + get(templateName).ifPresent(template -> storage.remove(template)); + } + + @Override + public List<String> getIdsByContentCriteria(JsonObject queryJson) { + throw new RuntimeException("Method is not implemented."); + } + +} diff --git a/src/test/java/org/onap/pnfsimulator/filesystem/WatcherEventProcessorTest.java b/src/test/java/org/onap/pnfsimulator/filesystem/WatcherEventProcessorTest.java new file mode 100644 index 0000000..9dfa002 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/filesystem/WatcherEventProcessorTest.java @@ -0,0 +1,125 @@ +/*- + * ============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.pnfsimulator.filesystem; + +import static junit.framework.TestCase.fail; +import static org.mockito.MockitoAnnotations.initMocks; + +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardWatchEventKinds; +import java.nio.file.WatchEvent; +import java.time.Instant; +import java.util.Collections; +import java.util.HashMap; +import java.util.Optional; + +import org.bson.Document; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.pnfsimulator.db.Storage; +import org.onap.pnfsimulator.template.Template; + +class WatcherEventProcessorTest { + + @Mock + private WatchEvent watchEvent; + @Mock + private Path templatesDir; + + private Storage<Template> storage; + private static Path jsonFilePath; + + @BeforeAll + static void init() { + jsonFilePath = Paths.get("src/test/resources/org/onap/pnfsimulator/simulator/filesystem/test1.json"); + } + + @BeforeEach + void resetMocks() { + initMocks(this); + storage = new InMemoryTemplateStorage(); + initStubs(); + } + + @Test + void shouldProcessCreatedEventTest() { + // when + Mockito.when(watchEvent.kind()).thenReturn(StandardWatchEventKinds.ENTRY_CREATE); + WatcherEventProcessor.process(watchEvent, storage, templatesDir); + // then + verifyPersistedValue(); + } + + @Test + void shouldProcessModifiedEventTest() { + //given + storage.persist(new Template("test1.json", new Document(Collections.emptyMap()), Instant.now().getNano())); + // when + Mockito.when(watchEvent.kind()).thenReturn(StandardWatchEventKinds.ENTRY_MODIFY); + WatcherEventProcessor.process(watchEvent, storage, templatesDir); + // then + verifyPersistedValue(); + } + + private void verifyPersistedValue() { + Assertions.assertEquals(1, storage.getAll().size()); + Optional<Template> templateFromStorage = storage.get("test1.json"); + if (templateFromStorage.isPresent()) { + Template retrievedTemplate = templateFromStorage.get(); + Document templateContent = retrievedTemplate.getContent(); + Document flatContent = retrievedTemplate.getFlatContent(); + Assertions.assertEquals("value1", templateContent.getString("field1")); + Assertions.assertEquals(2, templateContent.getInteger("field2", 0)); + Assertions.assertEquals(1, flatContent.getInteger(":nested:key1[0]", 0)); + Assertions.assertEquals(2, flatContent.getInteger(":nested:key1[1]", 0)); + Assertions.assertEquals(3, flatContent.getInteger(":nested:key1[2]", 0)); + Assertions.assertEquals("sampleValue2", flatContent.getString(":nested:key2")); + } else { + fail(); + } + } + + @Test + void shouldProcessDeletedEventTest() { + //given + HashMap<String, Object> legacyObject = new HashMap<>(); + legacyObject.put("field1", "value1"); + legacyObject.put("field2", 2); + + storage.persist(new Template("test1.json", new Document(legacyObject), Instant.now().getNano())); + // when + Mockito.when(watchEvent.kind()).thenReturn(StandardWatchEventKinds.ENTRY_DELETE); + WatcherEventProcessor.process(watchEvent, storage, templatesDir); + // then + Assertions.assertEquals(0, storage.getAll().size()); + } + + private void initStubs() { + Mockito.when(templatesDir.resolve(jsonFilePath)).thenReturn(jsonFilePath); + Mockito.when(watchEvent.context()).thenReturn(jsonFilePath); + } + +} diff --git a/src/test/java/org/onap/pnfsimulator/rest/SimulatorControllerTest.java b/src/test/java/org/onap/pnfsimulator/rest/SimulatorControllerTest.java new file mode 100644 index 0000000..8dba750 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/rest/SimulatorControllerTest.java @@ -0,0 +1,329 @@ +/* + * ============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.pnfsimulator.rest; + +import com.google.common.collect.ImmutableMap; +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.pnfsimulator.event.EventData; +import org.onap.pnfsimulator.event.EventDataService; +import org.onap.pnfsimulator.rest.model.FullEvent; +import org.onap.pnfsimulator.rest.model.SimulatorParams; +import org.onap.pnfsimulator.rest.model.SimulatorRequest; +import org.onap.pnfsimulator.simulator.SimulatorService; +import org.onap.pnfsimulator.simulator.client.HttpResponseAdapter; +import org.onap.pnfsimulator.simulatorconfig.SimulatorConfig; +import org.quartz.SchedulerException; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import java.io.IOException; +import java.net.URL; +import java.security.GeneralSecurityException; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +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.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +class SimulatorControllerTest { + + private static final String START_ENDPOINT = "/simulator/start"; + private static final String CONFIG_ENDPOINT = "/simulator/config"; + private static final String EVENT_ENDPOINT = "/simulator/event"; + private static final String CANCEL_JOB_ENDPOINT = "/simulator/cancel/"; + private static final String ALL_EVENTS_ENDPOINT = "/simulator/all-events"; + private static final String TEST_ENDPOINT = "/simulator/test"; + + private static final String JSON_MSG_EXPRESSION = "$.message"; + private static final String EVENT_WAS_CANCELLED = "Event(s) was cancelled"; + private static final String EVENT_WAS_NOT_CANCELLED = "Simulator was not able to cancel event(s)"; + + private static final String NEW_URL = "http://0.0.0.0:8090/eventListener/v7"; + private static final String UPDATE_SIM_CONFIG_VALID_JSON = "{\"vesServerUrl\": \"" + + NEW_URL + "\"}"; + private static final String SAMPLE_ID = "sampleId"; + private static final Gson GSON_OBJ = new Gson(); + private static final String JOB_NAME = "testJobName"; + private static final HttpResponseAdapter TEST_HTTP_ACCEPTED_RESPONSE = new HttpResponseAdapter(202,""); + private static String simulatorRequestBody; + private MockMvc mockMvc; + @InjectMocks + private SimulatorController controller; + @Mock + private EventDataService eventDataService; + @Mock + private SimulatorService simulatorService; + + @BeforeAll + static void beforeAll() { + SimulatorParams simulatorParams = new SimulatorParams("http://0.0.0.0:8080", 1, 1); + SimulatorRequest simulatorRequest = new SimulatorRequest(simulatorParams, + "testTemplate.json", new JsonObject(), new JsonObject()); + + simulatorRequestBody = GSON_OBJ.toJson(simulatorRequest); + } + + @BeforeEach + void setup() throws IOException, SchedulerException, GeneralSecurityException { + MockitoAnnotations.initMocks(this); + when(simulatorService.triggerEvent(any())).thenReturn("jobName"); + when(simulatorService.triggerOneTimeEvent(any())).thenReturn(TEST_HTTP_ACCEPTED_RESPONSE); + mockMvc = MockMvcBuilders + .standaloneSetup(controller) + .build(); + } + + @Test + void shouldStartSimulatorProperly() throws Exception { + startSimulator(); + SimulatorRequest simulatorRequest = new Gson().fromJson(simulatorRequestBody, SimulatorRequest.class); + + verify(simulatorService).triggerEvent(eq(simulatorRequest)); + } + + @Test + void testShouldGetConfigurationWhenRequested() throws Exception { + String newUrl = "http://localhost:8090/eventListener/v7"; + SimulatorConfig expectedConfig = new SimulatorConfig(SAMPLE_ID, new URL(newUrl)); + when(simulatorService.getConfiguration()).thenReturn(expectedConfig); + + MvcResult getResult = mockMvc + .perform(get(CONFIG_ENDPOINT) + .contentType(MediaType.APPLICATION_JSON) + .content(UPDATE_SIM_CONFIG_VALID_JSON)) + .andExpect(status().isOk()) + .andReturn(); + + String expectedVesUrlJsonPart = createStringReprOfJson("vesServerUrl", newUrl); + assertThat(getResult.getResponse().getContentAsString()).contains(expectedVesUrlJsonPart); + } + + @Test + void testShouldSuccessfullyUpdateConfigurationWithNewVesUrl() throws Exception { + String oldUrl = "http://localhost:8090/eventListener/v7"; + SimulatorConfig expectedConfigBeforeUpdate = new SimulatorConfig(SAMPLE_ID, new URL(oldUrl)); + SimulatorConfig expectedConfigAfterUpdate = new SimulatorConfig(SAMPLE_ID, new URL(NEW_URL)); + + when(simulatorService.getConfiguration()).thenReturn(expectedConfigBeforeUpdate); + when(simulatorService.updateConfiguration(any(SimulatorConfig.class))).thenReturn(expectedConfigAfterUpdate); + + MvcResult postResult = mockMvc + .perform(put(CONFIG_ENDPOINT) + .contentType(MediaType.APPLICATION_JSON) + .content(UPDATE_SIM_CONFIG_VALID_JSON)) + .andExpect(status().isOk()) + .andReturn(); + + String expectedVesUrlJsonPart = createStringReprOfJson("vesServerUrl", expectedConfigAfterUpdate.getVesServerUrl().toString()); + assertThat(postResult.getResponse().getContentAsString()).contains(expectedVesUrlJsonPart); + } + + @Test + void testShouldRaiseExceptionWhenUpdateConfigWithIncorrectPayloadWasSent() throws Exception { + mockMvc + .perform(put(CONFIG_ENDPOINT) + .contentType(MediaType.APPLICATION_JSON) + .content("{\"vesUrl\": \"" + + NEW_URL + "\"}")) + .andExpect(status().isBadRequest()); + } + + @Test + void testShouldRaiseExceptionWhenUrlInInvalidFormatIsSent() throws Exception { + mockMvc + .perform(put(CONFIG_ENDPOINT) + .contentType(MediaType.APPLICATION_JSON) + .content("{\"vesUrl\": \"http://0.0.0.0:VES-PORT/eventListener/v7\"}")) + .andExpect(status().isBadRequest()); + } + + @Test + void testShouldSendEventDirectly() throws Exception { + String contentAsString = mockMvc + .perform(post(EVENT_ENDPOINT) + .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE) + .content("{\"vesServerUrl\":\"http://0.0.0.0:8080/simulator/v7\",\n" + + " \"event\":{ \n" + + " \"commonEventHeader\":{ \n" + + " \"domain\":\"notification\",\n" + + " \"eventName\":\"vFirewallBroadcastPackets\"\n" + + " },\n" + + " \"notificationFields\":{ \n" + + " \"arrayOfNamedHashMap\":[ \n" + + " { \n" + + " \"name\":\"A20161221.1031-1041.bin.gz\",\n" + + " \"hashMap\":{ \n" + + " \"fileformatType\":\"org.3GPP.32.435#measCollec\"}}]}}}")) + .andExpect(status().isAccepted()).andReturn().getResponse().getContentAsString(); + assertThat(contentAsString).contains("One-time direct event sent successfully"); + } + + @Test + void testShouldReplaceKeywordsAndSendEventDirectly() throws Exception { + String contentAsString = mockMvc + .perform(post(EVENT_ENDPOINT) + .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE) + .content("{\"vesServerUrl\": \"http://localhost:9999/eventListener\",\n" + + " \"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"eventId\": \"#RandomString(20)\",\n" + + " \"sourceName\": \"PATCHED_sourceName\",\n" + + " \"version\": 3.0\n}}}")) + .andExpect(status().isAccepted()).andReturn().getResponse().getContentAsString(); + assertThat(contentAsString).contains("One-time direct event sent successfully"); + + verify(simulatorService, Mockito.times(1)).triggerOneTimeEvent(any(FullEvent.class)); + } + + @Test + void shouldUseTestEndpointThenReceiveProperMessage() throws Exception { + String contentAsString = mockMvc + .perform(post(TEST_ENDPOINT) + .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE) + .content("{\"simulatorParams\": {\n" + + " \"vesServerUrl\": \"http://localhost:9999/eventListener\"\n" + + " },\n" + + " \"templateName\": \"testTemplateName\"\n" + + "}")) + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + assertThat(contentAsString).contains("message1234"); + } + + @Test + void shouldSuccessfullyCancelJobThenReturnProperMessage() throws Exception { + when(simulatorService.cancelEvent(JOB_NAME)).thenReturn(true); + + String contentAsString = mockMvc + .perform(post(CANCEL_JOB_ENDPOINT + JOB_NAME) + .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE) + .content("")) + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + + assertThat(contentAsString).contains(EVENT_WAS_CANCELLED); + } + + @Test + void shouldFailWhileCancelingJobThenReturnProperMessage() throws Exception { + when(simulatorService.cancelEvent(JOB_NAME)).thenReturn(false); + + String contentAsString = mockMvc + .perform(post(CANCEL_JOB_ENDPOINT + JOB_NAME) + .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE) + .content("")) + .andExpect(status().isNotFound()).andReturn().getResponse().getContentAsString(); + + assertThat(contentAsString).contains(EVENT_WAS_NOT_CANCELLED); + } + + @Test + void shouldSuccessfullyCancelAllJobsThenReturnsProperMessage() throws Exception { + when(simulatorService.cancelAllEvents()).thenReturn(true); + + String contentAsString = mockMvc + .perform(post(CANCEL_JOB_ENDPOINT) + .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE) + .content("")) + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + + assertThat(contentAsString).contains(EVENT_WAS_CANCELLED); + } + + @Test + void shouldSuccessfullyCancelJobWhenSendingJobNameWithBreakingCharactersThenReturnProperMessage() throws SchedulerException { + final String lineBreakingJobName = "test\tJob\nName\r"; + when(simulatorService.cancelEvent(lineBreakingJobName)).thenReturn(true); + + Object actualResponseBody = Objects.requireNonNull(controller.cancelEvent(lineBreakingJobName).getBody()); + + assertThat(actualResponseBody.toString()).contains(EVENT_WAS_CANCELLED); + } + + @Test + void shouldReturnAllEvents() throws Exception { + List<EventData> events = getEventDatas(); + String expectedMessage = events.stream() + .map(EventData::toString) + .collect(Collectors.joining("\\n")); + + when(eventDataService.getAllEvents()).thenReturn(events); + + String contentAsString = mockMvc + .perform(get(ALL_EVENTS_ENDPOINT) + .contentType(MediaType.APPLICATION_JSON) + .content("")) + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + + assertThat(contentAsString).contains(expectedMessage); + } + + + private List<EventData> getEventDatas() { + return Arrays.asList( + getEventData("id1", "keywords1", "input1", "patched1", "template1", 0), + getEventData("id2", "keywords2", "input2", "patched2", "template2", 1) + ); + } + + private EventData getEventData(String id, String keywords, String input, String patched, String template, int incrementValue) { + return EventData.builder() + .id(id) + .keywords(keywords) + .input(input) + .patched(patched) + .template(template) + .incrementValue(incrementValue) + .build(); + } + + private void startSimulator() throws Exception { + mockMvc + .perform(post(START_ENDPOINT) + .content(simulatorRequestBody) + .contentType(MediaType.APPLICATION_JSON).characterEncoding("utf-8")) + .andExpect(status().isOk()) + .andExpect(jsonPath(JSON_MSG_EXPRESSION).value("Request started")); + + } + + private String createStringReprOfJson(String key, String value) { + return GSON_OBJ.toJson(ImmutableMap.of(key, value)); + } +} diff --git a/src/test/java/org/onap/pnfsimulator/rest/TemplateControllerTest.java b/src/test/java/org/onap/pnfsimulator/rest/TemplateControllerTest.java new file mode 100644 index 0000000..17be475 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/rest/TemplateControllerTest.java @@ -0,0 +1,256 @@ +/*- + * ============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.pnfsimulator.rest; + +import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.onap.pnfsimulator.rest.TemplateController.CANNOT_OVERRIDE_TEMPLATE_MSG; +import static org.onap.pnfsimulator.rest.TemplateController.TEMPLATE_NOT_FOUND_MSG; +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.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.mockito.Mockito.times; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; +import com.google.gson.reflect.TypeToken; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +import org.assertj.core.util.Lists; +import org.bson.Document; +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.db.Storage; +import org.onap.pnfsimulator.rest.model.SearchExp; +import org.onap.pnfsimulator.template.Template; +import org.onap.pnfsimulator.template.search.IllegalJsonValueException; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + + +class TemplateControllerTest { + + private static final String LIST_URL = "/template/list"; + private static final String GET_FORMAT_STR = "/template/get/%s"; + private static final String SEARCH_ENDPOINT = "/template/search"; + private static final String UPLOAD_URL_NOFORCE = "/template/upload"; + private static final String UPLOAD_URL_FORCE = "/template/upload?override=true"; + private static final String SAMPLE_TEMPLATE_JSON = "{\"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": \"measurementsForVfScaling\",\n" + + " \"eventName\": \"vFirewallBroadcastPackets\",\n" + + " }" + + "}}"; + + public static final String TEMPLATE_REQUEST = "{\n" + + " \"name\": \"someTemplate\",\n" + + " \"template\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": \"notification\",\n" + + " \"eventName\": \"vFirewallBroadcastPackets\"\n" + + " },\n" + + " \"notificationFields\": {\n" + + " \"arrayOfNamedHashMap\": [{\n" + + " \"name\": \"A20161221.1031-1041.bin.gz\",\n" + + "\n" + + " \"hashMap\": {\n" + + " \"fileformatType\": \"org.3GPP.32.435#measCollec\"\n" + + " }\n" + + " }]\n" + + " }\n" + + " }\n" + + "}"; + private static final Document SAMPLE_TEMPLATE_BSON = Document.parse(SAMPLE_TEMPLATE_JSON); + private static final List<String> SAMPLE_TEMPLATE_NAME_LIST = Lists.newArrayList("notification.json", "registration.json"); + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + private static final Gson GSON_OBJ = new GsonBuilder().create(); + private MockMvc mockMvc; + + @Mock + private Storage<Template> templateService; + @InjectMocks + private TemplateController controller; + + @BeforeEach + void setup() { + MockitoAnnotations.initMocks(this); + mockMvc = MockMvcBuilders + .standaloneSetup(controller) + .build(); + } + + @Test + void shouldGetAllTemplates() throws Exception { + List<Template> templateList = createTemplatesList(); + when(templateService.getAll()).thenReturn(templateList); + + MvcResult getResult = mockMvc + .perform(get(LIST_URL) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andReturn(); + + Type listType = new TypeToken<ArrayList<Template>>() {}.getType(); + List<Template> resultList = GSON_OBJ.fromJson(getResult.getResponse().getContentAsString(), listType); + assertThat(resultList).containsExactlyInAnyOrderElementsOf(templateList); + } + + @Test + void shouldListEmptyCollectionWhenNoTemplatesAvailable() throws Exception { + List<Template> templateList = Collections.emptyList(); + when(templateService.getAll()).thenReturn(templateList); + + MvcResult getResult = mockMvc + .perform(get(LIST_URL)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andReturn(); + + String templatesAsString = GSON_OBJ.toJson(templateList); + assertThat(getResult.getResponse().getContentAsString()).containsSequence(templatesAsString); + } + + @Test + void shouldSuccessfullyGetExisitngTemplateByName() throws Exception { + String sampleTemplateName = "someTemplate"; + String requestUrl = String.format(GET_FORMAT_STR, sampleTemplateName); + Template sampleTemplate = new Template(sampleTemplateName, SAMPLE_TEMPLATE_BSON, 0L); + + when(templateService.get(sampleTemplateName)).thenReturn(Optional.of(sampleTemplate)); + + MvcResult getResult = mockMvc + .perform(get(requestUrl)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andReturn(); + + Template result = new Gson().fromJson(getResult.getResponse().getContentAsString(), Template.class); + assertThat(result).isEqualTo(sampleTemplate); + } + + @Test + void shouldReturnNotFoundWhenGetNonExisitngTemplateByName() throws Exception { + String sampleTemplateName = "doesNotExist"; + String requestUrl = String.format(GET_FORMAT_STR, sampleTemplateName); + + when(templateService.get(sampleTemplateName)).thenReturn(Optional.empty()); + + MvcResult getResult = mockMvc + .perform(get(requestUrl)) + .andExpect(status().isNotFound()) + .andExpect(content().contentType(MediaType.TEXT_PLAIN_VALUE)) + .andReturn(); + + assertThat(getResult.getResponse().getContentLength()).isEqualTo(TEMPLATE_NOT_FOUND_MSG.length()); + } + + + @Test + void shouldReturnNamesOfTemplatesThatSatisfyGivenCriteria() throws Exception { + when(templateService.getIdsByContentCriteria(any(JsonObject.class))).thenReturn(SAMPLE_TEMPLATE_NAME_LIST); + SearchExp expr = new SearchExp(new JsonObject()); + + String responseContent = mockMvc + .perform(post(SEARCH_ENDPOINT).content(GSON_OBJ.toJson(expr)).contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andReturn().getResponse().getContentAsString(); + + List<String> actualTemplates = OBJECT_MAPPER.readValue(responseContent, new TypeReference<List<String>>() {}); + verify(templateService, times(1)).getIdsByContentCriteria(any(JsonObject.class)); + assertThat(actualTemplates).isEqualTo(SAMPLE_TEMPLATE_NAME_LIST); + } + + @Test + void shouldRaiseBadRequestWhenNullValueProvidedInSearchJsonAsJsonValue() throws Exception { + when(templateService.getIdsByContentCriteria(any(JsonObject.class))).thenThrow(IllegalJsonValueException.class); + SearchExp expr = new SearchExp(new JsonObject()); + + mockMvc.perform(post(SEARCH_ENDPOINT) + .content(GSON_OBJ.toJson(expr)) + .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(status().isBadRequest()); + } + + + @Test + void testTryUploadNewTemplate() throws Exception { + when(templateService.tryPersistOrOverwrite(any(Template.class), eq(false))).thenReturn(true); + + MvcResult postResult = mockMvc + .perform(post(UPLOAD_URL_NOFORCE) + .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE) + .content(TEMPLATE_REQUEST)) + .andExpect(status().isCreated()) + .andReturn(); + } + + @Test + void testTryUploadNewTemplateWithForce() throws Exception { + when(templateService.tryPersistOrOverwrite(any(Template.class), eq(true))).thenReturn(true); + + MvcResult postResult = mockMvc + .perform(post(UPLOAD_URL_FORCE) + .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE) + .content(TEMPLATE_REQUEST)) + .andExpect(status().isCreated()) + .andReturn(); + } + + @Test + void testOverrideExistingTemplateWithoutForceShouldFail() throws Exception { + when(templateService.tryPersistOrOverwrite(any(Template.class), eq(true))).thenReturn(false); + + MvcResult postResult = mockMvc + .perform(post(UPLOAD_URL_FORCE) + .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE) + .content(TEMPLATE_REQUEST)) + .andExpect(status().isConflict()) + .andReturn(); + + assertThat(postResult.getResponse().getContentAsString()).isEqualTo(CANNOT_OVERRIDE_TEMPLATE_MSG); + } + + private List<Template> createTemplatesList() { + return Arrays.asList( + new Template("1", SAMPLE_TEMPLATE_BSON, 0L), + new Template("2", SAMPLE_TEMPLATE_BSON, 0L), + new Template("3", SAMPLE_TEMPLATE_BSON, 0L)); + } +} diff --git a/src/test/java/org/onap/pnfsimulator/rest/util/DateUtilTest.java b/src/test/java/org/onap/pnfsimulator/rest/util/DateUtilTest.java new file mode 100644 index 0000000..1591a59 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/rest/util/DateUtilTest.java @@ -0,0 +1,38 @@ +/* + * ============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.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"))); + } +} diff --git a/src/test/java/org/onap/pnfsimulator/rest/util/ResponseBuilderTest.java b/src/test/java/org/onap/pnfsimulator/rest/util/ResponseBuilderTest.java new file mode 100644 index 0000000..4e8e4dc --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/rest/util/ResponseBuilderTest.java @@ -0,0 +1,66 @@ +/* + * ============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.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; + +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(SAMPLE_STATUS, responseEntity.getStatusCode()), + () -> 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)) + ); + } + + +} diff --git a/src/test/java/org/onap/pnfsimulator/simulator/DbTemplateReaderTest.java b/src/test/java/org/onap/pnfsimulator/simulator/DbTemplateReaderTest.java new file mode 100644 index 0000000..c3f85f5 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/simulator/DbTemplateReaderTest.java @@ -0,0 +1,81 @@ +/*- + * ============LICENSE_START======================================================= + * Simulator + * ================================================================================ + * Copyright (C) 2020 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.pnfsimulator.simulator; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import org.assertj.core.api.Assertions; +import org.bson.Document; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.onap.pnfsimulator.template.Template; +import org.onap.pnfsimulator.template.TemplateService; + +import java.io.IOException; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class DbTemplateReaderTest { + + public static final String SOME_TEMPLATE = "someTemplate"; + public static final String KEY = "key"; + public static final String VALUE = "value"; + public static final long LMOD = 10L; + private TemplateService service; + private DbTemplateReader dbTemplateReader; + + @BeforeEach + void setUp() { + this.service = mock(TemplateService.class); + this.dbTemplateReader = new DbTemplateReader(this.service, new Gson()); + } + + @Test + public void shouldReportErrorWhenTemplateDoesNotExistInTemplateService() { + // given + when(this.service.get(SOME_TEMPLATE)).thenReturn(Optional.empty()); + + // when/then + assertThrows(IOException.class, + () -> this.dbTemplateReader.readTemplate(SOME_TEMPLATE) + ); + } + + @Test + public void shouldReturnTemplateFromService() throws IOException { + // given + Template template = givenTemplate(SOME_TEMPLATE); + when(this.service.get(SOME_TEMPLATE)).thenReturn(Optional.of(template)); + + // when + final JsonObject someTemplate = this.dbTemplateReader.readTemplate(SOME_TEMPLATE); + + // then + Assertions.assertThat(someTemplate).isNotNull(); + Assertions.assertThat(someTemplate.get(KEY).getAsString()).isEqualTo(VALUE); + } + + private Template givenTemplate(String templateName) { + return new Template(templateName, new Document(KEY, VALUE), LMOD); + } +} diff --git a/src/test/java/org/onap/pnfsimulator/simulator/IncrementProviderImplTest.java b/src/test/java/org/onap/pnfsimulator/simulator/IncrementProviderImplTest.java new file mode 100644 index 0000000..b5304a7 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/simulator/IncrementProviderImplTest.java @@ -0,0 +1,79 @@ +/* + * ============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.pnfsimulator.simulator; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Optional; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.onap.pnfsimulator.event.EventData; +import org.onap.pnfsimulator.event.EventDataRepository; + +public class IncrementProviderImplTest { + private IncrementProvider incrementProvider; + + @Mock + private EventDataRepository eventDataRepositoryMock; + + @BeforeEach + void setUp() { + eventDataRepositoryMock = mock(EventDataRepository.class); + incrementProvider = new IncrementProviderImpl(eventDataRepositoryMock); + } + + @Test + public void getAndIncrementTest() { + ArgumentCaptor<EventData> eventDataArgumentCaptor = ArgumentCaptor.forClass(EventData.class); + String eventId = "1"; + int initialIncrementValue = 0; + int expectedValue = initialIncrementValue + 1; + EventData eventData = EventData.builder().id(eventId).incrementValue(initialIncrementValue).build(); + Optional<EventData> optional = Optional.of(eventData); + + when(eventDataRepositoryMock.findById(eventId)).thenReturn(optional); + + int value = incrementProvider.getAndIncrement(eventId); + + verify(eventDataRepositoryMock).save(eventDataArgumentCaptor.capture()); + + assertThat(value).isEqualTo(expectedValue); + assertThat(eventDataArgumentCaptor.getValue().getIncrementValue()).isEqualTo(expectedValue); + + } + + @Test + public void shouldThrowOnNonExistingEvent() { + Optional<EventData> emptyOptional = Optional.empty(); + String nonExistingEventId = "THIS_DOES_NOT_EXIST"; + when(eventDataRepositoryMock.findById(nonExistingEventId)).thenReturn(emptyOptional); + + assertThrows(EventNotFoundException.class, + () -> incrementProvider.getAndIncrement(nonExistingEventId)); + } +} diff --git a/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorInvalidRandomIntegerTest.java b/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorInvalidRandomIntegerTest.java new file mode 100644 index 0000000..8198e95 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorInvalidRandomIntegerTest.java @@ -0,0 +1,67 @@ +/* + * ============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.pnfsimulator.simulator; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Arrays; +import java.util.Collection; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class KeywordsExtractorInvalidRandomIntegerTest { + + private final String keyword; + private KeywordsExtractor keywordsExtractor; + + private static final Collection INVALID_INTEGER_KEYWORDS = Arrays.asList(new Object[][]{ + {"#RandoInteger"}, + {"#Randominteger(23,11)"}, + {"#randomInteger(11,34)"}, + {"#Random_Integer(11,13)"}, + {"#RandomInteger(11)"}, + {"RandomInteger(11)"}, + {"RandomInteger"} + }); + + public KeywordsExtractorInvalidRandomIntegerTest(String keyword) { + this.keyword = keyword; + } + + @Before + public void setUp() { + this.keywordsExtractor = new KeywordsExtractor(); + } + + @Parameterized.Parameters + public static Collection data() { + return INVALID_INTEGER_KEYWORDS; + } + + @Test + public void checkValidRandomStringKeyword() { + assertEquals(keywordsExtractor.substituteStringKeyword(this.keyword, 1), this.keyword); + } + +} diff --git a/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorInvalidRandomStringTest.java b/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorInvalidRandomStringTest.java new file mode 100644 index 0000000..6834c0d --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorInvalidRandomStringTest.java @@ -0,0 +1,67 @@ +/* + * ============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.pnfsimulator.simulator; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Arrays; +import java.util.Collection; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class KeywordsExtractorInvalidRandomStringTest { + + private final String keyword; + private KeywordsExtractor keywordsExtractor; + + private static final Collection INVALID_STRING_KEYWORDS = Arrays.asList(new Object[][]{ + {"#RandoString"}, + {"#Randomstring(23)"}, + {"#randomString(11)"}, + {"#Random_String(11)"}, + {"#RandomString(11,10)"}, + {"RandomString(11)"}, + {"RandomString"} + }); + + public KeywordsExtractorInvalidRandomStringTest(String keyword) { + this.keyword = keyword; + } + + @Before + public void setUp() { + this.keywordsExtractor = new KeywordsExtractor(); + } + + @Parameterized.Parameters + public static Collection data() { + return INVALID_STRING_KEYWORDS; + } + + @Test + public void checkValidRandomStringKeyword() { + assertEquals(keywordsExtractor.substituteStringKeyword(this.keyword, 1).length(), this.keyword.length()); + } + +} diff --git a/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorInvalidTimestampTest.java b/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorInvalidTimestampTest.java new file mode 100644 index 0000000..eda4070 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorInvalidTimestampTest.java @@ -0,0 +1,65 @@ +/* + * ============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.pnfsimulator.simulator; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Arrays; +import java.util.Collection; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class KeywordsExtractorInvalidTimestampTest { + + private final String keyword; + private KeywordsExtractor keywordsExtractor; + + private static final Collection INVALID_TIMESTAMP_KEYWORDS = Arrays.asList(new Object[][]{ + {"#Timesamp"}, + {"#Timestamp(10)"}, + {"#timestamp"}, + {"#Timestamp(11,13)"}, + {"Timestamp"} + }); + + public KeywordsExtractorInvalidTimestampTest(String keyword) { + this.keyword = keyword; + } + + @Before + public void setUp() { + this.keywordsExtractor = new KeywordsExtractor(); + } + + @Parameterized.Parameters + public static Collection data() { + return INVALID_TIMESTAMP_KEYWORDS; + } + + @Test + public void checkValidRandomStringKeyword() { + assertEquals(keywordsExtractor.substituteStringKeyword(this.keyword, 1), this.keyword); + } + +} diff --git a/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorValidRandomIntegerTest.java b/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorValidRandomIntegerTest.java new file mode 100644 index 0000000..be79488 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorValidRandomIntegerTest.java @@ -0,0 +1,66 @@ +/* + * ============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.pnfsimulator.simulator; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Arrays; +import java.util.Collection; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class KeywordsExtractorValidRandomIntegerTest { + + private final String keyword; + private final String shouldParseTo; + private KeywordsExtractor keywordsExtractor; + + private static final Collection VALID_INTEGER_KEYWORDS = Arrays.asList(new Object[][]{ + {"#RandomInteger(23,23)", "23"}, + {"#RandomInteger(6, 6)12", "612"}, + {"1#RandomInteger(11,11)", "111"}, + {"1#RandomInteger(11,11)2", "1112"} + }); + + public KeywordsExtractorValidRandomIntegerTest(String keyword, String shouldParseTo) { + this.keyword = keyword; + this.shouldParseTo = shouldParseTo; + } + + @Before + public void setUp() { + this.keywordsExtractor = new KeywordsExtractor(); + } + + @Parameterized.Parameters + public static Collection data() { + return VALID_INTEGER_KEYWORDS; + } + + @Test + public void checkValidRandomStringKeyword() { + assertEquals(keywordsExtractor.substituteStringKeyword(this.keyword, 1), this.shouldParseTo); + } + +} diff --git a/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorValidRandomPrimitiveIntegerTest.java b/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorValidRandomPrimitiveIntegerTest.java new file mode 100644 index 0000000..0843ad1 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorValidRandomPrimitiveIntegerTest.java @@ -0,0 +1,66 @@ +/* + * ============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.pnfsimulator.simulator; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Arrays; +import java.util.Collection; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class KeywordsExtractorValidRandomPrimitiveIntegerTest { + + private final String keyword; + private final Integer shouldParseTo; + private KeywordsExtractor keywordsExtractor; + + private static final Collection VALID_INTEGER_KEYWORDS = Arrays.asList(new Object[][]{ + {"#RandomPrimitiveInteger(23,23)", 23}, + {"#RandomPrimitiveInteger(6, 6)12", 6}, + {"1#RandomPrimitiveInteger(11,11)", 11}, + {"1#RandomPrimitiveInteger(11,11)2", 11} + }); + + public KeywordsExtractorValidRandomPrimitiveIntegerTest(String keyword, Integer shouldParseTo) { + this.keyword = keyword; + this.shouldParseTo = shouldParseTo; + } + + @Before + public void setUp() { + this.keywordsExtractor = new KeywordsExtractor(); + } + + @Parameterized.Parameters + public static Collection data() { + return VALID_INTEGER_KEYWORDS; + } + + @Test + public void checkValidRandomStringKeyword() { + assertEquals(keywordsExtractor.substitutePrimitiveKeyword(this.keyword), Long.valueOf(this.shouldParseTo)); + } + +} diff --git a/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorValidRandomStringTest.java b/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorValidRandomStringTest.java new file mode 100644 index 0000000..f0fdc0f --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorValidRandomStringTest.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.pnfsimulator.simulator; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.onap.pnfsimulator.simulator.KeywordsValueProvider.DEFAULT_STRING_LENGTH; + +import java.util.Arrays; +import java.util.Collection; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class KeywordsExtractorValidRandomStringTest { + + private final String keyword; + private final int length; + private KeywordsExtractor keywordsExtractor; + + private static final Collection VALID_STRING_KEYWORDS = Arrays.asList(new Object[][]{ + {"#RandomString", DEFAULT_STRING_LENGTH}, + {"1#RandomString2", 1 + DEFAULT_STRING_LENGTH + 1}, + {"#RandomString(23)", 23}, + {"#RandomString(11)12", 11 + 2}, + {"1#RandomString(11)", 1 + 11}, + {"1#RandomString(11)2", 1 + 11 + 1} + }); + + public KeywordsExtractorValidRandomStringTest(String keyword, int length) { + this.keyword = keyword; + this.length = length; + } + + @Before + public void setUp() { + this.keywordsExtractor = new KeywordsExtractor(); + } + + @Parameterized.Parameters + public static Collection data() { + return VALID_STRING_KEYWORDS; + } + + @Test + public void checkValidRandomStringKeyword() { + assertEquals(keywordsExtractor.substituteStringKeyword(this.keyword, 1).length(), this.length); + } + +} diff --git a/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorValidTimestampPrimitiveTest.java b/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorValidTimestampPrimitiveTest.java new file mode 100644 index 0000000..7743e55 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorValidTimestampPrimitiveTest.java @@ -0,0 +1,66 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * 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.pnfsimulator.simulator; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +import java.time.Instant; +import java.util.Arrays; +import java.util.Collection; + +import static org.assertj.core.api.Assertions.assertThat; + +@RunWith(Parameterized.class) +public class KeywordsExtractorValidTimestampPrimitiveTest { + private final String keyword; + private KeywordsExtractor keywordsExtractor; + + private static final Collection VALID_TIMESTAMP_KEYWORDS = Arrays.asList(new Object[][]{ + {"#TimestampPrimitive"} + }); + + public KeywordsExtractorValidTimestampPrimitiveTest(String keyword) { + this.keyword = keyword; + } + + @Before + public void setUp() { + this.keywordsExtractor = new KeywordsExtractor(); + } + + @Parameterized.Parameters + public static Collection data() { + return VALID_TIMESTAMP_KEYWORDS; + } + + @Test + public void checkValidRandomStringKeyword() { + long currentTimestamp = Instant.now().getEpochSecond(); + Long timestamp = keywordsExtractor.substitutePrimitiveKeyword(this.keyword); + long afterExecution = Instant.now().getEpochSecond(); + + assertThat(timestamp).isBetween(currentTimestamp, afterExecution); + } + +} diff --git a/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorValidTimestampTest.java b/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorValidTimestampTest.java new file mode 100644 index 0000000..bf6f290 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorValidTimestampTest.java @@ -0,0 +1,68 @@ +/* + * ============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.pnfsimulator.simulator; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Arrays; +import java.util.Collection; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + +@RunWith(Parameterized.class) +public class KeywordsExtractorValidTimestampTest { + + private final String keyword; + private final int length; + private KeywordsExtractor keywordsExtractor; + + private static final Collection VALID_TIMESTAMP_KEYWORDS = Arrays.asList(new Object[][]{ + {"#Timestamp", 10}, + {"#Timestamp12", 10 + 2}, + {"1#Timestamp", 1 + 10}, + {"1#Timestamp2", 1 + 10 + 1} + }); + + public KeywordsExtractorValidTimestampTest(String keyword, Integer length) { + this.keyword = keyword; + this.length = length; + } + + @Before + public void setUp() { + this.keywordsExtractor = new KeywordsExtractor(); + } + + @Parameterized.Parameters + public static Collection data() { + return VALID_TIMESTAMP_KEYWORDS; + } + + @Test + public void checkValidRandomStringKeyword() { + String substitution = keywordsExtractor.substituteStringKeyword(this.keyword, 1); + assertEquals(substitution.length(), this.length); + } + +} diff --git a/src/test/java/org/onap/pnfsimulator/simulator/KeywordsHandlerTest.java b/src/test/java/org/onap/pnfsimulator/simulator/KeywordsHandlerTest.java new file mode 100644 index 0000000..e36bb28 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/simulator/KeywordsHandlerTest.java @@ -0,0 +1,306 @@ +/* + * ============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.pnfsimulator.simulator; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.onap.pnfsimulator.simulator.KeywordsValueProvider.DEFAULT_STRING_LENGTH; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.Queue; + +import org.junit.jupiter.api.Test; + +class KeywordsHandlerTest { + + private static final String TEMPLATE_JSON = "{\n" + + " \"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": \"#RandomString\"\n" + + " },\n" + + " \"measurementsForVfScalingFields\": {\n" + + " \"measurementsForVfSclaingFieldsVersion\": 2.0,\n" + + " \"additionalMeasurements\": {\n" + + " \"name\": \"licenseUsage\",\n" + + " \"extraFields\": {\n" + + " \"name\": \"#RandomString(4)\",\n" + + " \"value\": \"1\"\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + "}"; + + private static final String TEMPLATE_JSON_WITH_MANY_KEYWORDS_INSIDE_SINGLE_VALUE = "{\n" + + " \"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain1\": \"#RandomString(1) #RandomString(2) #RandomString(3)\",\n" + + " \"domain2\": \"1 #RandomString(1) 2\"\n" + + " },\n" + + " \"measurementsForVfScalingFields\": {\n" + + " \"measurementsForVfSclaingFieldsVersion\": 2.0,\n" + + " \"additionalMeasurements\": {\n" + + " \"name\": \"licenseUsage\",\n" + + " \"extraFields\": {\n" + + " \"value\": \"1\"\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + "}"; + + private static final String TEMPLATE_JSON_WITH_ARRAY = "{\n" + + " \"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": \"#RandomString(1)\",\n" + + " \"version\": 2.0\n" + + " },\n" + + " \"measurementsForVfScalingFields\": {\n" + + " \"additionalMeasurements\": [\n" + + " {\n" + + " \"name\": \"licenseUsage\",\n" + + " \"arrayOfFields\": [\n" + + " {\n" + + " \"name\": \"G711AudioPort\",\n" + + " \"value\": \"1\"\n" + + " },\n" + + " {\n" + + " \"name\": [\"1\",\"2\"],\n" + + " \"value\": \"#RandomString(2)\"\n" + + " },\n" + + " {\n" + + " \"name\": \"G722AudioPort\",\n" + + " \"value\": \"1\"\n" + + " }\n" + + " ]\n" + + " }\n" + + " ]\n" + + " }\n" + + " }\n" + + "}"; + + private static final String TEMPLATE_ONE_INCREMENT_JSON = "{\n" + + " \"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": \"#RandomString\"\n" + + " },\n" + + " \"measurementsForVfScalingFields\": {\n" + + " \"measurementsForVfSclaingFieldsVersion\": 2.0,\n" + + " \"additionalMeasurements\": {\n" + + " \"name\": \"licenseUsage\",\n" + + " \"extraFields\": {\n" + + " \"name\": \"#RandomString(4)\",\n" + + " \"value\": \"#Increment\"\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + "}"; + + private static final String TEMPLATE_WITH_SIMPLE_VALUE = "\"#RandomString(4)\""; + + private static final String TEMPLATE_WITH_ARRAY_OF_PRIMITIVES = "[ 1, \"#RandomString(5)\", 3]"; + + private static final String TEMPLATE_TWO_INCREMENT_JSON = "{\n" + + " \"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": \"#RandomString\"\n" + + " },\n" + + " \"measurementsForVfScalingFields\": {\n" + + " \"measurementsForVfSclaingFieldsVersion\": 2.0,\n" + + " \"additionalMeasurements\": {\n" + + " \"name\": \"licenseUsage\",\n" + + " \"extraFields\": {\n" + + " \"name\": \"#RandomString(4)\",\n" + + " \"value\": \"#Increment\",\n" + + " \"otherValue\": \"#Increment\"\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + "}"; + + private Gson gson = new Gson(); + + @Test + void shouldReplaceRandomStringKeyword() { + // given + JsonObject templateJson = gson.fromJson(TEMPLATE_JSON, JsonObject.class); + KeywordsHandler keywordsHandler = new KeywordsHandler(new KeywordsExtractor(), (id) -> 1); + + // when + JsonObject resultJson = keywordsHandler.substituteKeywords(templateJson, "").getAsJsonObject(); + + // then + String extraFields = resultJson + .get("event").getAsJsonObject() + .get("measurementsForVfScalingFields").getAsJsonObject() + .get("additionalMeasurements").getAsJsonObject() + .get("extraFields").getAsJsonObject() + .get("name").getAsString(); + String newDomain = resultJson + .get("event").getAsJsonObject() + .get("commonEventHeader").getAsJsonObject() + .get("domain").getAsString(); + + assertThat(extraFields.length()).isEqualTo(4); + assertThat(newDomain.length()).isEqualTo(DEFAULT_STRING_LENGTH); + } + + @Test + void shouldReplaceRandomStringKeywordsInsideSingleValue() { + // given + JsonObject templateJson = gson.fromJson(TEMPLATE_JSON_WITH_MANY_KEYWORDS_INSIDE_SINGLE_VALUE, JsonObject.class); + KeywordsHandler keywordsHandler = new KeywordsHandler(new KeywordsExtractor(), (id) -> 1); + + // when + JsonObject resultJson = keywordsHandler.substituteKeywords(templateJson, "").getAsJsonObject(); + + // then + String newDomain1 = resultJson + .get("event").getAsJsonObject() + .get("commonEventHeader").getAsJsonObject() + .get("domain1").getAsString(); + String newDomain2 = resultJson + .get("event").getAsJsonObject() + .get("commonEventHeader").getAsJsonObject() + .get("domain2").getAsString(); + + assertThat(newDomain1.length()).isEqualTo(1 + 1 + 2 + 1 + 3); + assertThat(newDomain2.length()).isEqualTo(1 + 1 + 1 + 1 + 1); + } + + @Test + void shouldReplaceRandomStringKeywordInTeplateAsArrayWithPrimitves() { + // given + JsonElement templateJson = gson.fromJson(TEMPLATE_WITH_ARRAY_OF_PRIMITIVES, JsonElement.class); + KeywordsHandler keywordsHandler = new KeywordsHandler(new KeywordsExtractor(), (id) -> 1); + + // when + JsonElement resultJson = keywordsHandler.substituteKeywords(templateJson, ""); + assertThat(resultJson.getAsJsonArray().get(1).getAsString().length()).isEqualTo(5); + } + + @Test + void shouldReplaceRandomStringKeywordInTeplateAsSimpleValue() { + // given + JsonElement templateJson = gson.fromJson(TEMPLATE_WITH_SIMPLE_VALUE, JsonElement.class); + KeywordsHandler keywordsHandler = new KeywordsHandler(new KeywordsExtractor(), (id) -> 1); + + // when + JsonElement resultJson = keywordsHandler.substituteKeywords(templateJson, ""); + + // then + assertThat(resultJson.getAsString().length()).isEqualTo(4); + } + + @Test + void shouldReplaceRandomStringKeywordInTeplateWithJsonArray() { + // given + JsonElement templateJson = gson.fromJson(TEMPLATE_JSON_WITH_ARRAY, JsonElement.class); + KeywordsHandler keywordsHandler = new KeywordsHandler(new KeywordsExtractor(), (id) -> 1); + + // when + JsonObject resultJson = keywordsHandler.substituteKeywords(templateJson, "").getAsJsonObject(); + + // then + String actualValue = resultJson + .get("event").getAsJsonObject() + .get("measurementsForVfScalingFields").getAsJsonObject() + .get("additionalMeasurements").getAsJsonArray() + .get(0).getAsJsonObject() + .get("arrayOfFields").getAsJsonArray() + .get(1).getAsJsonObject() + .get("value").getAsString(); + String otherActualValue = resultJson + .get("event").getAsJsonObject() + .get("commonEventHeader").getAsJsonObject() + .get("domain").getAsString(); + + assertThat(otherActualValue.length()).isEqualTo(1); + assertThat(actualValue.length()).isEqualTo(2); + } + + @Test + void shouldReplaceOneIncrementKeyword() { + // given + final Integer newIncrementedValue = 2; + JsonObject templateJson = gson.fromJson(TEMPLATE_ONE_INCREMENT_JSON, JsonObject.class); + KeywordsHandler keywordsHandler = new KeywordsHandler(new KeywordsExtractor(), (id) -> newIncrementedValue); + + // when + JsonObject resultJson = keywordsHandler.substituteKeywords(templateJson, "some random id").getAsJsonObject(); + + // then + String actualValue = resultJson + .get("event").getAsJsonObject() + .get("measurementsForVfScalingFields").getAsJsonObject() + .get("additionalMeasurements").getAsJsonObject() + .get("extraFields").getAsJsonObject() + .get("value").getAsString(); + + assertThat(actualValue).isEqualTo(newIncrementedValue.toString()); + } + + @Test + void shouldReplaceTwoIncrementKeyword() { + // given + final Integer firstIncrementValue = 2; + final Integer secondIncrementValue = 3; + JsonObject templateJson = gson.fromJson(TEMPLATE_TWO_INCREMENT_JSON, JsonObject.class); + KeywordsHandler keywordsHandler = new KeywordsHandler(new KeywordsExtractor(), new IncrementProvider() { + Queue<Integer> sequenceOfValues = new LinkedList<>( + Arrays.asList(firstIncrementValue, secondIncrementValue)); + + @Override + public int getAndIncrement(String id) { + return sequenceOfValues.poll(); + } + }); + + // when + JsonObject resultJson = keywordsHandler.substituteKeywords(templateJson, "some random id").getAsJsonObject(); + resultJson = keywordsHandler.substituteKeywords(templateJson, "some random id").getAsJsonObject(); + + // then + String actualValue = resultJson + .get("event").getAsJsonObject() + .get("measurementsForVfScalingFields").getAsJsonObject() + .get("additionalMeasurements").getAsJsonObject() + .get("extraFields").getAsJsonObject() + .get("value").getAsString(); + + String actualOtherValue = resultJson + .get("event").getAsJsonObject() + .get("measurementsForVfScalingFields").getAsJsonObject() + .get("additionalMeasurements").getAsJsonObject() + .get("extraFields").getAsJsonObject() + .get("otherValue").getAsString(); + + assertThat(actualValue).isEqualTo(secondIncrementValue.toString()); + assertThat(actualOtherValue).isEqualTo(secondIncrementValue.toString()); + + } +} diff --git a/src/test/java/org/onap/pnfsimulator/simulator/KeywordsValueProviderTest.java b/src/test/java/org/onap/pnfsimulator/simulator/KeywordsValueProviderTest.java new file mode 100644 index 0000000..ac54237 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/simulator/KeywordsValueProviderTest.java @@ -0,0 +1,82 @@ +/* + * ============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.pnfsimulator.simulator; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.onap.pnfsimulator.simulator.KeywordsValueProvider.DEFAULT_STRING_LENGTH; + +import java.util.Random; + +import org.junit.jupiter.api.RepeatedTest; +import org.junit.jupiter.api.Test; + +class KeywordsValueProviderTest { + + @RepeatedTest(10) + void randomLimitedStringTest() { + String supplierResult = KeywordsValueProvider.getRandomLimitedString().apply(); + assertEquals(DEFAULT_STRING_LENGTH, supplierResult.length()); + } + + @RepeatedTest(10) + void randomStringTest() { + int length = new Random().nextInt(15) + 1; + String supplierResult = KeywordsValueProvider.getRandomString().apply(length); + assertEquals(length, supplierResult.length()); + } + + @RepeatedTest(10) + void randomIntegerTest() { + int min = new Random().nextInt(10) + 1; + int max = new Random().nextInt(1000) + 20; + String supplierResult = KeywordsValueProvider.getRandomInteger().apply(min, max); + assertTrue(Integer.parseInt(supplierResult) >= min); + assertTrue(Integer.parseInt(supplierResult) <= max); + } + + @Test + void randomIntegerContainsMaximalAndMinimalValuesTest() { + int anyNumber = new Random().nextInt(10) + 1; + String supplierResult = KeywordsValueProvider.getRandomInteger().apply(anyNumber, anyNumber); + assertEquals(Integer.parseInt(supplierResult), anyNumber); + } + + @Test + void randomIntegerFromNegativeRangeTest() { + String supplierResult = KeywordsValueProvider.getRandomInteger().apply(-20, -20); + assertEquals(Integer.parseInt(supplierResult), -20); + } + + @RepeatedTest(10) + void randomIntegerFromParametersWithDifferentOrdersTest() { + String supplierResult = KeywordsValueProvider.getRandomInteger().apply(-20, -10); + assertTrue(Integer.parseInt(supplierResult) >= -20); + assertTrue(Integer.parseInt(supplierResult) <= -10); + } + + @RepeatedTest(10) + void epochSecondGeneratedInCorrectFormatTest() { + String supplierResult = KeywordsValueProvider.getEpochSecond().apply(); + assertEquals(10, supplierResult.length()); + } + +} diff --git a/src/test/java/org/onap/pnfsimulator/simulator/SimulatorServiceTest.java b/src/test/java/org/onap/pnfsimulator/simulator/SimulatorServiceTest.java new file mode 100644 index 0000000..d5426ec --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/simulator/SimulatorServiceTest.java @@ -0,0 +1,308 @@ +/* + * ============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.pnfsimulator.simulator; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonSyntaxException; +import org.apache.http.HttpStatus; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.onap.pnfsimulator.event.EventData; +import org.onap.pnfsimulator.event.EventDataService; +import org.onap.pnfsimulator.rest.model.FullEvent; +import org.onap.pnfsimulator.rest.model.SimulatorParams; +import org.onap.pnfsimulator.rest.model.SimulatorRequest; +import org.onap.pnfsimulator.simulator.client.HttpClientAdapter; +import org.onap.pnfsimulator.simulator.client.HttpResponseAdapter; +import org.onap.pnfsimulator.simulator.client.HttpTestUtils; +import org.onap.pnfsimulator.simulator.client.utils.ssl.SslAuthenticationHelper; +import org.onap.pnfsimulator.simulator.scheduler.EventScheduler; +import org.onap.pnfsimulator.simulatorconfig.SimulatorConfig; +import org.onap.pnfsimulator.simulatorconfig.SimulatorConfigService; +import org.quartz.SchedulerException; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.security.GeneralSecurityException; + +import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; +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.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 static org.mockito.Mockito.when; +import static org.mockito.internal.verification.VerificationModeFactory.times; + +class SimulatorServiceTest { + + private static final String VES_URL = "http://0.0.0.0:8080"; + private static final String IN_DB_VES_URL = "http://0.0.0.0:8080/eventListener/v6"; + private static final Gson GSON = new Gson(); + private static final JsonObject VALID_PATCH = GSON.fromJson("{\"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"sourceName\": \"SomeCustomSource\"}}}\n", JsonObject.class); + private static final JsonObject VALID_FULL_EVENT = GSON.fromJson("{\"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": \"notification\",\n" + + " \"eventName\": \"vFirewallBroadcastPackets\"\n" + + " },\n" + + " \"notificationFields\": {\n" + + " \"arrayOfNamedHashMap\": [{\n" + + " \"name\": \"A20161221.1031-1041.bin.gz\",\n" + + " \"hashMap\": {\n" + + " \"fileformatType\": \"org.3GPP.32.435#measCollec\"}}]}}}", JsonObject.class); + private static final JsonObject FULL_EVENT_WITH_KEYWORDS = GSON.fromJson("{\"event\":{ \n" + + " \"commonEventHeader\":{ \n" + + " \"domain\":\"notification\",\n" + + " \"eventName\":\"#RandomString(20)\",\n" + + " \"eventOrderNo\":\"#Increment\"}}}", JsonObject.class); + private static final JsonObject VALID_VARIABLES = GSON.fromJson("{\"dn\": \"TestDN-1\", \"measurement\":{\n" + + " \"name\": \"AdditionalM\",\n" + + " \"value\": \"1.5\"\n" + + " }}", JsonObject.class); + private static final String SOME_CUSTOM_SOURCE = "SomeCustomSource"; + private static final String CLOSED_LOOP_VNF = "ClosedLoopVNF"; + private static final String SAMPLE_ID = "sampleId"; + private static final EventData SAMPLE_EVENT = EventData.builder().id("1").build(); + private static URL inDbVesUrl; + private final ArgumentCaptor<JsonObject> bodyCaptor = ArgumentCaptor.forClass(JsonObject.class); + private final ArgumentCaptor<Integer> intervalCaptor = ArgumentCaptor.forClass(Integer.class); + private final ArgumentCaptor<Integer> repeatCountCaptor = ArgumentCaptor + .forClass(Integer.class); + private final ArgumentCaptor<String> templateNameCaptor = ArgumentCaptor.forClass(String.class); + private final ArgumentCaptor<String> eventIdCaptor = ArgumentCaptor.forClass(String.class); + private final ArgumentCaptor<String> vesUrlCaptor = ArgumentCaptor.forClass(String.class); + private final ArgumentCaptor<String> eventContentCaptor = ArgumentCaptor.forClass(String.class); + private final SslAuthenticationHelper sslAuthenticationHelper = new SslAuthenticationHelper(); + private final TemplatePatcher templatePatcher = new TemplatePatcher(); + private final TemplateReader templateReader = new FilesystemTemplateReader( + "src/test/resources/org/onap/pnfsimulator/simulator/", GSON); + + private SimulatorService simulatorService; + private EventDataService eventDataService; + private EventScheduler eventScheduler; + private SimulatorConfigService simulatorConfigService; + + @BeforeEach + void setUp() throws MalformedURLException { + inDbVesUrl = new URL(IN_DB_VES_URL); + eventDataService = mock(EventDataService.class); + eventScheduler = mock(EventScheduler.class); + simulatorConfigService = mock(SimulatorConfigService.class); + + simulatorService = new SimulatorService(templatePatcher, templateReader, + eventScheduler, eventDataService, simulatorConfigService, + new TemplateVariablesReplacer(),new SslAuthenticationHelper()); + } + + @Test + void shouldTriggerEventWithGivenParams() throws IOException, SchedulerException, GeneralSecurityException { + String templateName = "validExampleMeasurementEvent.json"; + SimulatorParams simulatorParams = new SimulatorParams(VES_URL, 1, 1); + SimulatorRequest simulatorRequest = new SimulatorRequest(simulatorParams, + templateName, VALID_PATCH, VALID_VARIABLES); + + doReturn(SAMPLE_EVENT).when(eventDataService).persistEventData(any(JsonObject.class), any(JsonObject.class), any(JsonObject.class), any(JsonObject.class)); + + simulatorService.triggerEvent(simulatorRequest); + + assertEventHasExpectedStructure(VES_URL, templateName, SOME_CUSTOM_SOURCE); + assertEventHasReplacedVariables(); + } + + @Test + void shouldTriggerEventWithDefaultVesUrlWhenNotProvidedInRequest() throws IOException, SchedulerException, GeneralSecurityException { + String templateName = "validExampleMeasurementEvent.json"; + SimulatorRequest simulatorRequest = new SimulatorRequest( + new SimulatorParams("", 1, 1), + templateName, VALID_PATCH, new JsonObject()); + + doReturn(SAMPLE_EVENT).when(eventDataService).persistEventData(any(JsonObject.class), any(JsonObject.class), any(JsonObject.class), any(JsonObject.class)); + when(simulatorConfigService.getConfiguration()).thenReturn(new SimulatorConfig(SAMPLE_ID, inDbVesUrl)); + + simulatorService.triggerEvent(simulatorRequest); + + assertEventHasExpectedStructure(inDbVesUrl.toString(), templateName, SOME_CUSTOM_SOURCE); + } + + @Test + void shouldThrowJsonSyntaxWhenInvalidJson() { + //given + JsonObject patch = GSON.fromJson("{\n" + + " \"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"sourceName\": \"" + + SOME_CUSTOM_SOURCE + "\"\n" + + " }\n" + + " }\n" + + "}\n", JsonObject.class); + EventData eventData = EventData.builder().id("1").build(); + + SimulatorParams simulatorParams = new SimulatorParams(VES_URL, 1, 1); + SimulatorRequest simulatorRequest = new SimulatorRequest(simulatorParams, + "invalidJsonStructureEvent.json", patch, new JsonObject()); + doReturn(eventData).when(eventDataService).persistEventData(any(JsonObject.class), any(JsonObject.class), any(JsonObject.class), any(JsonObject.class)); + + //when + assertThrows(JsonSyntaxException.class, + () -> simulatorService.triggerEvent(simulatorRequest)); + } + + @Test + void shouldHandleNonExistingPatchSection() throws IOException, SchedulerException, GeneralSecurityException { + String templateName = "validExampleMeasurementEvent.json"; + SimulatorRequest simulatorRequest = new SimulatorRequest( + new SimulatorParams("", 1, 1), + templateName, null, new JsonObject()); + + doReturn(SAMPLE_EVENT).when(eventDataService).persistEventData(any(JsonObject.class), any(JsonObject.class), any(JsonObject.class), any(JsonObject.class)); + doReturn(new SimulatorConfig(SAMPLE_ID, inDbVesUrl)).when(simulatorConfigService).getConfiguration(); + + simulatorService.triggerEvent(simulatorRequest); + + assertEventHasExpectedStructure(inDbVesUrl.toString(), templateName, CLOSED_LOOP_VNF); + } + + @Test + void shouldSuccessfullySendOneTimeEventWithVesUrlWhenPassed() throws IOException, GeneralSecurityException { + SimulatorService spiedTestedService = spy(new SimulatorService( + templatePatcher, templateReader, eventScheduler, + eventDataService, simulatorConfigService, + new TemplateVariablesReplacer(), + new SslAuthenticationHelper())); + + HttpClientAdapter adapterMock = mock(HttpClientAdapter.class); + prepareMocksWithAcceptedResponse(spiedTestedService, adapterMock); + FullEvent event = new FullEvent(VES_URL, VALID_FULL_EVENT); + + spiedTestedService.triggerOneTimeEvent(event); + + assertThat(eventContentCaptor.getValue()).isEqualTo(VALID_FULL_EVENT.toString()); + verify(eventDataService, times(1)).persistEventData(any(JsonObject.class), any(JsonObject.class), any(JsonObject.class), any(JsonObject.class)); + verify(adapterMock, times(1)).send(VALID_FULL_EVENT.toString()); + } + + @Test + void shouldSubstituteKeywordsAndSuccessfullySendOneTimeEvent() throws IOException, GeneralSecurityException { + SimulatorService spiedTestedService = spy(new SimulatorService( + templatePatcher, templateReader, eventScheduler, + eventDataService, simulatorConfigService, + new TemplateVariablesReplacer(), + new SslAuthenticationHelper()) + ); + + HttpClientAdapter adapterMock = mock(HttpClientAdapter.class); + prepareMocksWithAcceptedResponse(spiedTestedService, adapterMock); + FullEvent event = new FullEvent(VES_URL, FULL_EVENT_WITH_KEYWORDS); + + spiedTestedService.triggerOneTimeEvent(event); + + JsonObject sentContent = GSON.fromJson(eventContentCaptor.getValue(), JsonElement.class).getAsJsonObject(); + assertThat(sentContent.getAsJsonObject("event").getAsJsonObject("commonEventHeader").get("eventOrderNo").getAsString()).isEqualTo("1"); + assertThat(sentContent.getAsJsonObject("event").getAsJsonObject("commonEventHeader").get("eventName").getAsString()).hasSize(20); + } + + @Test + void shouldGetSimulatorConfiguration() { + SimulatorConfig simulatorConfig = getSimulatorConfig(); + + when(simulatorConfigService.getConfiguration()).thenReturn(simulatorConfig); + + assertEquals(simulatorService.getConfiguration(), simulatorConfig); + } + + @Test + void shouldUpdateSimulatorConfiguration() { + SimulatorConfig simulatorConfig = getSimulatorConfig(); + + when(simulatorConfigService.updateConfiguration(simulatorConfig)).thenReturn(simulatorConfig); + + assertEquals(simulatorService.updateConfiguration(simulatorConfig), simulatorConfig); + } + + @Test + void shouldCancelAllEvents() throws SchedulerException { + when(eventScheduler.cancelAllEvents()).thenReturn(true); + + assertTrue(simulatorService.cancelAllEvents()); + } + + @Test + void shouldCancelSingleEvent() throws SchedulerException { + final String jobName = "testJobName"; + when(eventScheduler.cancelEvent(jobName)).thenReturn(true); + + assertTrue(simulatorService.cancelEvent(jobName)); + } + + private void prepareMocksWithAcceptedResponse(SimulatorService spiedTestedService, HttpClientAdapter adapterMock) throws IOException, GeneralSecurityException { + HttpResponseAdapter response = new HttpResponseAdapter(HttpStatus.SC_ACCEPTED, HttpTestUtils.HTTP_MESSAGE_ACCEPTER); + doReturn(response).when(adapterMock).send(eventContentCaptor.capture()); + doReturn(adapterMock).when(spiedTestedService).createHttpClientAdapter(any(String.class)); + } + + private void assertEventHasExpectedStructure(String expectedVesUrl, String templateName, String sourceNameString) throws SchedulerException, IOException, GeneralSecurityException { + verify(eventScheduler, times(1)).scheduleEvent(vesUrlCaptor.capture(), intervalCaptor.capture(), + repeatCountCaptor.capture(), templateNameCaptor.capture(), eventIdCaptor.capture(), bodyCaptor.capture()); + assertThat(vesUrlCaptor.getValue()).isEqualTo(expectedVesUrl); + assertThat(intervalCaptor.getValue()).isEqualTo(1); + assertThat(repeatCountCaptor.getValue()).isEqualTo(1); + assertThat(templateNameCaptor.getValue()).isEqualTo(templateName); + String actualSourceName = GSON.fromJson(bodyCaptor.getValue(), JsonObject.class) + .get("event").getAsJsonObject() + .get("commonEventHeader").getAsJsonObject() + .get("sourceName").getAsString(); + assertThat(actualSourceName).isEqualTo(sourceNameString); + verify(eventDataService) + .persistEventData(any(JsonObject.class), any(JsonObject.class), any(JsonObject.class), + any(JsonObject.class)); + } + + private SimulatorConfig getSimulatorConfig() { + return new SimulatorConfig(SAMPLE_ID, inDbVesUrl); + } + + private void assertEventHasReplacedVariables() { + String measurementName = GSON.fromJson(bodyCaptor.getValue(), JsonObject.class) + .get("event").getAsJsonObject() + .get("measurementsForVfScalingFields").getAsJsonObject() + .get("additionalMeasurements").getAsJsonArray().get(0).getAsJsonObject() + .get("arrayOfFields").getAsJsonArray().get(0).getAsJsonObject() + .get("name").getAsString(); + + String reportingEntityName = GSON.fromJson(bodyCaptor.getValue(), JsonObject.class) + .get("event").getAsJsonObject() + .get("commonEventHeader").getAsJsonObject() + .get("reportingEntityName").getAsString(); + + assertThat(measurementName).isEqualTo("AdditionalM"); + assertThat(reportingEntityName).isEqualTo("TestDN-1"); + } + +} diff --git a/src/test/java/org/onap/pnfsimulator/simulator/TemplatePatcherTest.java b/src/test/java/org/onap/pnfsimulator/simulator/TemplatePatcherTest.java new file mode 100644 index 0000000..818c8be --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/simulator/TemplatePatcherTest.java @@ -0,0 +1,164 @@ +/* + * ============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.pnfsimulator.simulator; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import org.assertj.core.api.AssertionsForInterfaceTypes; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + +class TemplatePatcherTest { + + private static final String TEMPLATE_JSON = "{\n" + + " \"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": \"measurementsForVfScaling\"\n" + + " },\n" + + " \"measurementsForVfScalingFields\": {\n" + + " \"measurementsForVfSclaingFieldsVersion\": 2.0,\n" + + " \"additionalMeasurements\": {\n" + + " \"name\": \"licenseUsage\",\n" + + " \"extraFields\": {\n" + + " \"name\": \"G711AudioPort\",\n" + + " \"value\": \"1\"\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + "}"; + + private TemplatePatcher templatePatcher; + private Gson gson = new Gson(); + private JsonObject templateJson; + + @BeforeEach + void setUp() { + templatePatcher = new TemplatePatcher(); + templateJson = gson.fromJson(TEMPLATE_JSON, JsonObject.class); + } + + @Test + void shouldReplaceJsonElementsInTemplate() { + //given + String patchJsonString = "{\n" + + " \"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": \"newDomain\"\n" + + " }\n" + + " }\n" + + "}"; + JsonObject patchJson = gson.fromJson(patchJsonString, JsonObject.class); + + //when + JsonObject requestJson = templatePatcher.mergeTemplateWithPatch(templateJson, patchJson); + + //then + String newDomain = requestJson + .get("event").getAsJsonObject() + .get("commonEventHeader").getAsJsonObject() + .get("domain").getAsString(); + assertThat(newDomain).isEqualTo("newDomain"); + } + + @Test + void shouldAddWholeJsonObjectToTemplateWhenItFinished() { + //given + String patchJsonString = + "{\n" + + " \"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": {\n" + + " \"extraFields\": {\n" + + " \"name\": \"G711AudioPort\",\n" + + " \"value\": \"1\"\n" + + " }\n" + + " }\n" + + " }\n" + + " }\n" + + "}"; + JsonObject patchJson = gson.fromJson(patchJsonString, JsonObject.class); + + //when + JsonObject requestJson = templatePatcher.mergeTemplateWithPatch(templateJson, patchJson); + + //then + JsonElement newDomain = requestJson + .get("event").getAsJsonObject() + .get("commonEventHeader").getAsJsonObject() + .get("domain"); + assertThat(newDomain.isJsonObject()).isTrue(); + JsonObject newDomainJsonObject = newDomain.getAsJsonObject(); + AssertionsForInterfaceTypes.assertThat(newDomainJsonObject.keySet()).containsExactly("extraFields"); + JsonObject newDomainExtraFields = newDomainJsonObject.get("extraFields").getAsJsonObject(); + AssertionsForInterfaceTypes.assertThat(newDomainExtraFields.keySet()).containsExactly("name", "value"); + } + + @Test + void shouldReplaceJsonObjectWithJsonElementFromPatch() { + //given + String patchJsonString = "{ \"event\": \"test\" }"; + JsonObject patchJson = gson.fromJson(patchJsonString, JsonObject.class); + + //when + JsonObject requestJson = templatePatcher.mergeTemplateWithPatch(templateJson, patchJson); + + //then + assertThat(requestJson.get("event").isJsonObject()).isFalse(); + assertThat(requestJson.get("event").getAsString()).isEqualTo("test"); + } + + @Test + void shouldAddNewKeyIfPatchHasItAndTempleteDoesnt() { + //given + String patchJsonString = "{ \"newTestKey\": { \"newTestKeyChild\":\"newTestValue\" }}"; + JsonObject patchJson = gson.fromJson(patchJsonString, JsonObject.class); + + //when + JsonObject requestJson = templatePatcher.mergeTemplateWithPatch(templateJson, patchJson); + + //then + assertThat(requestJson.get("event").isJsonObject()).isTrue(); + assertThat(requestJson.get("newTestKey").isJsonObject()).isTrue(); + JsonObject newTestKey = requestJson.get("newTestKey").getAsJsonObject(); + AssertionsForInterfaceTypes.assertThat(newTestKey.keySet()).containsExactly("newTestKeyChild"); + assertThat(newTestKey.get("newTestKeyChild").getAsString()).isEqualTo("newTestValue"); + + } + + + @Test + void shouldNotChangeInputTemplateParam() { + //given + String patchJsonString = "{ \"newTestKey\": { \"newTestKeyChild\":\"newTestValue\" }}"; + JsonObject patchJson = gson.fromJson(patchJsonString, JsonObject.class); + + //when + templatePatcher.mergeTemplateWithPatch(templateJson, patchJson); + + //then + assertThat(templateJson).isEqualTo(gson.fromJson(TEMPLATE_JSON, JsonObject.class)); + + } +} diff --git a/src/test/java/org/onap/pnfsimulator/simulator/TemplateReaderTest.java b/src/test/java/org/onap/pnfsimulator/simulator/TemplateReaderTest.java new file mode 100644 index 0000000..f029fce --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/simulator/TemplateReaderTest.java @@ -0,0 +1,51 @@ +/* + * ============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.pnfsimulator.simulator; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.google.gson.JsonSyntaxException; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.springframework.test.context.TestPropertySource; + +import java.io.IOException; + +import static org.assertj.core.api.Java6Assertions.assertThat; + +@TestPropertySource +class TemplateReaderTest { + + private FilesystemTemplateReader templateReader = new FilesystemTemplateReader("src/test/resources/org/onap/pnfsimulator/simulator/", new Gson()); + + @Test + void testShouldReadJsonFromFile() throws IOException { + JsonObject readJson = templateReader.readTemplate("validExampleMeasurementEvent.json"); + assertThat(readJson.keySet()).containsOnly("event"); + assertThat(readJson.get("event").getAsJsonObject().keySet()).containsExactlyInAnyOrder("commonEventHeader", "measurementsForVfScalingFields"); + } + + @Test + void testShouldRaiseExceptionWhenInvalidJsonIsRead() { + Assertions.assertThrows(JsonSyntaxException.class, () -> templateReader.readTemplate("invalidJsonStructureEvent.json")); + } + +} diff --git a/src/test/java/org/onap/pnfsimulator/simulator/TemplateVariablesReplacerTest.java b/src/test/java/org/onap/pnfsimulator/simulator/TemplateVariablesReplacerTest.java new file mode 100644 index 0000000..5b7e4f4 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/simulator/TemplateVariablesReplacerTest.java @@ -0,0 +1,174 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * 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.pnfsimulator.simulator; + + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import lombok.val; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.TestInstance.Lifecycle; +import org.skyscreamer.jsonassert.JSONAssert; + +@TestInstance(Lifecycle.PER_CLASS) +class TemplateVariablesReplacerTest { + + private static final Gson GSON = new Gson(); + + private TemplateVariablesReplacer replacer; + + @BeforeAll + void setUp() { + replacer = new TemplateVariablesReplacer(); + } + + @Test + void shouldReplaceStringVariable() { + val sourceAsString = "{\"test1\":\"#variable1\", \"variable1\":\"value2 #variable1\"}"; + val expectedAsString = "{\"test1\":\"valueOfVariable1\", \"variable1\":\"value2 #variable1\"}"; + val variablesAsString = "{\"variable1\":\"valueOfVariable1\"}"; + + val source = GSON.fromJson(sourceAsString, JsonObject.class); + val variables = GSON.fromJson(variablesAsString, JsonObject.class); + + JsonObject result = replacer.substituteVariables(source, variables); + JSONAssert.assertEquals(expectedAsString, result.toString(), true); + } + + @Test + void shouldReplaceStringAndNumberVariable() { + val sourceAsString = "{\"test1\":\"#variable1\", \"test2\":\"#variable2\"}"; + val expectedAsString = "{\"test1\":\"valueOfVariable1=1\", \"test2\":2}"; + val variablesAsString = "{\"variable1\":\"valueOfVariable1=1\", \"variable2\":2}"; + + val source = new Gson().fromJson(sourceAsString, JsonObject.class); + val variables = new Gson().fromJson(variablesAsString, JsonObject.class); + + JsonObject result = replacer.substituteVariables(source, variables); + JSONAssert.assertEquals(expectedAsString, result.toString(), true); + } + + @Test + void shouldReplaceSimpleStringVariable() { + val sourceAsString = "{\"test1\":\"value1\", \"variable1\":\"#variable1\"}"; + val expectedAsString = "{\"test1\":\"value1\", \"variable1\":\"valueOfVariable1\"}"; + val variablesAsString = "{\"variable1\":\"valueOfVariable1\"}"; + + val source = GSON.fromJson(sourceAsString, JsonObject.class); + val variables = GSON.fromJson(variablesAsString, JsonObject.class); + + JsonObject result = replacer.substituteVariables(source, variables); + JSONAssert.assertEquals(expectedAsString, result.toString(), true); + } + + @Test + void shouldReplaceObjectVariable() { + val sourceAsString = "{\"test1\":\"value1\", \"variable1\":\"#variable1\"}"; + val expectedAsString = "{\"test1\":\"value1\", \"variable1\":{\"replaced1\":\"valueOfVariable1\"}}"; + val variablesAsString = "{\"variable1\":{\"replaced1\":\"valueOfVariable1\"}}"; + + val source = GSON.fromJson(sourceAsString, JsonObject.class); + val variables = GSON.fromJson(variablesAsString, JsonObject.class); + + JsonObject result = replacer.substituteVariables(source, variables); + JSONAssert.assertEquals(expectedAsString, result.toString(), true); + } + + @Test + void shouldReplaceIntegerVariable() { + val sourceAsString = "{\"test1\":\"value1\", \"variable1\":\"#variable1\"}"; + val expectedAsString = "{\"test1\":\"value1\", \"variable1\": 1}"; + val variablesAsString = "{\"variable1\": 1}"; + + val source = GSON.fromJson(sourceAsString, JsonObject.class); + val variables = GSON.fromJson(variablesAsString, JsonObject.class); + + JsonObject result = replacer.substituteVariables(source, variables); + JSONAssert.assertEquals(expectedAsString, result.toString(), true); + } + + @Test + void shouldReplaceBoolVariable() { + val sourceAsString = "{\"test1\":\"value1\", \"variable1\":\"#variable1\"}"; + val expectedAsString = "{\"test1\":\"value1\", \"variable1\": true}"; + val variablesAsString = "{\"variable1\": true}"; + + val source = GSON.fromJson(sourceAsString, JsonObject.class); + val variables = GSON.fromJson(variablesAsString, JsonObject.class); + + JsonObject result = replacer.substituteVariables(source, variables); + JSONAssert.assertEquals(expectedAsString, result.toString(), true); + } + + @Test + void shouldReplaceDifferentVariables() { + val sourceAsString = "{\"test1\":\"value1\", \"variable1\":\"#variable\", \"variable2\":\"text #variable\"}"; + val expectedAsString = "{\"test1\":\"value1\", \"variable1\":{\"replaced1\":\"valueOfVariable1\"}, \"variable2\":\"text #variable\"}"; + val variablesAsString = "{\"variable\":{\"replaced1\":\"valueOfVariable1\"}}"; + + val source = GSON.fromJson(sourceAsString, JsonObject.class); + val variables = GSON.fromJson(variablesAsString, JsonObject.class); + + JsonObject result = replacer.substituteVariables(source, variables); + JSONAssert.assertEquals(expectedAsString, result.toString(), true); + } + + @Test + void shouldReplaceArrayVariables() { + val sourceAsString = "{\"test1\":\"value1\", \"variable1\":\"#variable1\"}"; + val expectedAsString = "{\"test1\":\"value1\", \"variable1\":[1,2,3]}"; + val variablesAsString = "{\"variable1\":[1,2,3]}"; + + val source = GSON.fromJson(sourceAsString, JsonObject.class); + val variables = GSON.fromJson(variablesAsString, JsonObject.class); + + JsonObject result = replacer.substituteVariables(source, variables); + JSONAssert.assertEquals(expectedAsString, result.toString(), true); + } + + @Test + void shouldReplaceArrayWithStringVariables() { + val sourceAsString = "{\"test1\":\"value1\", \"variable1\":\"#variable1\"}"; + val expectedAsString = "{\"test1\":\"value1\", \"variable1\":[\"1\",\"2\",\"3\"]}"; + val variablesAsString = "{\"variable1\":[\"1\",\"2\",\"3\"]}"; + + val source = GSON.fromJson(sourceAsString, JsonObject.class); + val variables = GSON.fromJson(variablesAsString, JsonObject.class); + + JsonObject result = replacer.substituteVariables(source, variables); + JSONAssert.assertEquals(expectedAsString, result.toString(), true); + } + + @Test + void shouldReplaceArrayAsStringVariables() { + val sourceAsString = "{\"test1\":\"#variable1\", \"variable1\":\"Text #variable1\"}"; + val expectedAsString = "{\"test1\":[1,2,3], \"variable1\": \"Text #variable1\"}"; + val variablesAsString = "{\"variable1\":[1,2,3]}"; + + val source = GSON.fromJson(sourceAsString, JsonObject.class); + val variables = GSON.fromJson(variablesAsString, JsonObject.class); + + JsonObject result = replacer.substituteVariables(source, variables); + JSONAssert.assertEquals(expectedAsString, result.toString(), true); + } + +}
\ No newline at end of file diff --git a/src/test/java/org/onap/pnfsimulator/simulator/client/HttpApacheResponseAdapterFactoryTest.java b/src/test/java/org/onap/pnfsimulator/simulator/client/HttpApacheResponseAdapterFactoryTest.java new file mode 100644 index 0000000..2f8c6b3 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/simulator/client/HttpApacheResponseAdapterFactoryTest.java @@ -0,0 +1,98 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2021 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.pnfsimulator.simulator.client; + +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeEach; + +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.onap.pnfsimulator.simulator.client.HttpTestUtils.createMockedHttpEntity; +import static org.onap.pnfsimulator.simulator.client.HttpTestUtils.createStatusLine; + +class HttpApacheResponseAdapterFactoryTest { + + private HttpResponse httpResponse; + + @BeforeEach + void setup() { + httpResponse = mock(HttpResponse.class); + } + + @Test + void shouldCreateCorrectHttpResponseAdapterFromApacheHttpAcceptedResponse() throws IOException { + // given + final int responseCode = HttpStatus.SC_ACCEPTED; + final String responseBody = HttpTestUtils.HTTP_MESSAGE_ACCEPTER; + prepareHttpResponseMock(responseCode, createMockedHttpEntity(responseBody)); + + // when + HttpResponseAdapter httpResponseAdapter = new HttpApacheResponseAdapterFactory().create(httpResponse); + + // then + assertHttpResponseIsCorrect(responseCode, responseBody, httpResponseAdapter); + } + + + @Test + void shouldCreateCorrectHttpResponseAdapterFromApacheHttpForbiddenResponse() throws IOException { + // given + final int responseCode = HttpStatus.SC_FORBIDDEN; + final String responseBody = HttpTestUtils.HTTP_MESSAGE_FORBIDDEN; + prepareHttpResponseMock(responseCode, createMockedHttpEntity(responseBody)); + + // when + HttpResponseAdapter httpResponseAdapter = new HttpApacheResponseAdapterFactory().create(httpResponse); + + // then + assertHttpResponseIsCorrect(responseCode, responseBody, httpResponseAdapter); + } + + @Test + void shouldCreateCorrectHttpResponseAdapterFromApacheHttpResponseWithEmptyEntity() { + // given + final int responseCode = HttpStatus.SC_INTERNAL_SERVER_ERROR; + prepareHttpResponseMock(responseCode, null); + + // when + HttpResponseAdapter httpResponseAdapter = new HttpApacheResponseAdapterFactory().create(httpResponse); + + + assertHttpResponseIsCorrect(responseCode, "", httpResponseAdapter); + } + + private void prepareHttpResponseMock(int responseCode, HttpEntity httpEntity) { + doReturn(createStatusLine(responseCode)).when(httpResponse).getStatusLine(); + doReturn(httpEntity).when(httpResponse).getEntity(); + } + + private void assertHttpResponseIsCorrect(int responseCode, String responseBody, HttpResponseAdapter httpResponseAdapter) { + assertEquals(responseCode, httpResponseAdapter.getCode()); + assertEquals(responseBody, httpResponseAdapter.getMessage()); + } + +} diff --git a/src/test/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapterImplTest.java b/src/test/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapterImplTest.java new file mode 100644 index 0000000..cfbc8c1 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapterImplTest.java @@ -0,0 +1,157 @@ +/* + * ============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.pnfsimulator.simulator.client; + +import org.apache.http.Header; +import org.apache.http.HttpHeaders; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.socket.PlainConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.message.BasicHeader; +import org.apache.tomcat.util.codec.binary.Base64; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.onap.pnfsimulator.simulator.client.utils.ssl.SslAuthenticationHelper; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.onap.pnfsimulator.simulator.client.HttpTestUtils.createMockedHttpEntity; +import static org.onap.pnfsimulator.simulator.client.HttpTestUtils.createStatusLine; + +class HttpClientAdapterImplTest { + + private static final String HTTPS_URL = "https://0.0.0.0:8443/"; + private static final String HTTP_URL = "http://0.0.0.0:8000/"; + + private HttpClient httpClient; + private HttpResponse httpResponse; + + @BeforeEach + void setup() { + httpClient = mock(HttpClient.class); + httpResponse = mock(HttpResponse.class); + } + + @Test + void sendShouldSuccessfullySendRequestGivenValidUrl() throws IOException { + assertAdapterSentRequest("http://valid-url:8080", + HttpStatus.SC_FORBIDDEN, HttpTestUtils.HTTP_MESSAGE_FORBIDDEN); + } + + @Test + void sendShouldSuccessfullySendRequestGivenValidUrlUsingHttps() throws IOException { + assertAdapterSentRequest("https://valid-url:8443", + HttpStatus.SC_ACCEPTED, HttpTestUtils.HTTP_MESSAGE_ACCEPTER); + } + + @Test + void sendShouldSuccessfullySendRequestUsingBasicAuth() throws IOException { + String testUserInfo = "user1:pass1"; + Header authorizationHeader = createAuthorizationHeader(testUserInfo); + assertAdapterSentRequest("https://" + testUserInfo + "@valid-url:8443", + HttpStatus.SC_ACCEPTED, HttpTestUtils.HTTP_MESSAGE_ACCEPTER, + List.of(authorizationHeader)); + } + + @Test + void sendShouldFailToSendRequestGivenInvalidUrlUsingAdnShouldInformUser() throws IOException { + assertAdapterInformsUserWhenServiceIsUnavailable("https://invalid-url:8080"); + } + + @Test + void shouldThrowExceptionWhenMalformedVesUrlPassed() { + assertThrows(MalformedURLException.class, () -> new HttpClientAdapterImpl("http://blablabla:VES-PORT", new SslAuthenticationHelper())); + } + + @Test + void shouldCreateAdapterWithClientNotSupportingSslConnection() throws IOException, GeneralSecurityException { + HttpClientAdapter adapterWithHttps = new HttpClientAdapterImpl(HTTPS_URL, new SslAuthenticationHelper()); + try { + adapterWithHttps.send("sample"); + } catch (Exception actualException) { + assertThat(actualException).hasStackTraceContaining(SSLConnectionSocketFactory.class.toString()); + } + } + + @Test + void shouldCreateAdapterWithClientSupportingPlainConnectionOnly() throws IOException, GeneralSecurityException { + HttpClientAdapter adapterWithHttps = new HttpClientAdapterImpl(HTTP_URL, new SslAuthenticationHelper()); + try { + adapterWithHttps.send("sample"); + } catch (Exception actualException) { + assertThat(actualException).hasStackTraceContaining(PlainConnectionSocketFactory.class.toString()); + } + } + + private Header createAuthorizationHeader(String testUserInfo) { + String encodedUserInfo = new String(Base64.encodeBase64(testUserInfo.getBytes(StandardCharsets.UTF_8))); + return new BasicHeader(HttpHeaders.AUTHORIZATION, "Basic " + encodedUserInfo); + } + + private void assertAdapterSentRequest(String targetUrl, int responseCode, String responseMessage) throws IOException { + assertAdapterSentRequest(targetUrl, responseCode, responseMessage, List.of()); + } + + private void assertAdapterSentRequest(String targetUrl, int responseCode, String responseMessage, List<Header> expectedHeaders) throws IOException { + HttpClientAdapter adapter = new HttpClientAdapterImpl(httpClient, targetUrl); + doReturn(httpResponse).when(httpClient).execute(any()); + doReturn(createStatusLine(responseCode)).when(httpResponse).getStatusLine(); + doReturn(createMockedHttpEntity(responseMessage)).when(httpResponse).getEntity(); + + HttpResponseAdapter response = adapter.send("test-msg"); + + ArgumentCaptor<HttpPost> httpPostCaptor = ArgumentCaptor.forClass(HttpPost.class); + verify(httpClient).execute(httpPostCaptor.capture()); + Header[] headers = httpPostCaptor.getValue().getAllHeaders(); + assertEquals(responseCode, response.getCode()); + assertEquals(responseMessage, response.getMessage()); + assertThat(headers).usingFieldByFieldElementComparator().containsAll(expectedHeaders); + } + + private void assertAdapterInformsUserWhenServiceIsUnavailable(String targetUrl) throws IOException { + HttpClientAdapter adapter = new HttpClientAdapterImpl(httpClient, targetUrl); + String exceptionMessage = "test message"; + doThrow(new IOException(exceptionMessage)).when(httpClient).execute(any()); + + HttpResponseAdapter response = adapter.send("test-msg"); + + verify(httpClient).execute(any()); + assertEquals(421, response.getCode()); + assertEquals(String.format("Fail to connect with ves: %s", exceptionMessage), response.getMessage()); + } + +} diff --git a/src/test/java/org/onap/pnfsimulator/simulator/client/HttpTestUtils.java b/src/test/java/org/onap/pnfsimulator/simulator/client/HttpTestUtils.java new file mode 100644 index 0000000..02ff531 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/simulator/client/HttpTestUtils.java @@ -0,0 +1,55 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2021 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.pnfsimulator.simulator.client; + +import org.apache.http.HttpEntity; +import org.apache.http.ProtocolVersion; +import org.apache.http.message.BasicStatusLine; + +import java.io.ByteArrayInputStream; +import java.io.IOException; + +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; + +public class HttpTestUtils { + + private HttpTestUtils() { + } + + public static final String HTTP_MESSAGE_ACCEPTER = "Accepted"; + public static final String HTTP_MESSAGE_FORBIDDEN = "Forbidden"; + + static HttpEntity createMockedHttpEntity(String responseBody) throws IOException { + HttpEntity httpEntity = mock(HttpEntity.class); + doReturn(new ByteArrayInputStream(responseBody.getBytes())).when(httpEntity).getContent(); + return httpEntity; + } + + static BasicStatusLine createStatusLine(int responseCode) { + return new BasicStatusLine( + new ProtocolVersion("1.0.0", 1, 0), + responseCode, + "" + ); + } + +} diff --git a/src/test/java/org/onap/pnfsimulator/simulator/client/utils/ssl/CertAuthSslContextFactoryTest.java b/src/test/java/org/onap/pnfsimulator/simulator/client/utils/ssl/CertAuthSslContextFactoryTest.java new file mode 100644 index 0000000..c64ddd7 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/simulator/client/utils/ssl/CertAuthSslContextFactoryTest.java @@ -0,0 +1,141 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2020 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.pnfsimulator.simulator.client.utils.ssl; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.nio.file.NoSuchFileException; +import java.security.GeneralSecurityException; +import javax.net.ssl.SSLContext; +import org.hamcrest.CoreMatchers; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; + +public class CertAuthSslContextFactoryTest { + + private static final String CERTIFICATES_DIRECTORY = "src/test/resources/certificates/"; + + private static final String KEYSTORE_FILENAME = "client.p12"; + private static final String VALID_KEYSTORE_PASSWORD_FILENAME = "client.pass"; + private static final String INVALID_KEYSTORE_PASSWORD_FILENAME = "client_invalid.pass"; + + private static final String TRUSTSTORE_FILENAME = "truststore"; + private static final String VALID_TRUSTSTORE_PASSWORD_FILENAME = "truststore.pass"; + private static final String INVALID_TRUSTSTORE_PASSWORD_FILENAME = "truststore_invalid.pass"; + + private static final String NON_EXISTING_PASSWORD_FILENAME = "non_existing.pass"; + private static final String PASSWORD_INCORRECT = "password was incorrect"; + + private CertAuthSslContextFactory certAuthSslContextFactory; + + @Before + public void setup() { + this.certAuthSslContextFactory = new CertAuthSslContextFactory(new CertificateReader()); + } + + @Test + public void shouldCreateSslContextSuccessfully_whenValidPasswordsUsed() + throws GeneralSecurityException, IOException { + // Given + final SslAuthenticationHelper sslAuthenticationHelper = mockSslAuthenticationHelperWithFiles( + VALID_KEYSTORE_PASSWORD_FILENAME, VALID_TRUSTSTORE_PASSWORD_FILENAME); + + // When + final SSLContext sslContext = certAuthSslContextFactory.createSslContext(sslAuthenticationHelper); + + // Then + assertNotNull(sslContext); + } + + @Test + public void shouldThrowIOException_whenInvalidKeystorePasswordUsed() { + // Given + final SslAuthenticationHelper sslAuthenticationHelper = mockSslAuthenticationHelperWithFiles( + INVALID_KEYSTORE_PASSWORD_FILENAME, VALID_TRUSTSTORE_PASSWORD_FILENAME); + + // When + final IOException exception = assertThrows(IOException.class, + () -> certAuthSslContextFactory.createSslContext(sslAuthenticationHelper)); + + // Then + assertThat(exception.getMessage(), CoreMatchers.containsString(PASSWORD_INCORRECT)); + } + + @Test + public void shouldThrowIOException_whenInvalidTruststorePasswordUsed() { + // Given + final SslAuthenticationHelper sslAuthenticationHelper = mockSslAuthenticationHelperWithFiles( + VALID_KEYSTORE_PASSWORD_FILENAME, INVALID_TRUSTSTORE_PASSWORD_FILENAME); + + // When + final IOException exception = assertThrows(IOException.class, + () -> certAuthSslContextFactory.createSslContext(sslAuthenticationHelper)); + + // Then + assertThat(exception.getMessage(), CoreMatchers.containsString(PASSWORD_INCORRECT)); + } + + @Test + public void shouldThrowNoSuchFileException_whenInvalidKeystoreFilePath() { + final SslAuthenticationHelper sslAuthenticationHelper = mockSslAuthenticationHelperWithFiles( + NON_EXISTING_PASSWORD_FILENAME, INVALID_TRUSTSTORE_PASSWORD_FILENAME); + + // When, Then + assertThrows(NoSuchFileException.class, + () -> certAuthSslContextFactory.createSslContext(sslAuthenticationHelper)); + } + + @Test + public void shouldThrowNoSuchFileException_whenInvalidTruststoreFilePath() { + // Given + final SslAuthenticationHelper sslAuthenticationHelper = mockSslAuthenticationHelperWithFiles( + VALID_KEYSTORE_PASSWORD_FILENAME, NON_EXISTING_PASSWORD_FILENAME); + + // When, Then + assertThrows(NoSuchFileException.class, + () -> certAuthSslContextFactory.createSslContext(sslAuthenticationHelper)); + } + + private SslAuthenticationHelper mockSslAuthenticationHelperWithFiles(String keystorePasswordFilename, + String truststorePasswordFilename) { + final SslAuthenticationHelper sslAuthenticationHelper = Mockito.mock(SslAuthenticationHelper.class); + + when(sslAuthenticationHelper.getClientCertificatePath()) + .thenReturn(getPath(KEYSTORE_FILENAME)); + when(sslAuthenticationHelper.getClientCertificatePasswordPath()) + .thenReturn(getPath(keystorePasswordFilename)); + when(sslAuthenticationHelper.getTrustStorePath()) + .thenReturn(getPath(TRUSTSTORE_FILENAME)); + when(sslAuthenticationHelper.getTrustStorePasswordPath()) + .thenReturn(getPath(truststorePasswordFilename)); + + return sslAuthenticationHelper; + } + + private String getPath(String fileName) { + return CERTIFICATES_DIRECTORY + fileName; + } +}
\ No newline at end of file diff --git a/src/test/java/org/onap/pnfsimulator/simulator/client/utils/ssl/HttpClientFactoryFacadeTest.java b/src/test/java/org/onap/pnfsimulator/simulator/client/utils/ssl/HttpClientFactoryFacadeTest.java new file mode 100644 index 0000000..e6d3d03 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/simulator/client/utils/ssl/HttpClientFactoryFacadeTest.java @@ -0,0 +1,35 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2020 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.pnfsimulator.simulator.client.utils.ssl; + +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.security.GeneralSecurityException; + +import static org.junit.Assert.assertNotNull; + +class HttpClientFactoryFacadeTest { + @Test + void shouldSuccessfullyCreateHttpClient() throws GeneralSecurityException, IOException { + assertNotNull(HttpClientFactoryFacade.create("http://example.com", new SslAuthenticationHelper())); + } +} diff --git a/src/test/java/org/onap/pnfsimulator/simulator/client/utils/ssl/HttpClientFactoryTest.java b/src/test/java/org/onap/pnfsimulator/simulator/client/utils/ssl/HttpClientFactoryTest.java new file mode 100644 index 0000000..c213982 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/simulator/client/utils/ssl/HttpClientFactoryTest.java @@ -0,0 +1,143 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2020 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.pnfsimulator.simulator.client.utils.ssl; + +import org.hamcrest.CoreMatchers; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.security.GeneralSecurityException; +import java.security.KeyStoreException; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class HttpClientFactoryTest { + private static final String HTTPS_URL = "https://example.com"; + private static final String HTTP_URL = "http://example.com"; + + private SSLContextFactory sslContextFactoryMock; + private HttpClientFactory httpClientFactory; + private SslAuthenticationHelper sslAuthenticationHelper; + + @BeforeEach + public void setup() { + sslContextFactoryMock = mock(SSLContextFactory.class); + httpClientFactory = new HttpClientFactory(sslContextFactoryMock); + sslAuthenticationHelper = new SslAuthenticationHelper(); + } + + @Test + void shouldCreateHttpsClient_whenClientCertificationDisabled() throws GeneralSecurityException, IOException { + // given + sslAuthenticationHelper.setClientCertificateEnabled(false); + + // when + final var httpClient = httpClientFactory.create(HTTPS_URL, sslAuthenticationHelper); + + // then + assertNotNull(httpClient); + verifySslContextFactoryMockCalls(0, 1); + } + + @Test + void shouldCreateHttpsClient_whenClientCertificationDisabled_AndCannotCreateTrustAlwaysSslContext() throws GeneralSecurityException, IOException { + // given + sslAuthenticationHelper.setClientCertificateEnabled(false); + when(sslContextFactoryMock.createTrustAlways()).thenThrow(KeyStoreException.class); + + // when + final var httpClient = httpClientFactory.create(HTTPS_URL, sslAuthenticationHelper); + + // then + assertNotNull(httpClient); + verifySslContextFactoryMockCalls(0, 1); + } + + @Test + void shouldCreateHttpClient_whenClientCertificationDisabled() throws GeneralSecurityException, IOException { + // given + sslAuthenticationHelper.setClientCertificateEnabled(false); + + // when + final var httpClient = httpClientFactory.create(HTTP_URL, sslAuthenticationHelper); + + // then + assertNotNull(httpClient); + verifySslContextFactoryMockCalls(0, 0); + } + + + @Test + void shouldCreateHttpClient_whenClientCertificationAndStrictHostnameVerificationAreEnabled() throws GeneralSecurityException, IOException { + // given + sslAuthenticationHelper.setClientCertificateEnabled(true); + sslAuthenticationHelper.setStrictHostnameVerification(true); + + // when + final var httpClient = httpClientFactory.create(HTTP_URL, sslAuthenticationHelper); + + // then + assertNotNull(httpClient); + verifySslContextFactoryMockCalls(1, 0); + } + + @Test + void shouldCreateHttpClient_whenClientCertificationEnabledAndStrictHostnameVerificationDisabled() throws GeneralSecurityException, IOException { + // given + sslAuthenticationHelper.setClientCertificateEnabled(true); + sslAuthenticationHelper.setStrictHostnameVerification(false); + + // when + final var httpClient = httpClientFactory.create(HTTP_URL, sslAuthenticationHelper); + + // then + assertNotNull(httpClient); + verifySslContextFactoryMockCalls(1, 0); + } + + @Test + void shouldThrowMalformedURLException_whenInvalidUrl() throws GeneralSecurityException, IOException { + // given + var invalidUrl = "invalid"; + + // when + final var exception = assertThrows(MalformedURLException.class, + () -> httpClientFactory.create(invalidUrl, sslAuthenticationHelper)); + + // then + assertThat(exception.getMessage(), CoreMatchers.containsString("invalid")); + } + + private void verifySslContextFactoryMockCalls(int createCalls, int createTrustAlwaysCalls) throws GeneralSecurityException, IOException { + verify(sslContextFactoryMock, times(createCalls)).create(any()); + verify(sslContextFactoryMock, times(createTrustAlwaysCalls)).createTrustAlways(); + } + +} diff --git a/src/test/java/org/onap/pnfsimulator/simulator/client/utils/ssl/PasswordConverterTest.java b/src/test/java/org/onap/pnfsimulator/simulator/client/utils/ssl/PasswordConverterTest.java new file mode 100644 index 0000000..fddfc5f --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/simulator/client/utils/ssl/PasswordConverterTest.java @@ -0,0 +1,44 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2020 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.pnfsimulator.simulator.client.utils.ssl; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +class PasswordConverterTest { + + @Test + void shouldSuccessfullyConvert() { + // given, when + final char[] result = PasswordConverter.convert("sw ./#%"); + + // then + assertArrayEquals(new char[]{'s', 'w', ' ', '.', '/', '#', '%'}, result); + } + + @Test + void shouldReturnNull_whenNullPasswordUsed() { + // given, when, then + assertNull(PasswordConverter.convert(null)); + } +} diff --git a/src/test/java/org/onap/pnfsimulator/simulator/client/utils/ssl/SSLContextFactoryTest.java b/src/test/java/org/onap/pnfsimulator/simulator/client/utils/ssl/SSLContextFactoryTest.java new file mode 100644 index 0000000..85e40e5 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/simulator/client/utils/ssl/SSLContextFactoryTest.java @@ -0,0 +1,61 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2020 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.pnfsimulator.simulator.client.utils.ssl; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class SSLContextFactoryTest { + private CertificateReader certificateReaderMock; + private CertAuthSslContextFactory certAuthSslContextFactory; + private SSLContextFactory sslContextFactory; + + @BeforeEach + void setup() { + certificateReaderMock = mock(CertificateReader.class); + certAuthSslContextFactory = new CertAuthSslContextFactory(certificateReaderMock); + sslContextFactory = new SSLContextFactory(certAuthSslContextFactory); + } + + @Test + void shouldSuccessfullyCreateTrustAlwaysSSLContext() throws GeneralSecurityException, IOException { + // given, when, then + assertNotNull(sslContextFactory.createTrustAlways()); + verify(certificateReaderMock, times(0)).read(any(), any(), any()); + } + + @Test + void shouldSuccessfullyCreateSSLContext() throws GeneralSecurityException, IOException { + // given, when, then + assertNotNull(sslContextFactory.create(new SslAuthenticationHelper())); + verify(certificateReaderMock, times(2)).read(any(), any(), any()); + } + +} + diff --git a/src/test/java/org/onap/pnfsimulator/simulator/keywords/TwoParameterKeywordTest.java b/src/test/java/org/onap/pnfsimulator/simulator/keywords/TwoParameterKeywordTest.java new file mode 100644 index 0000000..6477fbf --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/simulator/keywords/TwoParameterKeywordTest.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * Simulator + * ================================================================================ + * Copyright (C) 2020 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.pnfsimulator.simulator.keywords; + + +import io.vavr.Tuple1; +import org.junit.jupiter.api.Test; + +import static org.junit.Assert.assertEquals; + +class TwoParameterKeywordTest { + @Test + public void whenGivenKeywordShouldReturnTwoParameterKeywordObjectWithParsedValues() { + //given + final String expectedName = "TEST"; + final Integer expectedParam1 = 123; + final Integer expectedParam2 = 456; + + String keyword = "#" + expectedName + "(" + expectedParam1 + "," + expectedParam2 + ")"; + + //when + Tuple1<TwoParameterKeyword> keywordTuple = TwoParameterKeyword.twoParameterKeyword(keyword); + TwoParameterKeyword twoParameterKeyword = keywordTuple._1(); + + //then + assertEquals(twoParameterKeyword.getName(), expectedName); + assertEquals(twoParameterKeyword.getAdditionalParameter1(), expectedParam1); + assertEquals(twoParameterKeyword.getAdditionalParameter2(), expectedParam2); + } +}
\ No newline at end of file diff --git a/src/test/java/org/onap/pnfsimulator/simulator/scheduler/EventJobTest.java b/src/test/java/org/onap/pnfsimulator/simulator/scheduler/EventJobTest.java new file mode 100644 index 0000000..fed6bb6 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/simulator/scheduler/EventJobTest.java @@ -0,0 +1,90 @@ +/* + * ============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.pnfsimulator.simulator.scheduler; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.onap.pnfsimulator.simulator.scheduler.EventJob.BODY; +import static org.onap.pnfsimulator.simulator.scheduler.EventJob.CLIENT_ADAPTER; +import static org.onap.pnfsimulator.simulator.scheduler.EventJob.EVENT_ID; +import static org.onap.pnfsimulator.simulator.scheduler.EventJob.KEYWORDS_HANDLER; +import static org.onap.pnfsimulator.simulator.scheduler.EventJob.TEMPLATE_NAME; +import static org.onap.pnfsimulator.simulator.scheduler.EventJob.VES_URL; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.onap.pnfsimulator.simulator.KeywordsExtractor; +import org.onap.pnfsimulator.simulator.KeywordsHandler; +import org.onap.pnfsimulator.simulator.client.HttpClientAdapter; +import org.quartz.JobDataMap; +import org.quartz.JobDetail; +import org.quartz.JobExecutionContext; +import org.quartz.JobKey; + +class EventJobTest { + + @Test + void shouldSendEventWhenExecuteCalled() { + //given + EventJob eventJob = new EventJob(); + String templateName = "template name"; + String vesUrl = "http://someurl:80/"; + String eventId = "1"; + JsonParser parser = new JsonParser(); + JsonObject body = parser.parse("{\"a\": \"A\"}").getAsJsonObject(); + HttpClientAdapter clientAdapter = mock(HttpClientAdapter.class); + JobExecutionContext jobExecutionContext = + createMockJobExecutionContext(templateName, eventId, vesUrl, body, clientAdapter); + + ArgumentCaptor<String> vesUrlCaptor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor<String> bodyCaptor = ArgumentCaptor.forClass(String.class); + + //when + eventJob.execute(jobExecutionContext); + + //then + verify(clientAdapter).send(bodyCaptor.capture()); + assertThat(bodyCaptor.getValue()).isEqualTo(body.toString()); + } + + private JobExecutionContext createMockJobExecutionContext(String templateName, String eventId, String vesUrl, + JsonObject body, HttpClientAdapter clientAdapter) { + + JobDataMap jobDataMap = new JobDataMap(); + jobDataMap.put(TEMPLATE_NAME, templateName); + jobDataMap.put(KEYWORDS_HANDLER, new KeywordsHandler(new KeywordsExtractor(), (id) -> 1)); + jobDataMap.put(EVENT_ID, eventId); + jobDataMap.put(VES_URL, vesUrl); + jobDataMap.put(BODY, body); + jobDataMap.put(CLIENT_ADAPTER, clientAdapter); + + JobExecutionContext jobExecutionContext = mock(JobExecutionContext.class); + JobDetail jobDetail = mock(JobDetail.class); + when(jobExecutionContext.getJobDetail()).thenReturn(jobDetail); + when(jobDetail.getJobDataMap()).thenReturn(jobDataMap); + when(jobDetail.getKey()).thenReturn(new JobKey("jobId", "group")); + return jobExecutionContext; + } +} diff --git a/src/test/java/org/onap/pnfsimulator/simulator/scheduler/EventSchedulerTest.java b/src/test/java/org/onap/pnfsimulator/simulator/scheduler/EventSchedulerTest.java new file mode 100644 index 0000000..d7cabb7 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/simulator/scheduler/EventSchedulerTest.java @@ -0,0 +1,148 @@ +/* + * ============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.pnfsimulator.simulator.scheduler; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.gson.JsonObject; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +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.mockito.MockitoAnnotations; +import org.onap.pnfsimulator.simulator.client.utils.ssl.SslAuthenticationHelper; +import org.quartz.JobDataMap; +import org.quartz.JobDetail; +import org.quartz.JobExecutionContext; +import org.quartz.JobKey; +import org.quartz.Scheduler; +import org.quartz.SchedulerException; +import org.quartz.SimpleTrigger; + +class EventSchedulerTest { + + @InjectMocks + EventScheduler eventScheduler; + + @Mock + Scheduler quartzScheduler; + + @Mock + SslAuthenticationHelper sslAuthenticationHelper; + + @BeforeEach + void setUp() { + MockitoAnnotations.initMocks(this); + } + + @Test + void shouldTriggerEventWithGivenConfiguration() throws SchedulerException, IOException, GeneralSecurityException { + //given + ArgumentCaptor<JobDetail> jobDetailCaptor = ArgumentCaptor.forClass(JobDetail.class); + ArgumentCaptor<SimpleTrigger> triggerCaptor = ArgumentCaptor.forClass(SimpleTrigger.class); + + String vesUrl = "http://some:80/"; + int repeatInterval = 1; + int repeatCount = 4; + String testName = "testName"; + String eventId = "1"; + JsonObject body = new JsonObject(); + + //when + eventScheduler.scheduleEvent(vesUrl, repeatInterval, repeatCount, testName, eventId, body); + + //then + verify(quartzScheduler).scheduleJob(jobDetailCaptor.capture(), triggerCaptor.capture()); + JobDataMap actualJobDataMap = jobDetailCaptor.getValue().getJobDataMap(); + assertThat(actualJobDataMap.get(EventJob.BODY)).isEqualTo(body); + assertThat(actualJobDataMap.get(EventJob.TEMPLATE_NAME)).isEqualTo(testName); + assertThat(actualJobDataMap.get(EventJob.VES_URL)).isEqualTo(vesUrl); + + SimpleTrigger actualTrigger = triggerCaptor.getValue(); + // repeat count adds 1 to given value + assertThat(actualTrigger.getRepeatCount()).isEqualTo(repeatCount - 1); + + //getRepeatInterval returns interval in ms + assertThat(actualTrigger.getRepeatInterval()).isEqualTo(repeatInterval * 1000); + } + + @Test + void shouldCancelAllEvents() throws SchedulerException { + //given + List<JobKey> jobsKeys = Arrays.asList(new JobKey("jobName1"), new JobKey("jobName2"), + new JobKey("jobName3"), new JobKey("jobName4")); + List<JobExecutionContext> jobExecutionContexts = createExecutionContextWithKeys(jobsKeys); + when(quartzScheduler.getCurrentlyExecutingJobs()).thenReturn(jobExecutionContexts); + when(quartzScheduler.deleteJobs(jobsKeys)).thenReturn(true); + + //when + boolean isCancelled = eventScheduler.cancelAllEvents(); + + //then + assertThat(isCancelled).isTrue(); + } + + @Test + void shouldCancelSingleEvent() throws SchedulerException { + //given + JobKey jobToRemove = new JobKey("jobName3"); + List<JobKey> jobsKeys = Arrays.asList(new JobKey("jobName1"), new JobKey("jobName2"), + jobToRemove, new JobKey("jobName4")); + List<JobExecutionContext> jobExecutionContexts = createExecutionContextWithKeys(jobsKeys); + + when(quartzScheduler.getCurrentlyExecutingJobs()).thenReturn(jobExecutionContexts); + when(quartzScheduler.deleteJob(jobToRemove)).thenReturn(true); + + //when + boolean isCancelled = eventScheduler.cancelEvent("jobName3"); + + //then + assertThat(isCancelled).isTrue(); + } + + private List<JobExecutionContext> createExecutionContextWithKeys(List<JobKey> jobsKeys) { + List<JobExecutionContext> contexts = new ArrayList<>(); + for (JobKey key : jobsKeys) { + contexts.add(createExecutionContextFromKey(key)); + } + return contexts; + } + + private JobExecutionContext createExecutionContextFromKey(JobKey key) { + JobExecutionContext context = mock(JobExecutionContext.class); + JobDetail jobDetail = mock(JobDetail.class); + when(context.getJobDetail()).thenReturn(jobDetail); + when(jobDetail.getKey()).thenReturn(key); + return context; + } + + +} diff --git a/src/test/java/org/onap/pnfsimulator/simulatorconfig/SimulatorConfigServiceTest.java b/src/test/java/org/onap/pnfsimulator/simulatorconfig/SimulatorConfigServiceTest.java new file mode 100644 index 0000000..4ed0972 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/simulatorconfig/SimulatorConfigServiceTest.java @@ -0,0 +1,104 @@ +/* + * ============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.pnfsimulator.simulatorconfig; + +import org.assertj.core.util.Lists; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.List; + +import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.assertj.core.api.Java6Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + +class SimulatorConfigServiceTest { + + private static final String SAMPLE_ID = "sampleId"; + private static final String SAMPLE_NEW_VES_URL = "http://localhost:8090/eventListener/v7"; + @Mock + private SimulatorConfigRepository repository; + + @InjectMocks + private SimulatorConfigService service; + + @BeforeEach + void resetMocks() { + initMocks(this); + } + + @Test + void testShouldReturnConfiguration() throws MalformedURLException { + List<SimulatorConfig> expectedConfig = getExpectedConfig(); + when(repository.findAll()).thenReturn(expectedConfig); + + SimulatorConfig configs = service.getConfiguration(); + + assertThat(configs).isNotNull(); + } + + @Test + void testShouldRaiseExceptionWhenNoConfigurationPresent() { + when(repository.findAll()).thenReturn(Lists.emptyList()); + + assertThatThrownBy(() -> service.getConfiguration()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No configuration found in db"); + } + + @Test + void testShouldUpdateConfigurationWithVesUrl() throws MalformedURLException { + URL updatedUrl = new URL("http://localhost:8090/listener/v8"); + SimulatorConfig configWithUpdates = new SimulatorConfig("sampleId", updatedUrl); + List<SimulatorConfig> expectedConfig = getExpectedConfig(); + + when(repository.findAll()).thenReturn(expectedConfig); + when(repository.save(any(SimulatorConfig.class))).thenReturn(configWithUpdates); + + SimulatorConfig updatedConfig = service.updateConfiguration(configWithUpdates); + + assertThat(updatedConfig).isEqualToComparingFieldByField(configWithUpdates); + } + + @Test + void testShouldRaiseExceptionWhenNoConfigInDbPresentOnUpdate() throws MalformedURLException { + when(repository.findAll()).thenReturn(Lists.emptyList()); + + SimulatorConfig configWithUpdates = new SimulatorConfig(SAMPLE_ID, new URL(SAMPLE_NEW_VES_URL)); + + assertThatThrownBy(() -> service.updateConfiguration(configWithUpdates)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No configuration found in db"); + } + + private List<SimulatorConfig> getExpectedConfig() throws MalformedURLException { + URL sampleVesUrl = new URL("http://localhost:8080/eventListener/v7"); + SimulatorConfig config = new SimulatorConfig(SAMPLE_ID, sampleVesUrl); + return Lists.newArrayList(config); + } + +} diff --git a/src/test/java/org/onap/pnfsimulator/template/FsToDbTemplateSynchronizerTest.java b/src/test/java/org/onap/pnfsimulator/template/FsToDbTemplateSynchronizerTest.java new file mode 100644 index 0000000..2d65097 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/template/FsToDbTemplateSynchronizerTest.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * Simulator + * ================================================================================ + * Copyright (C) 2020 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.pnfsimulator.template; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; + +import java.util.List; + +import static org.junit.Assert.assertEquals; + +public class FsToDbTemplateSynchronizerTest { + + + @Test + public void shouldReturnErrorSynchronizedMessage() { + //given + FsToDbTemplateSynchronizer fsToDbTemplateSynchronizer = new FsToDbTemplateSynchronizer("someInvalidValue", null); + Logger logger = (Logger) LoggerFactory.getLogger(FsToDbTemplateSynchronizer.class); + ListAppender<ILoggingEvent> listAppender = new ListAppender<>(); + listAppender.start(); + logger.addAppender(listAppender); + //when + fsToDbTemplateSynchronizer.synchronize(); + List<ILoggingEvent> logsList = listAppender.list; + //then + assertEquals("Cannot synchronize templates. Check whether the proper folder exists.", logsList.get(0) + .getMessage()); + assertEquals(Level.ERROR, logsList.get(0) + .getLevel()); + } +}
\ No newline at end of file diff --git a/src/test/java/org/onap/pnfsimulator/template/TemplateServiceTest.java b/src/test/java/org/onap/pnfsimulator/template/TemplateServiceTest.java new file mode 100644 index 0000000..fd41045 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/template/TemplateServiceTest.java @@ -0,0 +1,152 @@ +/*- + * ============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.pnfsimulator.template; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import org.assertj.core.util.Lists; +import org.bson.Document; +import org.junit.Assert; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.onap.pnfsimulator.template.search.viewmodel.FlatTemplateContent; +import org.onap.pnfsimulator.template.search.TemplateSearchHelper; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.query.Query; + +import java.time.Instant; +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyObject; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + +class TemplateServiceTest { + private static final Gson GSON = new Gson(); + private static final Template SAMPLE_TEMPLATE = new Template("sample name", new Document(), Instant.now().getNano()); + private static final List<Template> SAMPLE_TEMPLATE_LIST = Collections.singletonList(SAMPLE_TEMPLATE); + + @Mock + private TemplateRepository templateRepositoryMock; + + @Mock + private MongoTemplate mongoTemplate; + + @InjectMocks + private TemplateService service; + + @BeforeEach + void setUp() { + initMocks(this); + TemplateSearchHelper searchHelper = new TemplateSearchHelper(mongoTemplate); + service = new TemplateService(templateRepositoryMock, searchHelper); + } + + @Test + void testShouldReturnAllTemplates() { + when(templateRepositoryMock.findAll()).thenReturn(SAMPLE_TEMPLATE_LIST); + + List<Template> actual = service.getAll(); + assertThat(actual).containsExactly(SAMPLE_TEMPLATE_LIST.get(0)); + } + + + @Test + void testShouldGetTemplateBySpecifiedName() { + when(templateRepositoryMock.findById("sample name")).thenReturn(Optional.of(SAMPLE_TEMPLATE)); + + Optional<Template> actualTemplate = service.get("sample name"); + assertThat(actualTemplate).isPresent(); + assertThat(actualTemplate.get()).isEqualTo(SAMPLE_TEMPLATE); + } + + @Test + void testShouldSaveTemplate() { + service.persist(SAMPLE_TEMPLATE); + + verify(templateRepositoryMock, times(1)).save(SAMPLE_TEMPLATE); + } + + @Test + void testShouldDeleteTemplateByName() { + service.delete("sample name"); + + verify(templateRepositoryMock, times(1)).deleteById("sample name"); + } + + + @Test + void testShouldReturnTemplatesAccordingToGivenSearchCriteria() { + doReturn(Lists.emptyList()).when(mongoTemplate).find(any(Query.class), anyObject(), any(String.class)); + + List<String> idsByContentCriteria = service.getIdsByContentCriteria(GSON.fromJson("{\"domain\": \"notification.json\"}", JsonObject.class)); + + assertThat(idsByContentCriteria).isEmpty(); + } + + @Test + void shouldReturnNamesForGivenComposedSearchCriteria() { + JsonObject composedCriteriaObject = GSON.fromJson("{\"eventName\": \"pnfRegistration_Nokia_5gDu\", \"sequence\": 1}", JsonObject.class); + List<FlatTemplateContent> arr = Lists.newArrayList(new FlatTemplateContent("sampleId", null)); + + doReturn(arr).when(mongoTemplate).find(any(Query.class), anyObject(), any(String.class)); + + List<String> idsByContentCriteria = service.getIdsByContentCriteria(composedCriteriaObject); + assertThat(idsByContentCriteria).containsOnly("sampleId"); + } + + @Test + void shouldReturnFalseWhenOverwritingWithoutForce() { + String id = "someTemplate"; + Template template = new Template(id, new Document(), Instant.now().getNano()); + when(templateRepositoryMock.existsById(id)).thenReturn(true); + boolean actual = service.tryPersistOrOverwrite(template, false); + Assert.assertFalse(actual); + } + + @Test + void shouldReturnTrueWhenOverwritingWithForce() { + String id = "someTemplate"; + Template template = new Template(id, new Document(), Instant.now().getNano()); + when(templateRepositoryMock.existsById(id)).thenReturn(true); + boolean actual = service.tryPersistOrOverwrite(template, true); + Assert.assertTrue(actual); + } + + @Test + void shouldReturnTrueWhenSavingNonExistingTemplate() { + String id = "someTemplate"; + Template template = new Template(id, new Document(), Instant.now().getNano()); + when(templateRepositoryMock.existsById(id)).thenReturn(false); + boolean actual = service.tryPersistOrOverwrite(template, false); + Assert.assertTrue(actual); + } + +} diff --git a/src/test/java/org/onap/pnfsimulator/template/search/JsonUtilsTest.java b/src/test/java/org/onap/pnfsimulator/template/search/JsonUtilsTest.java new file mode 100644 index 0000000..aac15a6 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/template/search/JsonUtilsTest.java @@ -0,0 +1,166 @@ +/*- + * ============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.pnfsimulator.template.search; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import org.bson.Document; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Java6Assertions.assertThat; + +class JsonUtilsTest { + + private static final Gson GSON_HELPER = new Gson(); + private JsonUtils utils; + + @BeforeEach + void setUp() { + utils = new JsonUtils(); + } + + private static final String NOTIFICATION_JSON = "{\n\"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": \"notification\",\n" + + " \"eventName\": \"vFirewallBroadcastPackets\"\n" + + " },\n" + + " \"notificationFields\": {\n" + + " \"changeIdentifier\": \"PM_MEAS_FILES\",\n" + + " \"arrayOfNamedHashMap\": [{\n" + + " \"name\": \"A20161221.1031-1041.bin.gz\",\n" + + " \"hashMap\": {\n" + + " \"fileformatType\": \"org.3GPP.32.435#measCollec\",\n" + + " \"fileFormatVersion\": \"V10\"\n" + + " }\n" + + " }, {\n" + + " \"name\": \"A20161222.1042-1102.bin.gz\",\n" + + " \"hashMap\": {\n" + + " \"fileFormatType\": \"org.3GPP.32.435#measCollec\",\n" + + " \"fileFormatVersion\": \"1.0.0\"\n" + + " }\n" + + " }],\n" + + " \"notificationFieldsVersion\": \"2.0\"\n}\n\n}}"; + private static final String EXPECTED_FLATTENED_NOTIFICATION = "{" + + " \":event:commonEventHeader:domain\" : \"notification\"," + + " \":event:commonEventHeader:eventName\" : \"vFirewallBroadcastPackets\"," + + " \":event:notificationFields:changeIdentifier\" : \"PM_MEAS_FILES\"," + + " \":event:notificationFields:arrayOfNamedHashMap[0]:name\" : \"A20161221.1031-1041.bin.gz\"," + + " \":event:notificationFields:arrayOfNamedHashMap[0]:hashMap:fileformatType\" : \"org.3GPP.32.435#measCollec\"," + + " \":event:notificationFields:arrayOfNamedHashMap[0]:hashMap:fileFormatVersion\" : \"V10\"," + + " \":event:notificationFields:arrayOfNamedHashMap[1]:name\" : \"A20161222.1042-1102.bin.gz\"," + + " \":event:notificationFields:arrayOfNamedHashMap[1]:hashMap:fileFormatType\" : \"org.3GPP.32.435#measCollec\"," + + " \":event:notificationFields:arrayOfNamedHashMap[1]:hashMap:fileFormatVersion\" : \"1.0.0\"," + + " \":event:notificationFields:notificationFieldsVersion\" : \"2.0\" }"; + + @Test + void shouldFlattenNestedJsonAndSeparateKeysWithDoubleHash() { + JsonObject templateJson = GSON_HELPER.fromJson(NOTIFICATION_JSON, JsonObject.class); + + JsonObject result = utils.flatten(templateJson); + + assertThat(result).isEqualTo(GSON_HELPER.fromJson(EXPECTED_FLATTENED_NOTIFICATION, JsonObject.class)); + } + + @Test + void shouldWorkOnEmptyJsonObject() { + JsonObject result = utils.flatten(new JsonObject()); + + assertThat(result.toString()).isEqualTo("{}"); + } + + @Test + void shouldFlattenObjectWithArrayValue() { + String expectedFlattenedObjectWithArray = "{" + + " \":sample[0]\": 1," + + " \":sample[1]\": 2," + + " \":sample[2]\": 3}"; + JsonObject jsonWithPrimitivesArray = GSON_HELPER.fromJson("{\"sample\": [1, 2, 3]}", JsonObject.class); + + JsonObject result = utils.flatten(jsonWithPrimitivesArray); + + assertThat(result).isEqualTo(GSON_HELPER.fromJson(expectedFlattenedObjectWithArray, JsonObject.class)); + } + + @Test + void shouldFlattenObjectWithEmptyArrayValue() { + String expectedFlattenedObjectWithEmptyArray = "{\":sample\": []}"; + JsonObject jsonWithEmptyArrayValue = GSON_HELPER.fromJson("{\"sample\": []}", JsonObject.class); + + JsonObject result = utils.flatten(jsonWithEmptyArrayValue); + + assertThat(result).isEqualTo(GSON_HELPER.fromJson(expectedFlattenedObjectWithEmptyArray, JsonObject.class)); + } + + @Test + void shouldFlattenNestedObjectWithEmptyObjectValue() { + String expectedFlattenedNestedObjectWithEmptyObject = "{\":sample:key\": {}}"; + JsonObject nestedJsonWithEmptyObject = GSON_HELPER.fromJson("{\"sample\": {\"key\":{}}}", JsonObject.class); + + JsonObject result = utils.flatten(nestedJsonWithEmptyObject); + + assertThat(result).isEqualTo(GSON_HELPER.fromJson(expectedFlattenedNestedObjectWithEmptyObject, JsonObject.class)); + } + + @Test + void shouldFlattenObjectWithDifferentDataTypes() { + String jsonWithDifferentDataTypes = "{ \"topLevelKey\": {\"sampleInt\": 1, \"sampleBool\": false, \"sampleDouble\": 10.0, \"sampleString\": \"str\"}}"; + String expectedResult = "{\":topLevelKey:sampleInt\": 1," + + " \":topLevelKey:sampleBool\": \"false\"," + + " \":topLevelKey:sampleDouble\": 10.0," + + " \":topLevelKey:sampleString\": \"str\"}"; + JsonObject templateJson = GSON_HELPER.fromJson(jsonWithDifferentDataTypes, JsonObject.class); + + JsonObject result = utils.flatten(templateJson); + + assertThat(result).isEqualTo(GSON_HELPER.fromJson(expectedResult, JsonObject.class)); + } + + @Test + void shouldHandleNullValues() { + String jsonWithNullValue = "{ \"topLevelKey\": {\"sampleNull\": null, \"sampleString\": \"str\"}}"; + String expectedResult = "{\":topLevelKey:sampleNull\": null," + + " \":topLevelKey:sampleString\": \"str\"}"; + JsonObject templateJson = GSON_HELPER.fromJson(jsonWithNullValue, JsonObject.class); + + JsonObject result = utils.flatten(templateJson); + + assertThat(result).isEqualTo(GSON_HELPER.fromJson(expectedResult, JsonObject.class)); + } + + @Test + void shouldFlattenBsonDocument() { + Document documentInput = Document.parse(NOTIFICATION_JSON); + + Document result = utils.flatten(documentInput); + + assertThat(result.toJson()).isEqualTo(EXPECTED_FLATTENED_NOTIFICATION); + } + + @Test + void shouldNotChangeEmptyBsonDocument() { + Document input = Document.parse("{}"); + + Document result = utils.flatten(input); + + assertThat(result.toJson()).isEqualTo("{ }"); + } +} diff --git a/src/test/java/org/onap/pnfsimulator/template/search/TemplateSearchHelperTest.java b/src/test/java/org/onap/pnfsimulator/template/search/TemplateSearchHelperTest.java new file mode 100644 index 0000000..13ea7c6 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/template/search/TemplateSearchHelperTest.java @@ -0,0 +1,160 @@ +/*- + * ============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.pnfsimulator.template.search; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.mongodb.BasicDBList; +import org.assertj.core.util.Lists; +import org.bson.Document; +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.onap.pnfsimulator.template.search.viewmodel.FlatTemplateContent; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.query.BasicQuery; +import org.springframework.data.mongodb.core.query.Query; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyObject; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + + +class TemplateSearchHelperTest { + + private static final Gson GSON = new Gson(); + private static final String FLATTENED_TEMPLATES_VIEW = "flatTemplatesView"; + + @Mock + private MongoTemplate mongoTemplate; + + @InjectMocks + private TemplateSearchHelper helper; + + private static final ArgumentCaptor<Query> QUERY_CAPTOR = ArgumentCaptor.forClass(Query.class); + private static final ArgumentCaptor<String> COLLECTION_NAME_CAPTOR = ArgumentCaptor.forClass(String.class); + private static final ArgumentCaptor<Class<FlatTemplateContent>> CLASS_TYPE_CAPTOR = ArgumentCaptor.forClass((Class) FlatTemplateContent.class); + + + @BeforeEach + void setUp() { + initMocks(this); + } + + @Test + void shouldReturnNamesForGivenComposedSearchCriteria() { + String expectedComposedQueryString = "{\"$and\":[{\"keyValues\":{\"$elemMatch\":{\"k\":{\"$regex\":\":eventName(?:(\\\\[[\\\\d]+\\\\]))?$\",\"$options\":\"iu\"},\"v\":{\"$regex\":\"^\\\\QpnfRegistration_Nokia_5gDu\\\\E$\",\"$options\":\"iu\"}}}},{\"keyValues\":{\"$elemMatch\":{\"k\":{\"$regex\":\":sequence(?:(\\\\[[\\\\d]+\\\\]))?$\",\"$options\":\"iu\"},\"v\":1.0}}}]}"; + Query expectedQuery = new BasicQuery(expectedComposedQueryString); + + String composedCriteriaInputJson = "{\"eventName\": \"pnfRegistration_Nokia_5gDu\", \"sequence\": 1}"; + JsonObject composedCriteriaObject = GSON.fromJson(composedCriteriaInputJson, JsonObject.class); + + when(mongoTemplate.find(any(Query.class), anyObject(), any(String.class))).thenReturn(Lists.newArrayList(new FlatTemplateContent("sampleId1", null), new FlatTemplateContent("sampleId2", null))); + + List<String> idsOfDocumentMatchingCriteria = helper.getIdsOfDocumentMatchingCriteria(composedCriteriaObject); + + assertThat(idsOfDocumentMatchingCriteria).containsOnly("sampleId1", "sampleId2"); + verify(mongoTemplate, times(1)).find(QUERY_CAPTOR.capture(), CLASS_TYPE_CAPTOR.capture(), COLLECTION_NAME_CAPTOR.capture()); + assertThat(QUERY_CAPTOR.getValue().toString()).isEqualTo(expectedQuery.toString()); + assertThat(COLLECTION_NAME_CAPTOR.getValue()).isEqualTo(FLATTENED_TEMPLATES_VIEW); + assertThat(CLASS_TYPE_CAPTOR.getValue()).isEqualTo(FlatTemplateContent.class); + } + + @Test + void shouldReturnTemplatesAccordingToGivenSearchCriteria() { + Query expectedQueryStructure = new BasicQuery("{\"$and\":[{\"keyValues\": { \"$elemMatch\" : { \"k\" : { \"$regex\" : \":domain(?:(\\\\[[\\\\d]+\\\\]))?$\", \"$options\" : \"iu\" }, \"v\" : { \"$regex\" : \"^\\\\Qnotification\\\\E$\", \"$options\" : \"iu\" }}}}]}"); + + helper.getIdsOfDocumentMatchingCriteria(GSON.fromJson("{\"domain\": \"notification\"}", JsonObject.class)); + + + verify(mongoTemplate, times(1)).find(QUERY_CAPTOR.capture(), CLASS_TYPE_CAPTOR.capture(), COLLECTION_NAME_CAPTOR.capture()); + + assertThat(QUERY_CAPTOR.getValue().toString()).isEqualTo(expectedQueryStructure.toString()); + assertThat(COLLECTION_NAME_CAPTOR.getValue()).isEqualTo(FLATTENED_TEMPLATES_VIEW); + assertThat(CLASS_TYPE_CAPTOR.getValue()).isEqualTo(FlatTemplateContent.class); + } + + @Test + void shouldGetQueryForEmptyJson() { + JsonObject jsonObject = GSON.fromJson("{}", JsonObject.class); + + String expectedComposedQueryString = "{}"; + Query expectedQuery = new BasicQuery(expectedComposedQueryString); + + helper.getIdsOfDocumentMatchingCriteria(jsonObject); + + verify(mongoTemplate, times(1)).find(QUERY_CAPTOR.capture(), CLASS_TYPE_CAPTOR.capture(), COLLECTION_NAME_CAPTOR.capture()); + Query queryBasedOnCriteria = QUERY_CAPTOR.getValue(); + + assertThat(QUERY_CAPTOR.getValue().toString()).isEqualTo(expectedQuery.toString()); + assertThat(COLLECTION_NAME_CAPTOR.getValue()).isEqualTo(FLATTENED_TEMPLATES_VIEW); + assertThat(CLASS_TYPE_CAPTOR.getValue()).isEqualTo(FlatTemplateContent.class); + } + + + @Test + void shouldGetQueryWithAllTypeValues() { + JsonObject jsonObject = GSON.fromJson("{\"stringKey\": \"stringValue\", \"numberKey\": 16.00, \"boolKey\": false}", JsonObject.class); + + helper.getIdsOfDocumentMatchingCriteria(jsonObject); + + verify(mongoTemplate, times(1)).find(QUERY_CAPTOR.capture(), CLASS_TYPE_CAPTOR.capture(), COLLECTION_NAME_CAPTOR.capture()); + Query queryBasedOnCriteria = QUERY_CAPTOR.getValue(); + + assertThat(queryBasedOnCriteria.getQueryObject().get("$and")).isInstanceOf(List.class); + List<Document> conditionDocuments = new ArrayList<>((List<Document>) queryBasedOnCriteria.getQueryObject().get("$and")); + List<Document> conditions = conditionDocuments.stream().map(el -> (Document) el.get("keyValues")).map(el -> (Document) el.get("$elemMatch")).collect(Collectors.toList()); + + assertThat(conditionDocuments).hasSize(3); + assertJsonPreparedKeyHasCorrectStructure(conditions.get(0), "stringKey"); + assertThat(conditions.get(0).get("v").toString()).isEqualTo(TemplateSearchHelper.getCaseInsensitive("^\\QstringValue\\E$").toString()); + + assertJsonPreparedKeyHasCorrectStructure(conditions.get(1), "numberKey"); + assertThat(conditions.get(1).get("v")).isEqualTo(16.0); + + assertJsonPreparedKeyHasCorrectStructure(conditions.get(2), "boolKey"); + assertThat(conditions.get(2).get("v")).isEqualTo("false"); + } + + @Test + void shouldThrowExceptionWhenNullIsPresentAsCriteriaValue() { + JsonObject jsonObject = GSON.fromJson("{\"stringKey\": \"stringValue\", \"nullKey\": null}", JsonObject.class); + + assertThrows(IllegalJsonValueException.class, () -> helper.getIdsOfDocumentMatchingCriteria(jsonObject)); + } + + private void assertJsonPreparedKeyHasCorrectStructure(Document actual, String expectedPattern) { + assertThat(actual.get("k").toString()).isEqualTo(Pattern.compile(String.format(":%s(?:(\\[[\\d]+\\]))?$", expectedPattern)).toString()); + + } +} diff --git a/src/test/java/org/onap/pnfsimulator/template/search/handler/PrimitiveValueCriteriaBuilderTest.java b/src/test/java/org/onap/pnfsimulator/template/search/handler/PrimitiveValueCriteriaBuilderTest.java new file mode 100644 index 0000000..6de86e0 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/template/search/handler/PrimitiveValueCriteriaBuilderTest.java @@ -0,0 +1,75 @@ +/*- + * ============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.pnfsimulator.template.search.handler; + +import com.google.gson.JsonPrimitive; +import org.junit.jupiter.api.Test; +import org.springframework.data.mongodb.core.query.Criteria; + +import static org.assertj.core.api.Java6Assertions.assertThat; + +class PrimitiveValueCriteriaBuilderTest { + + private PrimitiveValueCriteriaBuilder builder = new PrimitiveValueCriteriaBuilder(); + + @Test + void testShouldAddRegexLikeCriteriaForStringType() { + Criteria criteria = builder.applyValueCriteriaBasedOnPrimitiveType(Criteria.where("k").is("10").and("v"), new JsonPrimitive("sample")); + + assertThat(criteria.getCriteriaObject().toJson()).isEqualTo("{ \"k\" : \"10\", \"v\" : { \"$regex\" : \"^\\\\Qsample\\\\E$\", \"$options\" : \"iu\" } }"); + } + + @Test + void testShouldAddRegexLikeAndEscapeStringWithMetaChars() { + Criteria criteria = builder.applyValueCriteriaBasedOnPrimitiveType(Criteria.where("k").is("10").and("v"), new JsonPrimitive("[1,2,3,4,5]")); + + assertThat(criteria.getCriteriaObject().toJson()).isEqualTo("{ \"k\" : \"10\", \"v\" : { \"$regex\" : \"^\\\\Q[1,2,3,4,5]\\\\E$\", \"$options\" : \"iu\" } }"); + } + + @Test + void testShouldAddRegexLikeCriteriaForIntType() { + Criteria criteria = builder.applyValueCriteriaBasedOnPrimitiveType(Criteria.where("k").is("10").and("v"), new JsonPrimitive(1)); + + assertThat(criteria.getCriteriaObject().toJson()).isEqualTo("{ \"k\" : \"10\", \"v\" : 1.0 }"); + } + + @Test + void testShouldAddRegexLikeCriteriaForLongType() { + Criteria criteria = builder.applyValueCriteriaBasedOnPrimitiveType(Criteria.where("k").is("10").and("v"), new JsonPrimitive(Long.MAX_VALUE)); + + assertThat(criteria.getCriteriaObject().toJson()).isEqualTo("{ \"k\" : \"10\", \"v\" : 9.223372036854776E18 }"); + } + + @Test + void testShouldAddRegexLikeCriteriaForDoubleType() { + Criteria criteria = builder.applyValueCriteriaBasedOnPrimitiveType(Criteria.where("k").is("10").and("v"), new JsonPrimitive(2.5)); + + assertThat(criteria.getCriteriaObject().toJson()).isEqualTo("{ \"k\" : \"10\", \"v\" : 2.5 }"); + } + + @Test + void testShouldAddRegexLikeCriteriaForBooleanType() { + Criteria criteria = builder.applyValueCriteriaBasedOnPrimitiveType(Criteria.where("k").is("10").and("v"), new JsonPrimitive(true)); + + assertThat(criteria.getCriteriaObject().toJson()).isEqualTo("{ \"k\" : \"10\", \"v\" : \"true\" }"); + } + +} diff --git a/src/test/resources/application.properties b/src/test/resources/application.properties new file mode 100644 index 0000000..6815680 --- /dev/null +++ b/src/test/resources/application.properties @@ -0,0 +1,2 @@ +templates.dir=src/test/resources/org/onap/pnfsimulator/simulator +ssl.clientCertificateEnabled=false diff --git a/src/test/resources/certificates/client.p12 b/src/test/resources/certificates/client.p12 Binary files differnew file mode 100644 index 0000000..0bbec38 --- /dev/null +++ b/src/test/resources/certificates/client.p12 diff --git a/src/test/resources/certificates/client.pass b/src/test/resources/certificates/client.pass new file mode 100644 index 0000000..25acfbf --- /dev/null +++ b/src/test/resources/certificates/client.pass @@ -0,0 +1 @@ +collector
\ No newline at end of file diff --git a/src/test/resources/certificates/client_invalid.pass b/src/test/resources/certificates/client_invalid.pass new file mode 100644 index 0000000..0b54957 --- /dev/null +++ b/src/test/resources/certificates/client_invalid.pass @@ -0,0 +1 @@ +invalidpassword
\ No newline at end of file diff --git a/src/test/resources/certificates/truststore b/src/test/resources/certificates/truststore Binary files differnew file mode 100644 index 0000000..e90b710 --- /dev/null +++ b/src/test/resources/certificates/truststore diff --git a/src/test/resources/certificates/truststore.pass b/src/test/resources/certificates/truststore.pass new file mode 100644 index 0000000..25acfbf --- /dev/null +++ b/src/test/resources/certificates/truststore.pass @@ -0,0 +1 @@ +collector
\ No newline at end of file diff --git a/src/test/resources/certificates/truststore_invalid.pass b/src/test/resources/certificates/truststore_invalid.pass new file mode 100644 index 0000000..0b54957 --- /dev/null +++ b/src/test/resources/certificates/truststore_invalid.pass @@ -0,0 +1 @@ +invalidpassword
\ No newline at end of file diff --git a/src/test/resources/logback-test.xml b/src/test/resources/logback-test.xml new file mode 100644 index 0000000..0dedeba --- /dev/null +++ b/src/test/resources/logback-test.xml @@ -0,0 +1,55 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ============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========================================================= + --> + +<Configuration complete="true" compact="true"> + + <Property name="outputFilename" value="pnfsimulator_output"/> + <Property name="log-path" value="${java.io.tmpdir}"/> + <property name="maxFileSize" value="50MB"/> + <property name="maxHistory" value="30"/> + <property name="totalSizeCap" value="10GB"/> + <include resource="org/springframework/boot/logging/logback/defaults.xml"/> + + + <appender name="Console" target="SYSTEM_OUT" class="ch.qos.logback.core.ConsoleAppender"> + <encoder> + <Pattern>${CONSOLE_LOG_PATTERN}</Pattern> + </encoder> + </appender> + + <appender name="ROLLING-FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> + <encoder> + <pattern>${FILE_LOG_PATTERN}</pattern> + </encoder> + <File>${log-path}/${outputFilename}.log</File> + <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> + <FileNamePattern>${log-path}/${outputFilename}.%d{yyyy-MM-dd}.%i.log.zip</FileNamePattern> + <MaxFileSize>${maxFileSize}</MaxFileSize> + <MaxHistory>${maxHistory}</MaxHistory> + <TotalSizeCap>${totalSizeCap}</TotalSizeCap> + </rollingPolicy> + </appender> + + <root level="info"> + <appender-ref ref="Console" /> + <appender-ref ref="ROLLING-FILE" /> + </root> +</Configuration> diff --git a/src/test/resources/org/onap/pnfsimulator/simulator/filesystem/test1.json b/src/test/resources/org/onap/pnfsimulator/simulator/filesystem/test1.json new file mode 100644 index 0000000..89e4a76 --- /dev/null +++ b/src/test/resources/org/onap/pnfsimulator/simulator/filesystem/test1.json @@ -0,0 +1,12 @@ +{ + "field1": "value1", + "field2": 2, + "nested": { + "key1": [ + 1, + 2, + 3 + ], + "key2": "sampleValue2" + } +} diff --git a/src/test/resources/org/onap/pnfsimulator/simulator/invalidJsonStructureEvent.json b/src/test/resources/org/onap/pnfsimulator/simulator/invalidJsonStructureEvent.json new file mode 100644 index 0000000..4d6ef7d --- /dev/null +++ b/src/test/resources/org/onap/pnfsimulator/simulator/invalidJsonStructureEvent.json @@ -0,0 +1 @@ +{"sampleKey1": [{"sampleKey2": "1"}, {"sampleKey2": "2"}] diff --git a/src/test/resources/org/onap/pnfsimulator/simulator/validExampleMeasurementEvent.json b/src/test/resources/org/onap/pnfsimulator/simulator/validExampleMeasurementEvent.json new file mode 100644 index 0000000..a240b93 --- /dev/null +++ b/src/test/resources/org/onap/pnfsimulator/simulator/validExampleMeasurementEvent.json @@ -0,0 +1,86 @@ +{ + "event": { + "commonEventHeader": { + "domain": "measurementsForVfScaling", + "eventName": "vFirewallBroadcastPackets", + "eventId": "4cfc-91cf-31a46", + "nfType": "mrfx", + "priority": "Normal", + "reportingEntityName": "#dn", + "sequence": 1, + "sourceName": "ClosedLoopVNF", + "startEpochMicrosec": 1531616794, + "lastEpochMicrosec": 1531719042, + "version": 2.0 + }, + "measurementsForVfScalingFields": { + "measurementsForVfSclaingFieldsVersion": 2.0, + "measurementsForVfScalingVersion": 2.0, + "measurementInterval": 180, + "concurrentSessions": 2, + "cpuUsageArray": [ + { + "cpuIdentifier": "INTEL_CORE_I7_1", + "percentUsage": 50 + }, + { + "cpuIdentifier": "INTEL_CORE_I7_2", + "percentUsage": 70 + } + ], + "memoryUsageArray": [ + { + "vmIdentifier": "vmIdentifier", + "memoryFree": 50, + "memoryUsed": 10 + } + ], + "vNicUsageArray": [ + { + "receivedTotalPacketsDelta": 30 + } + ], + "numberOfMediaPortsInUse": 100, + "additionalMeasurements": [ + { + "name": "licenseUsage", + "arrayOfFields": [ + "#measurement", + { + "name": "G729AudioPort", + "value": "1" + }, + { + "name": "G722AudioPort", + "value": "1" + }, + { + "name": "AMRAudioPort", + "value": "4" + }, + { + "name": "AMRWBAudioPort", + "value": "5" + }, + { + "name": "OpusAudioPort", + "value": "6" + }, + { + "name": "H263VideoPort", + "value": "7" + }, + { + "name": "H264NonHCVideoPort", + "value": "8" + }, + { + "name": "H264HCVideoPort", + "value": "9" + } + ] + } + ] + } + } +} |