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