diff options
author | 2020-04-08 09:31:13 +0200 | |
---|---|---|
committer | 2020-04-08 09:43:31 +0000 | |
commit | 3c494af52c476a86ae1389991b464914517774b8 (patch) | |
tree | e6d9b4f261eac5f7b3fd0f42e740840a106842e6 /pnfsimulator/src/test/java/org/onap | |
parent | 75496bfc5b2f7e03e49ab4929d1f20962b39c992 (diff) |
Move PNF simulator from /test/mocks to new project
This code is a copy of pnfsimulator located in integration repository
(/test/mocks/pnfsimulator) with added profile "docker" in pom.xml
located in pnfsimulator and netconfsimulator subprojects
Issue-ID: INT-1517
Signed-off-by: Bartosz Gardziejewski <bartosz.gardziejewski@nokia.com>
Change-Id: I725fa0530c41b13cb12705979dee8b8b354dc1a1
Diffstat (limited to 'pnfsimulator/src/test/java/org/onap')
30 files changed, 3384 insertions, 0 deletions
diff --git a/pnfsimulator/src/test/java/org/onap/pnfsimulator/event/EventDataServiceTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/event/EventDataServiceTest.java new file mode 100644 index 0000000..5ed51cc --- /dev/null +++ b/pnfsimulator/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/pnfsimulator/src/test/java/org/onap/pnfsimulator/filesystem/InMemoryTemplateStorage.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/filesystem/InMemoryTemplateStorage.java new file mode 100644 index 0000000..98c4bc5 --- /dev/null +++ b/pnfsimulator/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/pnfsimulator/src/test/java/org/onap/pnfsimulator/filesystem/WatcherEventProcessorTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/filesystem/WatcherEventProcessorTest.java new file mode 100644 index 0000000..42ed4d3 --- /dev/null +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/filesystem/WatcherEventProcessorTest.java @@ -0,0 +1,124 @@ +/*- + * ============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(storage.getAll().size(), 1); + Optional<Template> templateFromStorage = storage.get("test1.json"); + if (templateFromStorage.isPresent()) { + Template retrievedTemplate = templateFromStorage.get(); + Document templateContent = retrievedTemplate.getContent(); + Document flatContent = retrievedTemplate.getFlatContent(); + Assertions.assertEquals(templateContent.getString("field1"), "value1"); + Assertions.assertEquals(templateContent.getInteger("field2", 0), 2); + Assertions.assertEquals(flatContent.getInteger(":nested:key1[0]", 0), 1); + Assertions.assertEquals(flatContent.getInteger(":nested:key1[1]", 0), 2); + Assertions.assertEquals(flatContent.getInteger(":nested:key1[2]", 0), 3); + Assertions.assertEquals(flatContent.getString(":nested:key2"), "sampleValue2"); + } 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(storage.getAll().size(), 0); + } + + private void initStubs() { + Mockito.when(templatesDir.resolve(jsonFilePath)).thenReturn(jsonFilePath); + Mockito.when(watchEvent.context()).thenReturn(jsonFilePath); + } + +} diff --git a/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/SimulatorControllerTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/SimulatorControllerTest.java new file mode 100644 index 0000000..dae16c7 --- /dev/null +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/SimulatorControllerTest.java @@ -0,0 +1,212 @@ +/* + * ============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.rest.model.FullEvent; +import org.onap.pnfsimulator.rest.model.SimulatorParams; +import org.onap.pnfsimulator.rest.model.SimulatorRequest; +import org.onap.pnfsimulator.rest.util.JsonObjectDeserializer; +import org.onap.pnfsimulator.simulator.SimulatorService; +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.result.MockMvcResultHandlers; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import java.io.IOException; +import java.net.URL; +import java.security.GeneralSecurityException; + +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 JSON_MSG_EXPRESSION = "$.message"; + + 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 String simulatorRequestBody; + private MockMvc mockMvc; + @InjectMocks + private SimulatorController controller; + @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()); + + simulatorRequestBody = GSON_OBJ.toJson(simulatorRequest); + } + + @BeforeEach + void setup() throws IOException, SchedulerException, GeneralSecurityException { + MockitoAnnotations.initMocks(this); + when(simulatorService.triggerEvent(any())).thenReturn("jobName"); + 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)); + } + + + 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/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/TemplateControllerTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/TemplateControllerTest.java new file mode 100644 index 0000000..f34d73c --- /dev/null +++ b/pnfsimulator/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.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +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 static org.mockito.Mockito.times; +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/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/util/DateUtilTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/util/DateUtilTest.java new file mode 100644 index 0000000..1591a59 --- /dev/null +++ b/pnfsimulator/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/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/util/ResponseBuilderTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/util/ResponseBuilderTest.java new file mode 100644 index 0000000..0d62ee9 --- /dev/null +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/rest/util/ResponseBuilderTest.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.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(responseEntity.getStatusCode(), SAMPLE_STATUS), + () -> assertNull(responseEntity.getBody()) + ); + } + + @Test + void builder_should_set_response_status_and_body() { + String key = "key"; + String value = "value"; + ResponseEntity response = ResponseBuilder + .status(SAMPLE_STATUS) + .put(key, value) + .build(); + + Map<String, Object> body = (Map<String, Object>) response.getBody(); + + assertAll( + () -> assertEquals(SAMPLE_STATUS, response.getStatusCode()), + () -> assertEquals(value, body.get(key)) + ); + } + + +} diff --git a/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/IncrementProviderImplTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/IncrementProviderImplTest.java new file mode 100644 index 0000000..53f02da --- /dev/null +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/IncrementProviderImplTest.java @@ -0,0 +1,78 @@ +/* + * ============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/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorInvalidRandomIntegerTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorInvalidRandomIntegerTest.java new file mode 100644 index 0000000..8198e95 --- /dev/null +++ b/pnfsimulator/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/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorInvalidRandomStringTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorInvalidRandomStringTest.java new file mode 100644 index 0000000..6834c0d --- /dev/null +++ b/pnfsimulator/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/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorInvalidTimestampTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorInvalidTimestampTest.java new file mode 100644 index 0000000..eda4070 --- /dev/null +++ b/pnfsimulator/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/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorValidRandomIntegerTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorValidRandomIntegerTest.java new file mode 100644 index 0000000..be79488 --- /dev/null +++ b/pnfsimulator/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/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorValidRandomPrimitiveIntegerTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorValidRandomPrimitiveIntegerTest.java new file mode 100644 index 0000000..0843ad1 --- /dev/null +++ b/pnfsimulator/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/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorValidRandomStringTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorValidRandomStringTest.java new file mode 100644 index 0000000..f0fdc0f --- /dev/null +++ b/pnfsimulator/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/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorValidTimestampPrimitiveTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorValidTimestampPrimitiveTest.java new file mode 100644 index 0000000..7743e55 --- /dev/null +++ b/pnfsimulator/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/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorValidTimestampTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorValidTimestampTest.java new file mode 100644 index 0000000..f5c12c3 --- /dev/null +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsExtractorValidTimestampTest.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 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/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsHandlerTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsHandlerTest.java new file mode 100644 index 0000000..e67d4a3 --- /dev/null +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsHandlerTest.java @@ -0,0 +1,304 @@ +/* + * ============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/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsValueProviderTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsValueProviderTest.java new file mode 100644 index 0000000..73e4c31 --- /dev/null +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/KeywordsValueProviderTest.java @@ -0,0 +1,81 @@ +/* + * ============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(supplierResult.length(), DEFAULT_STRING_LENGTH); + } + + @RepeatedTest(10) + void randomStringTest() { + int length = new Random().nextInt(15) + 1; + String supplierResult = KeywordsValueProvider.getRandomString().apply(length); + assertEquals(supplierResult.length(), 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(supplierResult.length(), 10); + } + +} diff --git a/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/SimulatorServiceTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/SimulatorServiceTest.java new file mode 100644 index 0000000..0196eb0 --- /dev/null +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/SimulatorServiceTest.java @@ -0,0 +1,227 @@ +/* + * ============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.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.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.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doNothing; +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 Gson GSON = new Gson(); + private static final JsonObject VALID_PATCH = GSON.fromJson("{\"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"sourceName\": \"SomeCustomSource\"}}}\n", JsonObject.class); + private static 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 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 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 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 SimulatorService simulatorService; + private EventDataService eventDataService; + private EventScheduler eventScheduler; + private SimulatorConfigService simulatorConfigService; + private static TemplatePatcher templatePatcher = new TemplatePatcher(); + private static TemplateReader templateReader = new FilesystemTemplateReader( + "src/test/resources/org/onap/pnfsimulator/simulator/", GSON); + + @BeforeEach + void setUp() { + eventDataService = mock(EventDataService.class); + eventScheduler = mock(EventScheduler.class); + simulatorConfigService = mock(SimulatorConfigService.class); + + simulatorService = new SimulatorService(templatePatcher, templateReader, + eventScheduler, eventDataService, simulatorConfigService, 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); + + 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); + } + + @Test + void shouldTriggerEventWithDefaultVesUrlWhenNotProvidedInRequest() throws IOException, SchedulerException, GeneralSecurityException { + String templateName = "validExampleMeasurementEvent.json"; + SimulatorRequest simulatorRequest = new SimulatorRequest( + new SimulatorParams("", 1, 1), + templateName, VALID_PATCH); + + URL inDbVesUrl = new URL("http://0.0.0.0:8080/eventListener/v6"); + 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); + 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); + + URL inDbVesUrl = new URL("http://0.0.0.0:8080/eventListener/v6"); + 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 SSLAuthenticationHelper())); + + HttpClientAdapter adapterMock = mock(HttpClientAdapter.class); + doNothing().when(adapterMock).send(eventContentCaptor.capture()); + doReturn(adapterMock).when(spiedTestedService).createHttpClientAdapter(any(String.class)); + 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 SSLAuthenticationHelper())); + + HttpClientAdapter adapterMock = mock(HttpClientAdapter.class); + doNothing().when(adapterMock).send(eventContentCaptor.capture()); + doReturn(adapterMock).when(spiedTestedService).createHttpClientAdapter(any(String.class)); + 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); + } + + + 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)); + } +} diff --git a/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/TemplatePatcherTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/TemplatePatcherTest.java new file mode 100644 index 0000000..52e0d6a --- /dev/null +++ b/pnfsimulator/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 newDomainJO = newDomain.getAsJsonObject(); + AssertionsForInterfaceTypes.assertThat(newDomainJO.keySet()).containsExactly("extraFields"); + JsonObject newDomainExtraFields = newDomainJO.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/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/TemplateReaderTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/TemplateReaderTest.java new file mode 100644 index 0000000..f029fce --- /dev/null +++ b/pnfsimulator/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/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapterImplTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapterImplTest.java new file mode 100644 index 0000000..63c1b72 --- /dev/null +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/client/HttpClientAdapterImplTest.java @@ -0,0 +1,99 @@ +/* + * ============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.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.conn.socket.PlainConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.onap.pnfsimulator.simulator.client.utils.ssl.SSLAuthenticationHelper; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.security.GeneralSecurityException; + +import static org.assertj.core.api.Assertions.assertThat; +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.mock; +import static org.mockito.Mockito.verify; + +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"); + } + + @Test + void sendShouldSuccessfullySendRequestGivenValidUrlUsingHTTPS() throws IOException { + assertAdapterSentRequest("https://valid-url:8443"); + } + + @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 void assertAdapterSentRequest(String targetUrl) throws IOException { + HttpClientAdapter adapter = new HttpClientAdapterImpl(httpClient, targetUrl); + doReturn(httpResponse).when(httpClient).execute(any()); + + adapter.send("test-msg"); + + verify(httpClient).execute(any()); + verify(httpResponse).getStatusLine(); + } +} diff --git a/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/client/utils/ssl/SslSupportLevelTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/client/utils/ssl/SslSupportLevelTest.java new file mode 100644 index 0000000..ff41c44 --- /dev/null +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/client/utils/ssl/SslSupportLevelTest.java @@ -0,0 +1,52 @@ +/* + * ============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.utils.ssl; + +import org.junit.jupiter.api.Test; + +import java.net.MalformedURLException; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class SslSupportLevelTest { + + private static final String HTTPS_URL = "https://127.0.0.1:8443/"; + private static final String HTTP_URL = "http://127.0.0.1:8080/"; + + @Test + void testShouldReturnAlwaysTrustSupportLevelForHttpsUrl() throws MalformedURLException { + SslSupportLevel actualSupportLevel = SslSupportLevel.getSupportLevelBasedOnProtocol(HTTPS_URL); + assertEquals(actualSupportLevel, SslSupportLevel.ALWAYS_TRUST); + } + + @Test + void testShouldReturnNoneSupportLevelForHttpUrl() throws MalformedURLException { + SslSupportLevel actualSupportLevel = SslSupportLevel.getSupportLevelBasedOnProtocol(HTTP_URL); + assertEquals(actualSupportLevel, SslSupportLevel.NONE); + } + + @Test + void testShouldRaiseExceptionWhenInvalidUrlPassed(){ + assertThrows(MalformedURLException.class, () -> SslSupportLevel.getSupportLevelBasedOnProtocol("http://bla:VES-PORT/")); + } + +} diff --git a/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/scheduler/EventJobTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/scheduler/EventJobTest.java new file mode 100644 index 0000000..25ed84c --- /dev/null +++ b/pnfsimulator/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/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/scheduler/EventSchedulerTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/scheduler/EventSchedulerTest.java new file mode 100644 index 0000000..84df5e9 --- /dev/null +++ b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulator/scheduler/EventSchedulerTest.java @@ -0,0 +1,149 @@ +/* + * ============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.net.MalformedURLException; +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/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulatorconfig/SimulatorConfigServiceTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/simulatorconfig/SimulatorConfigServiceTest.java new file mode 100644 index 0000000..4ed0972 --- /dev/null +++ b/pnfsimulator/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/pnfsimulator/src/test/java/org/onap/pnfsimulator/template/TemplateServiceTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/template/TemplateServiceTest.java new file mode 100644 index 0000000..0746960 --- /dev/null +++ b/pnfsimulator/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/pnfsimulator/src/test/java/org/onap/pnfsimulator/template/search/JsonUtilsTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/template/search/JsonUtilsTest.java new file mode 100644 index 0000000..fa0bed1 --- /dev/null +++ b/pnfsimulator/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/pnfsimulator/src/test/java/org/onap/pnfsimulator/template/search/TemplateSearchHelperTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/template/search/TemplateSearchHelperTest.java new file mode 100644 index 0000000..aeef870 --- /dev/null +++ b/pnfsimulator/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/pnfsimulator/src/test/java/org/onap/pnfsimulator/template/search/handler/PrimitiveValueCriteriaBuilderTest.java b/pnfsimulator/src/test/java/org/onap/pnfsimulator/template/search/handler/PrimitiveValueCriteriaBuilderTest.java new file mode 100644 index 0000000..31bcf1c --- /dev/null +++ b/pnfsimulator/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\" }"); + } + +} |