f34d73cd933d934d95e97161dba1fce62ebd32c3
[integration.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * Simulator
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.onap.pnfsimulator.rest;
22
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;
35
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;
48
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;
65
66 class TemplateControllerTest {
67
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"
77         + "   }"
78         + "}}";
79
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"
86         + "  },\n"
87         + "  \"notificationFields\": {\n"
88         + "   \"arrayOfNamedHashMap\": [{\n"
89         + "    \"name\": \"A20161221.1031-1041.bin.gz\",\n"
90         + "\n"
91         + "    \"hashMap\": {\n"
92         + "     \"fileformatType\": \"org.3GPP.32.435#measCollec\"\n"
93         + "    }\n"
94         + "   }]\n"
95         + "  }\n"
96         + " }\n"
97         + "}";
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;
103
104     @Mock
105     private Storage<Template> templateService;
106     @InjectMocks
107     private TemplateController controller;
108
109     @BeforeEach
110     void setup() {
111         MockitoAnnotations.initMocks(this);
112         mockMvc = MockMvcBuilders
113             .standaloneSetup(controller)
114             .build();
115     }
116
117     @Test
118     void shouldGetAllTemplates() throws Exception {
119         List<Template> templateList = createTemplatesList();
120         when(templateService.getAll()).thenReturn(templateList);
121
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))
127             .andReturn();
128
129         Type listType = new TypeToken<ArrayList<Template>>() {}.getType();
130         List<Template> resultList = GSON_OBJ.fromJson(getResult.getResponse().getContentAsString(), listType);
131         assertThat(resultList).containsExactlyInAnyOrderElementsOf(templateList);
132     }
133
134     @Test
135     void shouldListEmptyCollectionWhenNoTemplatesAvailable() throws Exception {
136         List<Template> templateList = Collections.emptyList();
137         when(templateService.getAll()).thenReturn(templateList);
138
139         MvcResult getResult = mockMvc
140             .perform(get(LIST_URL))
141             .andExpect(status().isOk())
142             .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
143             .andReturn();
144
145         String templatesAsString = GSON_OBJ.toJson(templateList);
146         assertThat(getResult.getResponse().getContentAsString()).containsSequence(templatesAsString);
147     }
148
149     @Test
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);
154
155         when(templateService.get(sampleTemplateName)).thenReturn(Optional.of(sampleTemplate));
156
157         MvcResult getResult = mockMvc
158             .perform(get(requestUrl))
159             .andExpect(status().isOk())
160             .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
161             .andReturn();
162
163         Template result = new Gson().fromJson(getResult.getResponse().getContentAsString(), Template.class);
164         assertThat(result).isEqualTo(sampleTemplate);
165     }
166
167     @Test
168     void shouldReturnNotFoundWhenGetNonExisitngTemplateByName() throws Exception {
169         String sampleTemplateName = "doesNotExist";
170         String requestUrl = String.format(GET_FORMAT_STR, sampleTemplateName);
171
172         when(templateService.get(sampleTemplateName)).thenReturn(Optional.empty());
173
174         MvcResult getResult = mockMvc
175             .perform(get(requestUrl))
176             .andExpect(status().isNotFound())
177             .andExpect(content().contentType(MediaType.TEXT_PLAIN_VALUE))
178             .andReturn();
179
180         assertThat(getResult.getResponse().getContentLength()).isEqualTo(TEMPLATE_NOT_FOUND_MSG.length());
181     }
182
183
184     @Test
185     void shouldReturnNamesOfTemplatesThatSatisfyGivenCriteria() throws Exception {
186         when(templateService.getIdsByContentCriteria(any(JsonObject.class))).thenReturn(SAMPLE_TEMPLATE_NAME_LIST);
187         SearchExp expr = new SearchExp(new JsonObject());
188
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();
194
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);
198     }
199
200     @Test
201     void shouldRaiseBadRequestWhenNullValueProvidedInSearchJsonAsJsonValue() throws Exception {
202         when(templateService.getIdsByContentCriteria(any(JsonObject.class))).thenThrow(IllegalJsonValueException.class);
203         SearchExp expr = new SearchExp(new JsonObject());
204
205         mockMvc.perform(post(SEARCH_ENDPOINT)
206                 .content(GSON_OBJ.toJson(expr))
207                 .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
208                 .andExpect(status().isBadRequest());
209     }
210
211
212     @Test
213     void testTryUploadNewTemplate() throws Exception {
214         when(templateService.tryPersistOrOverwrite(any(Template.class), eq(false))).thenReturn(true);
215
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())
221             .andReturn();
222     }
223
224     @Test
225     void testTryUploadNewTemplateWithForce() throws Exception {
226         when(templateService.tryPersistOrOverwrite(any(Template.class), eq(true))).thenReturn(true);
227
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())
233             .andReturn();
234     }
235
236     @Test
237     void testOverrideExistingTemplateWithoutForceShouldFail() throws Exception {
238         when(templateService.tryPersistOrOverwrite(any(Template.class), eq(true))).thenReturn(false);
239
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())
245             .andReturn();
246
247         assertThat(postResult.getResponse().getContentAsString()).isEqualTo(CANNOT_OVERRIDE_TEMPLATE_MSG);
248     }
249
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));
255     }
256 }