2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019 Nokia. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.pnfsimulator.rest;
23 import static org.assertj.core.api.Java6Assertions.assertThat;
24 import static org.mockito.ArgumentMatchers.eq;
25 import static org.mockito.ArgumentMatchers.any;
26 import static org.mockito.Mockito.verify;
27 import static org.mockito.Mockito.when;
28 import static org.onap.pnfsimulator.rest.TemplateController.CANNOT_OVERRIDE_TEMPLATE_MSG;
29 import static org.onap.pnfsimulator.rest.TemplateController.TEMPLATE_NOT_FOUND_MSG;
30 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
31 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
32 import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
33 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
34 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
36 import com.fasterxml.jackson.core.type.TypeReference;
37 import com.fasterxml.jackson.databind.ObjectMapper;
38 import com.google.gson.Gson;
39 import com.google.gson.GsonBuilder;
40 import com.google.gson.JsonObject;
41 import com.google.gson.reflect.TypeToken;
42 import java.lang.reflect.Type;
43 import java.util.ArrayList;
44 import java.util.Arrays;
45 import java.util.Collections;
46 import java.util.List;
47 import java.util.Optional;
49 import org.assertj.core.util.Lists;
50 import org.bson.Document;
51 import org.junit.jupiter.api.BeforeEach;
52 import org.junit.jupiter.api.Test;
53 import org.mockito.InjectMocks;
54 import org.mockito.Mock;
55 import static org.mockito.Mockito.times;
56 import org.mockito.MockitoAnnotations;
57 import org.onap.pnfsimulator.db.Storage;
58 import org.onap.pnfsimulator.rest.model.SearchExp;
59 import org.onap.pnfsimulator.template.Template;
60 import org.onap.pnfsimulator.template.search.IllegalJsonValueException;
61 import org.springframework.http.MediaType;
62 import org.springframework.test.web.servlet.MockMvc;
63 import org.springframework.test.web.servlet.MvcResult;
64 import org.springframework.test.web.servlet.setup.MockMvcBuilders;
66 class TemplateControllerTest {
68 private static final String LIST_URL = "/template/list";
69 private static final String GET_FORMAT_STR = "/template/get/%s";
70 private static final String SEARCH_ENDPOINT = "/template/search";
71 private static final String UPLOAD_URL_NOFORCE = "/template/upload";
72 private static final String UPLOAD_URL_FORCE = "/template/upload?override=true";
73 private static final String SAMPLE_TEMPLATE_JSON = "{\"event\": {\n"
74 + " \"commonEventHeader\": {\n"
75 + " \"domain\": \"measurementsForVfScaling\",\n"
76 + " \"eventName\": \"vFirewallBroadcastPackets\",\n"
80 public static final String TEMPLATE_REQUEST = "{\n"
81 + " \"name\": \"someTemplate\",\n"
82 + " \"template\": {\n"
83 + " \"commonEventHeader\": {\n"
84 + " \"domain\": \"notification\",\n"
85 + " \"eventName\": \"vFirewallBroadcastPackets\"\n"
87 + " \"notificationFields\": {\n"
88 + " \"arrayOfNamedHashMap\": [{\n"
89 + " \"name\": \"A20161221.1031-1041.bin.gz\",\n"
92 + " \"fileformatType\": \"org.3GPP.32.435#measCollec\"\n"
98 private static final Document SAMPLE_TEMPLATE_BSON = Document.parse(SAMPLE_TEMPLATE_JSON);
99 private static final List<String> SAMPLE_TEMPLATE_NAME_LIST = Lists.newArrayList("notification.json", "registration.json");
100 private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
101 private static final Gson GSON_OBJ = new GsonBuilder().create();
102 private MockMvc mockMvc;
105 private Storage<Template> templateService;
107 private TemplateController controller;
111 MockitoAnnotations.initMocks(this);
112 mockMvc = MockMvcBuilders
113 .standaloneSetup(controller)
118 void shouldGetAllTemplates() throws Exception {
119 List<Template> templateList = createTemplatesList();
120 when(templateService.getAll()).thenReturn(templateList);
122 MvcResult getResult = mockMvc
123 .perform(get(LIST_URL)
124 .accept(MediaType.APPLICATION_JSON))
125 .andExpect(status().isOk())
126 .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
129 Type listType = new TypeToken<ArrayList<Template>>() {}.getType();
130 List<Template> resultList = GSON_OBJ.fromJson(getResult.getResponse().getContentAsString(), listType);
131 assertThat(resultList).containsExactlyInAnyOrderElementsOf(templateList);
135 void shouldListEmptyCollectionWhenNoTemplatesAvailable() throws Exception {
136 List<Template> templateList = Collections.emptyList();
137 when(templateService.getAll()).thenReturn(templateList);
139 MvcResult getResult = mockMvc
140 .perform(get(LIST_URL))
141 .andExpect(status().isOk())
142 .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
145 String templatesAsString = GSON_OBJ.toJson(templateList);
146 assertThat(getResult.getResponse().getContentAsString()).containsSequence(templatesAsString);
150 void shouldSuccessfullyGetExisitngTemplateByName() throws Exception {
151 String sampleTemplateName = "someTemplate";
152 String requestUrl = String.format(GET_FORMAT_STR, sampleTemplateName);
153 Template sampleTemplate = new Template(sampleTemplateName, SAMPLE_TEMPLATE_BSON, 0L);
155 when(templateService.get(sampleTemplateName)).thenReturn(Optional.of(sampleTemplate));
157 MvcResult getResult = mockMvc
158 .perform(get(requestUrl))
159 .andExpect(status().isOk())
160 .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
163 Template result = new Gson().fromJson(getResult.getResponse().getContentAsString(), Template.class);
164 assertThat(result).isEqualTo(sampleTemplate);
168 void shouldReturnNotFoundWhenGetNonExisitngTemplateByName() throws Exception {
169 String sampleTemplateName = "doesNotExist";
170 String requestUrl = String.format(GET_FORMAT_STR, sampleTemplateName);
172 when(templateService.get(sampleTemplateName)).thenReturn(Optional.empty());
174 MvcResult getResult = mockMvc
175 .perform(get(requestUrl))
176 .andExpect(status().isNotFound())
177 .andExpect(content().contentType(MediaType.TEXT_PLAIN_VALUE))
180 assertThat(getResult.getResponse().getContentLength()).isEqualTo(TEMPLATE_NOT_FOUND_MSG.length());
185 void shouldReturnNamesOfTemplatesThatSatisfyGivenCriteria() throws Exception {
186 when(templateService.getIdsByContentCriteria(any(JsonObject.class))).thenReturn(SAMPLE_TEMPLATE_NAME_LIST);
187 SearchExp expr = new SearchExp(new JsonObject());
189 String responseContent = mockMvc
190 .perform(post(SEARCH_ENDPOINT).content(GSON_OBJ.toJson(expr)).contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
191 .andExpect(status().isOk())
192 .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
193 .andReturn().getResponse().getContentAsString();
195 List<String> actualTemplates = OBJECT_MAPPER.readValue(responseContent, new TypeReference<List<String>>() {});
196 verify(templateService, times(1)).getIdsByContentCriteria(any(JsonObject.class));
197 assertThat(actualTemplates).isEqualTo(SAMPLE_TEMPLATE_NAME_LIST);
201 void shouldRaiseBadRequestWhenNullValueProvidedInSearchJsonAsJsonValue() throws Exception {
202 when(templateService.getIdsByContentCriteria(any(JsonObject.class))).thenThrow(IllegalJsonValueException.class);
203 SearchExp expr = new SearchExp(new JsonObject());
205 mockMvc.perform(post(SEARCH_ENDPOINT)
206 .content(GSON_OBJ.toJson(expr))
207 .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
208 .andExpect(status().isBadRequest());
213 void testTryUploadNewTemplate() throws Exception {
214 when(templateService.tryPersistOrOverwrite(any(Template.class), eq(false))).thenReturn(true);
216 MvcResult postResult = mockMvc
217 .perform(post(UPLOAD_URL_NOFORCE)
218 .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
219 .content(TEMPLATE_REQUEST))
220 .andExpect(status().isCreated())
225 void testTryUploadNewTemplateWithForce() throws Exception {
226 when(templateService.tryPersistOrOverwrite(any(Template.class), eq(true))).thenReturn(true);
228 MvcResult postResult = mockMvc
229 .perform(post(UPLOAD_URL_FORCE)
230 .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
231 .content(TEMPLATE_REQUEST))
232 .andExpect(status().isCreated())
237 void testOverrideExistingTemplateWithoutForceShouldFail() throws Exception {
238 when(templateService.tryPersistOrOverwrite(any(Template.class), eq(true))).thenReturn(false);
240 MvcResult postResult = mockMvc
241 .perform(post(UPLOAD_URL_FORCE)
242 .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
243 .content(TEMPLATE_REQUEST))
244 .andExpect(status().isConflict())
247 assertThat(postResult.getResponse().getContentAsString()).isEqualTo(CANNOT_OVERRIDE_TEMPLATE_MSG);
250 private List<Template> createTemplatesList() {
251 return Arrays.asList(
252 new Template("1", SAMPLE_TEMPLATE_BSON, 0L),
253 new Template("2", SAMPLE_TEMPLATE_BSON, 0L),
254 new Template("3", SAMPLE_TEMPLATE_BSON, 0L));