3c8250b26df9870b72e1fe84999871a04309ba3e
[vid.git] / vid-app-common / src / test / java / org / onap / vid / controllers / ChangeManagementControllerTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
4  * ================================================================================
5  * Copyright © 2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright 2018 Nokia
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.vid.controllers;
24
25 import static org.mockito.ArgumentMatchers.eq;
26 import static org.mockito.BDDMockito.given;
27 import static org.mockito.BDDMockito.willThrow;
28 import static org.mockito.Matchers.argThat;
29 import static org.mockito.Matchers.isA;
30 import static org.onap.vid.controllers.ChangeManagementController.CHANGE_MANAGEMENT;
31 import static org.onap.vid.controllers.ChangeManagementController.GET_VNF_WORKFLOW_RELATION;
32 import static org.onap.vid.controllers.ChangeManagementController.SCHEDULER_BY_SCHEDULE_ID;
33 import static org.onap.vid.controllers.ChangeManagementController.VNF_WORKFLOW_RELATION;
34 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
35 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
36 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
37 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
38 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
39
40 import com.fasterxml.jackson.core.JsonProcessingException;
41 import com.fasterxml.jackson.databind.ObjectMapper;
42 import com.google.common.collect.ImmutableList;
43 import java.io.IOException;
44 import java.io.InputStream;
45 import java.nio.charset.StandardCharsets;
46 import java.util.Arrays;
47 import java.util.Collection;
48 import java.util.Scanner;
49 import javax.ws.rs.WebApplicationException;
50 import javax.ws.rs.core.MediaType;
51 import javax.ws.rs.core.Response;
52 import org.apache.commons.collections4.CollectionUtils;
53 import org.apache.commons.lang3.StringUtils;
54 import org.apache.commons.lang3.tuple.ImmutablePair;
55 import org.apache.commons.lang3.tuple.Pair;
56 import org.apache.log4j.BasicConfigurator;
57 import org.json.simple.JSONArray;
58 import org.junit.Before;
59 import org.junit.Test;
60 import org.junit.runner.RunWith;
61 import org.mockito.ArgumentMatcher;
62 import org.mockito.Mock;
63 import org.mockito.runners.MockitoJUnitRunner;
64 import org.onap.vid.changeManagement.GetVnfWorkflowRelationRequest;
65 import org.onap.vid.changeManagement.GetWorkflowsResponse;
66 import org.onap.vid.changeManagement.VnfDetailsWithWorkflows;
67 import org.onap.vid.changeManagement.VnfWorkflowRelationAllResponse;
68 import org.onap.vid.changeManagement.VnfWorkflowRelationResponse;
69 import org.onap.vid.domain.mso.InstanceIds;
70 import org.onap.vid.domain.mso.RequestStatus;
71 import org.onap.vid.exceptions.NotFoundException;
72 import org.onap.vid.model.ExceptionResponse;
73 import org.onap.vid.mso.rest.Request;
74 import org.onap.vid.services.ChangeManagementService;
75 import org.onap.vid.services.WorkflowService;
76 import org.springframework.http.HttpStatus;
77 import org.springframework.http.ResponseEntity;
78 import org.springframework.mock.web.MockMultipartFile;
79 import org.springframework.test.web.servlet.MockMvc;
80 import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
81 import org.springframework.test.web.servlet.setup.MockMvcBuilders;
82 import org.springframework.web.multipart.MultipartFile;
83
84 @RunWith(MockitoJUnitRunner.class)
85 public class ChangeManagementControllerTest {
86
87     private static final String FILE_NAME = "file";
88     private static final String GET_VNF_WORKFLOW_RELATION_URL =
89         "/" + CHANGE_MANAGEMENT + "/" + GET_VNF_WORKFLOW_RELATION;
90     private static final String WORKFLOW_URL = "/" + CHANGE_MANAGEMENT + "/workflow";
91     private static final String WORKFLOW_NAME_URL = WORKFLOW_URL + "/{name}";
92     private static final String MSO_URL = "/" + CHANGE_MANAGEMENT + "/mso";
93     private static final String UPLOAD_CONFIG_UPDATE_FILE_URL = "/" + CHANGE_MANAGEMENT + "/uploadConfigUpdateFile";
94     private static final String SCHEDULER_URL = "/" + CHANGE_MANAGEMENT + "/scheduler";
95     private static final String SCHEDULER_BY_SCHEDULE_ID_URL = "/" + CHANGE_MANAGEMENT + SCHEDULER_BY_SCHEDULE_ID;
96     private static final String VNF_WORKFLOW_RELATION_URL = "/" + CHANGE_MANAGEMENT + "/" + VNF_WORKFLOW_RELATION;
97     private static final String VNFS = "vnfs";
98
99     private static final String FAILED_TO_GET_MSG = "Failed to get workflows for vnf";
100     private static final String FAILED_TO_ADD_MSG = "Failed to add vnf to workflow relation";
101     private static final String FAILED_TO_GET_ALL_MSG = "Failed to get all vnf to workflow relations";
102     private static final String FAILED_TO_DELETE_MSG = "Failed to delete vnf from workflow relation";
103
104     private final ObjectMapper objectMapper = new ObjectMapper();
105     private ChangeManagementController controller;
106     private MockMvc mockMvc;
107     @Mock
108     private WorkflowService workflowService;
109     @Mock
110     private ChangeManagementService changeManagementService;
111     @Mock
112     private Response mockResponse;
113     @Mock
114     private Response.StatusType statusType;
115     private ClassLoader classLoader = getClass().getClassLoader();
116     private final String CHANGE_MANAGEMENT_REQUEST_JSON = getRequestContent("change-management-request.json");
117     private final String GET_VNF_WORKFLOW_RELATION_REQUEST_JSON = getRequestContent(
118         "get-vnf-workflow-relation-request.json");
119     private final String VNF_WORKFLOW_RELATION_REQUEST_JSON = getRequestContent("vnf-workflow-relation-request.json");
120
121     @Before
122     public void setUp() {
123         controller = new ChangeManagementController(workflowService, changeManagementService, objectMapper);
124         BasicConfigurator.configure();
125         mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
126     }
127
128     @Test
129     public void getWorkflow_shouldReturnListOfVnfs_whenServiceReturnsCorrectValue() throws Exception {
130
131         Collection<String> givenVnfs = ImmutableList.of("vnf1", "vnf2", "vnf3");
132         Collection<String> resultWorkflows = ImmutableList.of("workflow1", "workflow2");
133
134         given(
135             workflowService.getWorkflowsForVNFs(argThat(other -> CollectionUtils.isEqualCollection(givenVnfs, other))))
136             .willReturn(resultWorkflows);
137
138         mockMvc.perform(get(WORKFLOW_URL)
139             .param(VNFS, StringUtils.join(givenVnfs, ",")))
140             .andExpect(status().isOk())
141             .andExpect(content().json(objectMapper.writeValueAsString(resultWorkflows)));
142     }
143
144     @Test
145     public void getMSOChangeManagements_shouldReturnCollectionOfRequests_whenServiceReturnsCorrectValue()
146         throws Exception {
147
148         Collection<Request> requests = ImmutableList.of(
149             createRequest("network-instance-id-1", "status-message-1"),
150             createRequest("network-instance-id-2", "status-message-2"));
151
152         given(changeManagementService.getMSOChangeManagements()).willReturn(requests);
153
154         mockMvc.perform(get(MSO_URL))
155             .andExpect(status().isOk())
156             .andExpect(content().json(objectMapper.writeValueAsString(requests)));
157     }
158
159     @Test
160     public void changeManagement_shouldReturnOkResponse_whenServiceReturnsCorrectValue() throws Exception {
161
162         String vnfName = "vnfName1";
163         String jsonBody = "{'param1': 'paramparam'}";
164
165         given(changeManagementService.doChangeManagement(
166             argThat(request -> matches(request, CHANGE_MANAGEMENT_REQUEST_JSON)), eq(vnfName)))
167             .willReturn(ResponseEntity.ok().body(jsonBody));
168
169         mockMvc.perform(post(WORKFLOW_NAME_URL, vnfName)
170             .contentType(MediaType.APPLICATION_JSON)
171             .content(CHANGE_MANAGEMENT_REQUEST_JSON))
172             .andExpect(status().isOk())
173             .andExpect(content().json(jsonBody));
174     }
175
176     @Test
177     public void uploadConfigUpdateFile_shouldReturnOkResponse_whenServiceReturnsCorrectJson() throws Exception {
178
179         String jsonString = "{'param1': 'paramparam'}";
180         byte[] fileContent = "some file content".getBytes(StandardCharsets.UTF_8);
181         MockMultipartFile file = new MockMultipartFile(FILE_NAME, fileContent);
182
183         given(changeManagementService
184             .uploadConfigUpdateFile(argThat(multipartFileMatcher(file))))
185             .willReturn(jsonString);
186
187         mockMvc.perform(MockMvcRequestBuilders
188             .fileUpload(UPLOAD_CONFIG_UPDATE_FILE_URL)
189             .file(file))
190             .andExpect(status().isOk())
191             .andExpect(content().json(jsonString));
192     }
193
194     @Test
195     public void uploadConfigUpdateFile_shouldReturnResponseStatus_whenServiceThrowsWebApplicationException()
196         throws Exception {
197
198         byte[] fileContent = "some file content".getBytes(StandardCharsets.UTF_8);
199         MockMultipartFile file = new MockMultipartFile(FILE_NAME, fileContent);
200
201         given(statusType.getStatusCode()).willReturn(HttpStatus.NOT_FOUND.value());
202         given(mockResponse.getStatus()).willReturn(HttpStatus.NOT_FOUND.value());
203         given(mockResponse.getStatusInfo()).willReturn(statusType);
204
205         WebApplicationException exception = new WebApplicationException(mockResponse);
206
207         willThrow(exception).given(changeManagementService)
208             .uploadConfigUpdateFile(argThat(multipartFileMatcher(file)));
209
210         mockMvc.perform(MockMvcRequestBuilders
211             .fileUpload(UPLOAD_CONFIG_UPDATE_FILE_URL)
212             .file(file))
213             .andExpect(status().isNotFound())
214             .andExpect(content().json(objectMapper.writeValueAsString(new ExceptionResponse(exception))));
215     }
216
217     @Test
218     public void uploadConfigUpdateFile_shouldReturnInternalServerError_whenServiceThrowsRuntimeException()
219         throws Exception {
220
221         byte[] fileContent = "some file content".getBytes(StandardCharsets.UTF_8);
222         MockMultipartFile file = new MockMultipartFile(FILE_NAME, fileContent);
223
224         RuntimeException exception = new RuntimeException("runtime exception message");
225
226         willThrow(exception).given(changeManagementService)
227             .uploadConfigUpdateFile(argThat(multipartFileMatcher(file)));
228
229         mockMvc.perform(MockMvcRequestBuilders
230             .fileUpload(UPLOAD_CONFIG_UPDATE_FILE_URL)
231             .file(file))
232             .andExpect(status().isInternalServerError())
233             .andExpect(content().json(objectMapper.writeValueAsString(new ExceptionResponse(exception))));
234     }
235
236     @Test
237     public void getSchedulerChangeManagements_shouldReturnJsonArray_whenServiceReturnsCorrectValue() throws Exception {
238
239         JSONArray array = new JSONArray();
240         array.add("element1");
241         array.add("element2");
242
243         given(changeManagementService.getSchedulerChangeManagements()).willReturn(array);
244
245         mockMvc.perform(get(SCHEDULER_URL))
246             .andExpect(status().isOk())
247             .andExpect(content().json(array.toJSONString()));
248     }
249
250     @Test
251     public void deleteSchedule_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception {
252
253         String id = "schedule-id-1";
254         Pair<String, Integer> pair = new ImmutablePair<>("myString", HttpStatus.OK.value());
255
256         given(changeManagementService.deleteSchedule(id)).willReturn(pair);
257
258         mockMvc.perform(delete(SCHEDULER_BY_SCHEDULE_ID_URL, id))
259             .andExpect(status().isOk());
260     }
261
262     @Test
263     public void deleteSchedule_shouldReturnNotFoundResponse_whenServiceReturnsNotFoundStatus() throws Exception {
264
265         String id = "schedule-id-1";
266         Pair<String, Integer> pair = new ImmutablePair<>("myString", HttpStatus.NOT_FOUND.value());
267
268         given(changeManagementService.deleteSchedule(id)).willReturn(pair);
269
270         mockMvc.perform(delete(SCHEDULER_BY_SCHEDULE_ID_URL, id))
271             .andExpect(status().isNotFound());
272     }
273
274     @Test
275     public void getWorkflows_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception {
276
277         ImmutableList<String> elements = ImmutableList.of("workflow1", "workflow2");
278         GetWorkflowsResponse response = new GetWorkflowsResponse();
279         response.setWorkflows(elements);
280
281         given(changeManagementService
282             .getWorkflowsForVnf(argThat(request -> matches(request, GET_VNF_WORKFLOW_RELATION_REQUEST_JSON))))
283             .willReturn(elements);
284
285         mockMvc.perform(post(GET_VNF_WORKFLOW_RELATION_URL)
286             .contentType(MediaType.APPLICATION_JSON)
287             .content(GET_VNF_WORKFLOW_RELATION_REQUEST_JSON))
288             .andExpect(status().isOk())
289             .andExpect(content().json(objectMapper.writeValueAsString(response)));
290     }
291
292     @Test
293     public void getWorkflows_shouldReturnNotFound_whenServiceThrowsNotFoundException() throws Exception {
294
295         String errorMsg = "not found";
296         VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(errorMsg));
297
298         willThrow(new NotFoundException(errorMsg))
299             .given(changeManagementService)
300             .getWorkflowsForVnf(argThat(request -> matches(request, GET_VNF_WORKFLOW_RELATION_REQUEST_JSON)));
301
302         mockMvc.perform(post(GET_VNF_WORKFLOW_RELATION_URL)
303             .contentType(MediaType.APPLICATION_JSON)
304             .content(GET_VNF_WORKFLOW_RELATION_REQUEST_JSON))
305             .andExpect(status().isNotFound())
306             .andExpect(content().json(objectMapper.writeValueAsString(response)));
307     }
308
309     @Test
310     public void getWorkflows_shouldReturnInternalServerError_whenServiceThrowsRuntimeException() throws Exception {
311
312         VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_GET_MSG));
313
314         willThrow(new RuntimeException("runtime exception message"))
315             .given(changeManagementService).getWorkflowsForVnf(isA(GetVnfWorkflowRelationRequest.class));
316
317         mockMvc.perform(post(GET_VNF_WORKFLOW_RELATION_URL)
318             .contentType(MediaType.APPLICATION_JSON)
319             .content(VNF_WORKFLOW_RELATION_REQUEST_JSON))
320             .andExpect(status().isInternalServerError())
321             .andExpect(content().json(objectMapper.writeValueAsString(response)));
322     }
323
324     @Test
325     public void createWorkflowRelation_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception {
326
327         VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse();
328
329         given(changeManagementService
330             .addVnfWorkflowRelation(argThat(request -> matches(request, VNF_WORKFLOW_RELATION_REQUEST_JSON))))
331             .willReturn(response);
332
333         mockMvc.perform(post(VNF_WORKFLOW_RELATION_URL)
334             .contentType(MediaType.APPLICATION_JSON)
335             .content(VNF_WORKFLOW_RELATION_REQUEST_JSON))
336             .andExpect(status().isOk())
337             .andExpect(content().json(objectMapper.writeValueAsString(response)));
338     }
339
340     @Test
341     public void createWorkflowRelation_shouldReturnInternalServerError_whenServiceThrowsException() throws Exception {
342
343         VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_ADD_MSG));
344
345         willThrow(new RuntimeException("runtime exception message"))
346             .given(changeManagementService).addVnfWorkflowRelation(argThat(request -> matches(request,
347             VNF_WORKFLOW_RELATION_REQUEST_JSON)));
348
349         mockMvc.perform(post(VNF_WORKFLOW_RELATION_URL)
350             .contentType(MediaType.APPLICATION_JSON)
351             .content(VNF_WORKFLOW_RELATION_REQUEST_JSON))
352             .andExpect(status().isInternalServerError())
353             .andExpect(content().json(objectMapper.writeValueAsString(response)));
354     }
355
356     @Test
357     public void getAllWorkflowRelation_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception {
358
359         VnfDetailsWithWorkflows workflows = new VnfDetailsWithWorkflows();
360         workflows.setWorkflows(ImmutableList.of("workflow1", "workflow2"));
361         VnfWorkflowRelationAllResponse response = new VnfWorkflowRelationAllResponse(ImmutableList.of(workflows));
362
363         given(changeManagementService.getAllVnfWorkflowRelations()).willReturn(response);
364
365         mockMvc.perform(get(VNF_WORKFLOW_RELATION_URL))
366             .andExpect(status().isOk())
367             .andExpect(content().json(objectMapper.writeValueAsString(response)));
368     }
369
370     @Test
371     public void getAllWorkflowRelation_shouldReturnInternalServerError_whenServiceThrowsRuntimeException()
372         throws Exception {
373
374         VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_GET_ALL_MSG));
375
376         willThrow(new RuntimeException("runtime exception message"))
377             .given(changeManagementService).getAllVnfWorkflowRelations();
378
379         mockMvc.perform(get(VNF_WORKFLOW_RELATION_URL))
380             .andExpect(status().isInternalServerError())
381             .andExpect(content().json(objectMapper.writeValueAsString(response)));
382     }
383
384     @Test
385     public void deleteWorkflowRelation_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception {
386         VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of("abc"));
387
388         given(changeManagementService.deleteVnfWorkflowRelation(argThat(request -> matches(request,
389             VNF_WORKFLOW_RELATION_REQUEST_JSON))))
390             .willReturn(response);
391
392         mockMvc.perform(delete(VNF_WORKFLOW_RELATION_URL)
393             .contentType(MediaType.APPLICATION_JSON)
394             .content(VNF_WORKFLOW_RELATION_REQUEST_JSON))
395             .andExpect(status().isOk())
396             .andExpect(content().json(objectMapper.writeValueAsString(response)));
397     }
398
399     @Test
400     public void deleteWorkflowRelation_shouldReturnInternalServerError_whenServiceThrowsRuntimeException()
401         throws Exception {
402         VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_DELETE_MSG));
403
404         willThrow(new RuntimeException("runtime exception message"))
405             .given(changeManagementService).deleteVnfWorkflowRelation(argThat(request -> matches(request,
406             VNF_WORKFLOW_RELATION_REQUEST_JSON)));
407
408         mockMvc.perform(delete(VNF_WORKFLOW_RELATION_URL)
409             .contentType(MediaType.APPLICATION_JSON)
410             .content(VNF_WORKFLOW_RELATION_REQUEST_JSON))
411             .andExpect(status().isInternalServerError())
412             .andExpect(content().json(objectMapper.writeValueAsString(response)));
413     }
414
415     private <T> boolean matches(T request, String expectedJson) {
416         try {
417             return objectMapper.writeValueAsString(request).equals(expectedJson);
418         } catch (JsonProcessingException e) {
419             System.out.println("Exception occurred: " + e.getMessage());
420         }
421         return false;
422     }
423
424     private ArgumentMatcher<MultipartFile> multipartFileMatcher(MultipartFile otherFile) {
425         return other -> {
426             try {
427                 return other.getName().equals(otherFile.getName())
428                     && other.getSize() == otherFile.getSize()
429                     && Arrays.equals(other.getBytes(), otherFile.getBytes());
430             } catch (IOException e) {
431                 System.out.println("IOException occurred: " + e.getMessage());
432             }
433             return false;
434         };
435     }
436
437     private Request createRequest(String networkInstanceId, String statusMessage) {
438         Request req = new Request();
439         InstanceIds instanceIds = new InstanceIds();
440         instanceIds.setNetworkInstanceId(networkInstanceId);
441
442         RequestStatus requestStatus = new RequestStatus();
443         requestStatus.setStatusMessage(statusMessage);
444
445         req.setInstanceIds(instanceIds);
446         req.setRequestStatus(requestStatus);
447
448         return req;
449     }
450
451     private String getRequestContent(String filename) {
452         InputStream inputStream = classLoader.getResourceAsStream(filename);
453         return new Scanner(inputStream).useDelimiter("\\A").next().replaceAll("\\s+", "");
454     }
455 }