diff options
author | Bogumil Zebek <bogumil.zebek@nokia.com> | 2021-03-09 12:54:38 +0100 |
---|---|---|
committer | Zebek Bogumil <bogumil.zebek@nokia.com> | 2021-03-10 09:31:58 +0100 |
commit | 4af5241ab25b0103d8ea680789aaf9a8696dfc75 (patch) | |
tree | 36ccae11ebf094aa1ddd65df309b7531ce0db1ff /src/test/java/org/onap/pnfsimulator/rest | |
parent | c9975cb96ba4e0208e72399ed80f909beb95d9d9 (diff) |
Move pnf simulator to the new repo
In the first phase we renamed project from pnf simulator to vesclient.
Next steps: package rename, update Readme.md, upgrade project dependencies.
Issue-ID: INT-1869
Signed-off-by: Bogumil Zebek<bogumil.zebek@nokia.com>
Change-Id: I7714792f9739eb746c9c533e8ef41b9618a3a1d9
Diffstat (limited to 'src/test/java/org/onap/pnfsimulator/rest')
4 files changed, 689 insertions, 0 deletions
diff --git a/src/test/java/org/onap/pnfsimulator/rest/SimulatorControllerTest.java b/src/test/java/org/onap/pnfsimulator/rest/SimulatorControllerTest.java new file mode 100644 index 0000000..8dba750 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/rest/SimulatorControllerTest.java @@ -0,0 +1,329 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.pnfsimulator.rest; + +import com.google.common.collect.ImmutableMap; +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.pnfsimulator.event.EventData; +import org.onap.pnfsimulator.event.EventDataService; +import org.onap.pnfsimulator.rest.model.FullEvent; +import org.onap.pnfsimulator.rest.model.SimulatorParams; +import org.onap.pnfsimulator.rest.model.SimulatorRequest; +import org.onap.pnfsimulator.simulator.SimulatorService; +import org.onap.pnfsimulator.simulator.client.HttpResponseAdapter; +import org.onap.pnfsimulator.simulatorconfig.SimulatorConfig; +import org.quartz.SchedulerException; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import java.io.IOException; +import java.net.URL; +import java.security.GeneralSecurityException; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +class SimulatorControllerTest { + + private static final String START_ENDPOINT = "/simulator/start"; + private static final String CONFIG_ENDPOINT = "/simulator/config"; + private static final String EVENT_ENDPOINT = "/simulator/event"; + private static final String CANCEL_JOB_ENDPOINT = "/simulator/cancel/"; + private static final String ALL_EVENTS_ENDPOINT = "/simulator/all-events"; + private static final String TEST_ENDPOINT = "/simulator/test"; + + private static final String JSON_MSG_EXPRESSION = "$.message"; + private static final String EVENT_WAS_CANCELLED = "Event(s) was cancelled"; + private static final String EVENT_WAS_NOT_CANCELLED = "Simulator was not able to cancel event(s)"; + + private static final String NEW_URL = "http://0.0.0.0:8090/eventListener/v7"; + private static final String UPDATE_SIM_CONFIG_VALID_JSON = "{\"vesServerUrl\": \"" + + NEW_URL + "\"}"; + private static final String SAMPLE_ID = "sampleId"; + private static final Gson GSON_OBJ = new Gson(); + private static final String JOB_NAME = "testJobName"; + private static final HttpResponseAdapter TEST_HTTP_ACCEPTED_RESPONSE = new HttpResponseAdapter(202,""); + private static String simulatorRequestBody; + private MockMvc mockMvc; + @InjectMocks + private SimulatorController controller; + @Mock + private EventDataService eventDataService; + @Mock + private SimulatorService simulatorService; + + @BeforeAll + static void beforeAll() { + SimulatorParams simulatorParams = new SimulatorParams("http://0.0.0.0:8080", 1, 1); + SimulatorRequest simulatorRequest = new SimulatorRequest(simulatorParams, + "testTemplate.json", new JsonObject(), new JsonObject()); + + simulatorRequestBody = GSON_OBJ.toJson(simulatorRequest); + } + + @BeforeEach + void setup() throws IOException, SchedulerException, GeneralSecurityException { + MockitoAnnotations.initMocks(this); + when(simulatorService.triggerEvent(any())).thenReturn("jobName"); + when(simulatorService.triggerOneTimeEvent(any())).thenReturn(TEST_HTTP_ACCEPTED_RESPONSE); + mockMvc = MockMvcBuilders + .standaloneSetup(controller) + .build(); + } + + @Test + void shouldStartSimulatorProperly() throws Exception { + startSimulator(); + SimulatorRequest simulatorRequest = new Gson().fromJson(simulatorRequestBody, SimulatorRequest.class); + + verify(simulatorService).triggerEvent(eq(simulatorRequest)); + } + + @Test + void testShouldGetConfigurationWhenRequested() throws Exception { + String newUrl = "http://localhost:8090/eventListener/v7"; + SimulatorConfig expectedConfig = new SimulatorConfig(SAMPLE_ID, new URL(newUrl)); + when(simulatorService.getConfiguration()).thenReturn(expectedConfig); + + MvcResult getResult = mockMvc + .perform(get(CONFIG_ENDPOINT) + .contentType(MediaType.APPLICATION_JSON) + .content(UPDATE_SIM_CONFIG_VALID_JSON)) + .andExpect(status().isOk()) + .andReturn(); + + String expectedVesUrlJsonPart = createStringReprOfJson("vesServerUrl", newUrl); + assertThat(getResult.getResponse().getContentAsString()).contains(expectedVesUrlJsonPart); + } + + @Test + void testShouldSuccessfullyUpdateConfigurationWithNewVesUrl() throws Exception { + String oldUrl = "http://localhost:8090/eventListener/v7"; + SimulatorConfig expectedConfigBeforeUpdate = new SimulatorConfig(SAMPLE_ID, new URL(oldUrl)); + SimulatorConfig expectedConfigAfterUpdate = new SimulatorConfig(SAMPLE_ID, new URL(NEW_URL)); + + when(simulatorService.getConfiguration()).thenReturn(expectedConfigBeforeUpdate); + when(simulatorService.updateConfiguration(any(SimulatorConfig.class))).thenReturn(expectedConfigAfterUpdate); + + MvcResult postResult = mockMvc + .perform(put(CONFIG_ENDPOINT) + .contentType(MediaType.APPLICATION_JSON) + .content(UPDATE_SIM_CONFIG_VALID_JSON)) + .andExpect(status().isOk()) + .andReturn(); + + String expectedVesUrlJsonPart = createStringReprOfJson("vesServerUrl", expectedConfigAfterUpdate.getVesServerUrl().toString()); + assertThat(postResult.getResponse().getContentAsString()).contains(expectedVesUrlJsonPart); + } + + @Test + void testShouldRaiseExceptionWhenUpdateConfigWithIncorrectPayloadWasSent() throws Exception { + mockMvc + .perform(put(CONFIG_ENDPOINT) + .contentType(MediaType.APPLICATION_JSON) + .content("{\"vesUrl\": \"" + + NEW_URL + "\"}")) + .andExpect(status().isBadRequest()); + } + + @Test + void testShouldRaiseExceptionWhenUrlInInvalidFormatIsSent() throws Exception { + mockMvc + .perform(put(CONFIG_ENDPOINT) + .contentType(MediaType.APPLICATION_JSON) + .content("{\"vesUrl\": \"http://0.0.0.0:VES-PORT/eventListener/v7\"}")) + .andExpect(status().isBadRequest()); + } + + @Test + void testShouldSendEventDirectly() throws Exception { + String contentAsString = mockMvc + .perform(post(EVENT_ENDPOINT) + .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE) + .content("{\"vesServerUrl\":\"http://0.0.0.0:8080/simulator/v7\",\n" + + " \"event\":{ \n" + + " \"commonEventHeader\":{ \n" + + " \"domain\":\"notification\",\n" + + " \"eventName\":\"vFirewallBroadcastPackets\"\n" + + " },\n" + + " \"notificationFields\":{ \n" + + " \"arrayOfNamedHashMap\":[ \n" + + " { \n" + + " \"name\":\"A20161221.1031-1041.bin.gz\",\n" + + " \"hashMap\":{ \n" + + " \"fileformatType\":\"org.3GPP.32.435#measCollec\"}}]}}}")) + .andExpect(status().isAccepted()).andReturn().getResponse().getContentAsString(); + assertThat(contentAsString).contains("One-time direct event sent successfully"); + } + + @Test + void testShouldReplaceKeywordsAndSendEventDirectly() throws Exception { + String contentAsString = mockMvc + .perform(post(EVENT_ENDPOINT) + .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE) + .content("{\"vesServerUrl\": \"http://localhost:9999/eventListener\",\n" + + " \"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"eventId\": \"#RandomString(20)\",\n" + + " \"sourceName\": \"PATCHED_sourceName\",\n" + + " \"version\": 3.0\n}}}")) + .andExpect(status().isAccepted()).andReturn().getResponse().getContentAsString(); + assertThat(contentAsString).contains("One-time direct event sent successfully"); + + verify(simulatorService, Mockito.times(1)).triggerOneTimeEvent(any(FullEvent.class)); + } + + @Test + void shouldUseTestEndpointThenReceiveProperMessage() throws Exception { + String contentAsString = mockMvc + .perform(post(TEST_ENDPOINT) + .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE) + .content("{\"simulatorParams\": {\n" + + " \"vesServerUrl\": \"http://localhost:9999/eventListener\"\n" + + " },\n" + + " \"templateName\": \"testTemplateName\"\n" + + "}")) + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + assertThat(contentAsString).contains("message1234"); + } + + @Test + void shouldSuccessfullyCancelJobThenReturnProperMessage() throws Exception { + when(simulatorService.cancelEvent(JOB_NAME)).thenReturn(true); + + String contentAsString = mockMvc + .perform(post(CANCEL_JOB_ENDPOINT + JOB_NAME) + .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE) + .content("")) + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + + assertThat(contentAsString).contains(EVENT_WAS_CANCELLED); + } + + @Test + void shouldFailWhileCancelingJobThenReturnProperMessage() throws Exception { + when(simulatorService.cancelEvent(JOB_NAME)).thenReturn(false); + + String contentAsString = mockMvc + .perform(post(CANCEL_JOB_ENDPOINT + JOB_NAME) + .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE) + .content("")) + .andExpect(status().isNotFound()).andReturn().getResponse().getContentAsString(); + + assertThat(contentAsString).contains(EVENT_WAS_NOT_CANCELLED); + } + + @Test + void shouldSuccessfullyCancelAllJobsThenReturnsProperMessage() throws Exception { + when(simulatorService.cancelAllEvents()).thenReturn(true); + + String contentAsString = mockMvc + .perform(post(CANCEL_JOB_ENDPOINT) + .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE) + .content("")) + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + + assertThat(contentAsString).contains(EVENT_WAS_CANCELLED); + } + + @Test + void shouldSuccessfullyCancelJobWhenSendingJobNameWithBreakingCharactersThenReturnProperMessage() throws SchedulerException { + final String lineBreakingJobName = "test\tJob\nName\r"; + when(simulatorService.cancelEvent(lineBreakingJobName)).thenReturn(true); + + Object actualResponseBody = Objects.requireNonNull(controller.cancelEvent(lineBreakingJobName).getBody()); + + assertThat(actualResponseBody.toString()).contains(EVENT_WAS_CANCELLED); + } + + @Test + void shouldReturnAllEvents() throws Exception { + List<EventData> events = getEventDatas(); + String expectedMessage = events.stream() + .map(EventData::toString) + .collect(Collectors.joining("\\n")); + + when(eventDataService.getAllEvents()).thenReturn(events); + + String contentAsString = mockMvc + .perform(get(ALL_EVENTS_ENDPOINT) + .contentType(MediaType.APPLICATION_JSON) + .content("")) + .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); + + assertThat(contentAsString).contains(expectedMessage); + } + + + private List<EventData> getEventDatas() { + return Arrays.asList( + getEventData("id1", "keywords1", "input1", "patched1", "template1", 0), + getEventData("id2", "keywords2", "input2", "patched2", "template2", 1) + ); + } + + private EventData getEventData(String id, String keywords, String input, String patched, String template, int incrementValue) { + return EventData.builder() + .id(id) + .keywords(keywords) + .input(input) + .patched(patched) + .template(template) + .incrementValue(incrementValue) + .build(); + } + + private void startSimulator() throws Exception { + mockMvc + .perform(post(START_ENDPOINT) + .content(simulatorRequestBody) + .contentType(MediaType.APPLICATION_JSON).characterEncoding("utf-8")) + .andExpect(status().isOk()) + .andExpect(jsonPath(JSON_MSG_EXPRESSION).value("Request started")); + + } + + private String createStringReprOfJson(String key, String value) { + return GSON_OBJ.toJson(ImmutableMap.of(key, value)); + } +} diff --git a/src/test/java/org/onap/pnfsimulator/rest/TemplateControllerTest.java b/src/test/java/org/onap/pnfsimulator/rest/TemplateControllerTest.java new file mode 100644 index 0000000..17be475 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/rest/TemplateControllerTest.java @@ -0,0 +1,256 @@ +/*- + * ============LICENSE_START======================================================= + * Simulator + * ================================================================================ + * Copyright (C) 2019 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.pnfsimulator.rest; + +import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.onap.pnfsimulator.rest.TemplateController.CANNOT_OVERRIDE_TEMPLATE_MSG; +import static org.onap.pnfsimulator.rest.TemplateController.TEMPLATE_NOT_FOUND_MSG; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.mockito.Mockito.times; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; +import com.google.gson.reflect.TypeToken; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +import org.assertj.core.util.Lists; +import org.bson.Document; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.pnfsimulator.db.Storage; +import org.onap.pnfsimulator.rest.model.SearchExp; +import org.onap.pnfsimulator.template.Template; +import org.onap.pnfsimulator.template.search.IllegalJsonValueException; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + + +class TemplateControllerTest { + + private static final String LIST_URL = "/template/list"; + private static final String GET_FORMAT_STR = "/template/get/%s"; + private static final String SEARCH_ENDPOINT = "/template/search"; + private static final String UPLOAD_URL_NOFORCE = "/template/upload"; + private static final String UPLOAD_URL_FORCE = "/template/upload?override=true"; + private static final String SAMPLE_TEMPLATE_JSON = "{\"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": \"measurementsForVfScaling\",\n" + + " \"eventName\": \"vFirewallBroadcastPackets\",\n" + + " }" + + "}}"; + + public static final String TEMPLATE_REQUEST = "{\n" + + " \"name\": \"someTemplate\",\n" + + " \"template\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": \"notification\",\n" + + " \"eventName\": \"vFirewallBroadcastPackets\"\n" + + " },\n" + + " \"notificationFields\": {\n" + + " \"arrayOfNamedHashMap\": [{\n" + + " \"name\": \"A20161221.1031-1041.bin.gz\",\n" + + "\n" + + " \"hashMap\": {\n" + + " \"fileformatType\": \"org.3GPP.32.435#measCollec\"\n" + + " }\n" + + " }]\n" + + " }\n" + + " }\n" + + "}"; + private static final Document SAMPLE_TEMPLATE_BSON = Document.parse(SAMPLE_TEMPLATE_JSON); + private static final List<String> SAMPLE_TEMPLATE_NAME_LIST = Lists.newArrayList("notification.json", "registration.json"); + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + private static final Gson GSON_OBJ = new GsonBuilder().create(); + private MockMvc mockMvc; + + @Mock + private Storage<Template> templateService; + @InjectMocks + private TemplateController controller; + + @BeforeEach + void setup() { + MockitoAnnotations.initMocks(this); + mockMvc = MockMvcBuilders + .standaloneSetup(controller) + .build(); + } + + @Test + void shouldGetAllTemplates() throws Exception { + List<Template> templateList = createTemplatesList(); + when(templateService.getAll()).thenReturn(templateList); + + MvcResult getResult = mockMvc + .perform(get(LIST_URL) + .accept(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andReturn(); + + Type listType = new TypeToken<ArrayList<Template>>() {}.getType(); + List<Template> resultList = GSON_OBJ.fromJson(getResult.getResponse().getContentAsString(), listType); + assertThat(resultList).containsExactlyInAnyOrderElementsOf(templateList); + } + + @Test + void shouldListEmptyCollectionWhenNoTemplatesAvailable() throws Exception { + List<Template> templateList = Collections.emptyList(); + when(templateService.getAll()).thenReturn(templateList); + + MvcResult getResult = mockMvc + .perform(get(LIST_URL)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andReturn(); + + String templatesAsString = GSON_OBJ.toJson(templateList); + assertThat(getResult.getResponse().getContentAsString()).containsSequence(templatesAsString); + } + + @Test + void shouldSuccessfullyGetExisitngTemplateByName() throws Exception { + String sampleTemplateName = "someTemplate"; + String requestUrl = String.format(GET_FORMAT_STR, sampleTemplateName); + Template sampleTemplate = new Template(sampleTemplateName, SAMPLE_TEMPLATE_BSON, 0L); + + when(templateService.get(sampleTemplateName)).thenReturn(Optional.of(sampleTemplate)); + + MvcResult getResult = mockMvc + .perform(get(requestUrl)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andReturn(); + + Template result = new Gson().fromJson(getResult.getResponse().getContentAsString(), Template.class); + assertThat(result).isEqualTo(sampleTemplate); + } + + @Test + void shouldReturnNotFoundWhenGetNonExisitngTemplateByName() throws Exception { + String sampleTemplateName = "doesNotExist"; + String requestUrl = String.format(GET_FORMAT_STR, sampleTemplateName); + + when(templateService.get(sampleTemplateName)).thenReturn(Optional.empty()); + + MvcResult getResult = mockMvc + .perform(get(requestUrl)) + .andExpect(status().isNotFound()) + .andExpect(content().contentType(MediaType.TEXT_PLAIN_VALUE)) + .andReturn(); + + assertThat(getResult.getResponse().getContentLength()).isEqualTo(TEMPLATE_NOT_FOUND_MSG.length()); + } + + + @Test + void shouldReturnNamesOfTemplatesThatSatisfyGivenCriteria() throws Exception { + when(templateService.getIdsByContentCriteria(any(JsonObject.class))).thenReturn(SAMPLE_TEMPLATE_NAME_LIST); + SearchExp expr = new SearchExp(new JsonObject()); + + String responseContent = mockMvc + .perform(post(SEARCH_ENDPOINT).content(GSON_OBJ.toJson(expr)).contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andReturn().getResponse().getContentAsString(); + + List<String> actualTemplates = OBJECT_MAPPER.readValue(responseContent, new TypeReference<List<String>>() {}); + verify(templateService, times(1)).getIdsByContentCriteria(any(JsonObject.class)); + assertThat(actualTemplates).isEqualTo(SAMPLE_TEMPLATE_NAME_LIST); + } + + @Test + void shouldRaiseBadRequestWhenNullValueProvidedInSearchJsonAsJsonValue() throws Exception { + when(templateService.getIdsByContentCriteria(any(JsonObject.class))).thenThrow(IllegalJsonValueException.class); + SearchExp expr = new SearchExp(new JsonObject()); + + mockMvc.perform(post(SEARCH_ENDPOINT) + .content(GSON_OBJ.toJson(expr)) + .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) + .andExpect(status().isBadRequest()); + } + + + @Test + void testTryUploadNewTemplate() throws Exception { + when(templateService.tryPersistOrOverwrite(any(Template.class), eq(false))).thenReturn(true); + + MvcResult postResult = mockMvc + .perform(post(UPLOAD_URL_NOFORCE) + .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE) + .content(TEMPLATE_REQUEST)) + .andExpect(status().isCreated()) + .andReturn(); + } + + @Test + void testTryUploadNewTemplateWithForce() throws Exception { + when(templateService.tryPersistOrOverwrite(any(Template.class), eq(true))).thenReturn(true); + + MvcResult postResult = mockMvc + .perform(post(UPLOAD_URL_FORCE) + .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE) + .content(TEMPLATE_REQUEST)) + .andExpect(status().isCreated()) + .andReturn(); + } + + @Test + void testOverrideExistingTemplateWithoutForceShouldFail() throws Exception { + when(templateService.tryPersistOrOverwrite(any(Template.class), eq(true))).thenReturn(false); + + MvcResult postResult = mockMvc + .perform(post(UPLOAD_URL_FORCE) + .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE) + .content(TEMPLATE_REQUEST)) + .andExpect(status().isConflict()) + .andReturn(); + + assertThat(postResult.getResponse().getContentAsString()).isEqualTo(CANNOT_OVERRIDE_TEMPLATE_MSG); + } + + private List<Template> createTemplatesList() { + return Arrays.asList( + new Template("1", SAMPLE_TEMPLATE_BSON, 0L), + new Template("2", SAMPLE_TEMPLATE_BSON, 0L), + new Template("3", SAMPLE_TEMPLATE_BSON, 0L)); + } +} diff --git a/src/test/java/org/onap/pnfsimulator/rest/util/DateUtilTest.java b/src/test/java/org/onap/pnfsimulator/rest/util/DateUtilTest.java new file mode 100644 index 0000000..1591a59 --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/rest/util/DateUtilTest.java @@ -0,0 +1,38 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.pnfsimulator.rest.util; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.text.SimpleDateFormat; +import java.util.Calendar; +import org.junit.jupiter.api.Test; + +class DateUtilTest { + + @Test + void getFormattedDate() { + Calendar currentCalendar = Calendar.getInstance(); + String expectedResult = String.valueOf(currentCalendar.get(Calendar.YEAR)); + + assertEquals(expectedResult, DateUtil.getTimestamp(new SimpleDateFormat("yyyy"))); + } +} diff --git a/src/test/java/org/onap/pnfsimulator/rest/util/ResponseBuilderTest.java b/src/test/java/org/onap/pnfsimulator/rest/util/ResponseBuilderTest.java new file mode 100644 index 0000000..4e8e4dc --- /dev/null +++ b/src/test/java/org/onap/pnfsimulator/rest/util/ResponseBuilderTest.java @@ -0,0 +1,66 @@ +/* + * ============LICENSE_START======================================================= + * PNF-REGISTRATION-HANDLER + * ================================================================================ + * Copyright (C) 2018 Nokia. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.pnfsimulator.rest.util; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.util.Map; + +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; + +class ResponseBuilderTest { + + + private static final HttpStatus SAMPLE_STATUS = HttpStatus.OK; + + @Test + void response_should_have_empty_body_when_built_immediately() { + ResponseEntity responseEntity = ResponseBuilder.status(SAMPLE_STATUS).build(); + + assertAll( + () -> assertEquals(SAMPLE_STATUS, responseEntity.getStatusCode()), + () -> assertNull(responseEntity.getBody()) + ); + } + + @Test + void builder_should_set_response_status_and_body() { + String key = "key"; + String value = "value"; + ResponseEntity response = ResponseBuilder + .status(SAMPLE_STATUS) + .put(key, value) + .build(); + + Map<String, Object> body = (Map<String, Object>) response.getBody(); + + assertAll( + () -> assertEquals(SAMPLE_STATUS, response.getStatusCode()), + () -> assertEquals(value, body.get(key)) + ); + } + + +} |