2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2018 - 2019 Nokia. All rights reserved.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.vid.controller;
24 import com.fasterxml.jackson.core.JsonProcessingException;
25 import com.fasterxml.jackson.databind.ObjectMapper;
26 import com.fasterxml.jackson.databind.node.ArrayNode;
27 import com.google.common.collect.ImmutableList;
28 import org.apache.commons.collections4.CollectionUtils;
29 import org.apache.commons.lang3.StringUtils;
30 import org.apache.commons.lang3.tuple.ImmutablePair;
31 import org.apache.commons.lang3.tuple.Pair;
32 import org.apache.log4j.BasicConfigurator;
33 import org.junit.Before;
34 import org.junit.Test;
35 import org.junit.runner.RunWith;
36 import org.mockito.ArgumentMatcher;
37 import org.mockito.Mock;
38 import org.mockito.runners.MockitoJUnitRunner;
39 import org.onap.vid.changeManagement.*;
40 import org.onap.vid.exceptions.NotFoundException;
41 import org.onap.vid.model.ExceptionResponse;
42 import org.onap.vid.mso.rest.InstanceIds;
43 import org.onap.vid.mso.rest.Request;
44 import org.onap.vid.mso.rest.RequestStatus;
45 import org.onap.vid.services.ChangeManagementService;
46 import org.onap.vid.services.WorkflowService;
47 import org.springframework.http.HttpStatus;
48 import org.springframework.http.ResponseEntity;
49 import org.springframework.mock.web.MockMultipartFile;
50 import org.springframework.test.web.servlet.MockMvc;
51 import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
52 import org.springframework.test.web.servlet.setup.MockMvcBuilders;
53 import org.springframework.web.multipart.MultipartFile;
55 import javax.ws.rs.WebApplicationException;
56 import javax.ws.rs.core.MediaType;
57 import javax.ws.rs.core.Response;
58 import java.io.IOException;
59 import java.io.InputStream;
60 import java.nio.charset.StandardCharsets;
61 import java.util.Arrays;
62 import java.util.Collection;
63 import java.util.Scanner;
65 import static org.mockito.ArgumentMatchers.eq;
66 import static org.mockito.BDDMockito.given;
67 import static org.mockito.BDDMockito.willThrow;
68 import static org.mockito.Matchers.argThat;
69 import static org.mockito.Matchers.isA;
70 import static org.onap.vid.controller.ChangeManagementController.*;
71 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
72 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
73 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
75 @RunWith(MockitoJUnitRunner.class)
76 public class ChangeManagementControllerTest {
78 private static final String FILE_NAME = "file";
79 private static final String GET_VNF_WORKFLOW_RELATION_URL =
80 "/" + CHANGE_MANAGEMENT + "/" + GET_VNF_WORKFLOW_RELATION;
81 private static final String WORKFLOW_URL = "/" + CHANGE_MANAGEMENT + "/workflow";
82 private static final String WORKFLOW_NAME_URL = WORKFLOW_URL + "/{name}";
83 private static final String MSO_URL = "/" + CHANGE_MANAGEMENT + "/mso";
84 private static final String UPLOAD_CONFIG_UPDATE_FILE_URL = "/" + CHANGE_MANAGEMENT + "/uploadConfigUpdateFile";
85 private static final String SCHEDULER_URL = "/" + CHANGE_MANAGEMENT + "/scheduler";
86 private static final String SCHEDULER_BY_SCHEDULE_ID_URL = "/" + CHANGE_MANAGEMENT + SCHEDULER_BY_SCHEDULE_ID;
87 private static final String VNF_WORKFLOW_RELATION_URL = "/" + CHANGE_MANAGEMENT + "/" + VNF_WORKFLOW_RELATION;
88 private static final String VNFS = "vnfs";
90 private static final String FAILED_TO_GET_MSG = "Failed to get workflows for vnf";
91 private static final String FAILED_TO_ADD_MSG = "Failed to add vnf to workflow relation";
92 private static final String FAILED_TO_GET_ALL_MSG = "Failed to get all vnf to workflow relations";
93 private static final String FAILED_TO_DELETE_MSG = "Failed to delete vnf from workflow relation";
95 private final ObjectMapper objectMapper = new ObjectMapper();
96 private ChangeManagementController controller;
97 private MockMvc mockMvc;
99 private WorkflowService workflowService;
101 private ChangeManagementService changeManagementService;
103 private Response mockResponse;
105 private Response.StatusType statusType;
106 private ClassLoader classLoader = getClass().getClassLoader();
107 private final String CHANGE_MANAGEMENT_REQUEST_JSON = getRequestContent("change-management-request.json");
108 private final String GET_VNF_WORKFLOW_RELATION_REQUEST_JSON = getRequestContent(
109 "get-vnf-workflow-relation-request.json");
110 private final String VNF_WORKFLOW_RELATION_REQUEST_JSON = getRequestContent("vnf-workflow-relation-request.json");
113 public void setUp() {
114 controller = new ChangeManagementController(workflowService, changeManagementService, objectMapper);
115 BasicConfigurator.configure();
116 mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
120 public void getWorkflow_shouldReturnListOfVnfs_whenServiceReturnsCorrectValue() throws Exception {
122 Collection<String> givenVnfs = ImmutableList.of("vnf1", "vnf2", "vnf3");
123 Collection<String> resultWorkflows = ImmutableList.of("workflow1", "workflow2");
126 workflowService.getWorkflowsForVNFs(argThat(other -> CollectionUtils.isEqualCollection(givenVnfs, other))))
127 .willReturn(resultWorkflows);
129 mockMvc.perform(get(WORKFLOW_URL)
130 .param(VNFS, StringUtils.join(givenVnfs, ",")))
131 .andExpect(status().isOk())
132 .andExpect(content().json(objectMapper.writeValueAsString(resultWorkflows)));
136 public void getMSOChangeManagements_shouldReturnCollectionOfRequests_whenServiceReturnsCorrectValue()
139 Collection<Request> requests = ImmutableList.of(
140 createRequest("network-instance-id-1", "status-message-1"),
141 createRequest("network-instance-id-2", "status-message-2"));
143 given(changeManagementService.getMSOChangeManagements()).willReturn(requests);
145 mockMvc.perform(get(MSO_URL))
146 .andExpect(status().isOk())
147 .andExpect(content().json(objectMapper.writeValueAsString(requests)));
151 public void changeManagement_shouldReturnOkResponse_whenServiceReturnsCorrectValue() throws Exception {
153 String vnfName = "vnfName1";
154 String jsonBody = "{'param1': 'paramparam'}";
156 given(changeManagementService.doChangeManagement(
157 argThat(request -> matches(request, CHANGE_MANAGEMENT_REQUEST_JSON)), eq(vnfName)))
158 .willReturn(ResponseEntity.ok().body(jsonBody));
160 mockMvc.perform(post(WORKFLOW_NAME_URL, vnfName)
161 .contentType(MediaType.APPLICATION_JSON)
162 .content(CHANGE_MANAGEMENT_REQUEST_JSON))
163 .andExpect(status().isOk())
164 .andExpect(content().json(jsonBody));
168 public void uploadConfigUpdateFile_shouldReturnOkResponse_whenServiceReturnsCorrectJson() throws Exception {
170 String jsonString = "{'param1': 'paramparam'}";
171 byte[] fileContent = "some file content".getBytes(StandardCharsets.UTF_8);
172 MockMultipartFile file = new MockMultipartFile(FILE_NAME, fileContent);
174 given(changeManagementService
175 .uploadConfigUpdateFile(argThat(multipartFileMatcher(file))))
176 .willReturn(jsonString);
178 mockMvc.perform(MockMvcRequestBuilders
179 .fileUpload(UPLOAD_CONFIG_UPDATE_FILE_URL)
181 .andExpect(status().isOk())
182 .andExpect(content().json(jsonString));
186 public void uploadConfigUpdateFile_shouldReturnResponseStatus_whenServiceThrowsWebApplicationException()
189 byte[] fileContent = "some file content".getBytes(StandardCharsets.UTF_8);
190 MockMultipartFile file = new MockMultipartFile(FILE_NAME, fileContent);
192 given(statusType.getStatusCode()).willReturn(HttpStatus.NOT_FOUND.value());
193 given(mockResponse.getStatus()).willReturn(HttpStatus.NOT_FOUND.value());
194 given(mockResponse.getStatusInfo()).willReturn(statusType);
196 WebApplicationException exception = new WebApplicationException(mockResponse);
198 willThrow(exception).given(changeManagementService)
199 .uploadConfigUpdateFile(argThat(multipartFileMatcher(file)));
201 mockMvc.perform(MockMvcRequestBuilders
202 .fileUpload(UPLOAD_CONFIG_UPDATE_FILE_URL)
204 .andExpect(status().isNotFound())
205 .andExpect(content().json(objectMapper.writeValueAsString(new ExceptionResponse(exception))));
209 public void uploadConfigUpdateFile_shouldReturnInternalServerError_whenServiceThrowsRuntimeException()
212 byte[] fileContent = "some file content".getBytes(StandardCharsets.UTF_8);
213 MockMultipartFile file = new MockMultipartFile(FILE_NAME, fileContent);
215 RuntimeException exception = new RuntimeException("runtime exception message");
217 willThrow(exception).given(changeManagementService)
218 .uploadConfigUpdateFile(argThat(multipartFileMatcher(file)));
220 mockMvc.perform(MockMvcRequestBuilders
221 .fileUpload(UPLOAD_CONFIG_UPDATE_FILE_URL)
223 .andExpect(status().isInternalServerError())
224 .andExpect(content().json(objectMapper.writeValueAsString(new ExceptionResponse(exception))));
228 public void getSchedulerChangeManagements_shouldReturnJsonArray_whenServiceReturnsCorrectValue() throws Exception {
230 ObjectMapper mapper = new ObjectMapper();
231 ArrayNode array = mapper.createArrayNode();
232 array.add("element1");
233 array.add("element2");
235 given(changeManagementService.getSchedulerChangeManagements()).willReturn(array);
237 mockMvc.perform(get(SCHEDULER_URL))
238 .andExpect(status().isOk())
239 .andExpect(content().json(mapper.writeValueAsString(array)));
243 public void deleteSchedule_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception {
245 String id = "schedule-id-1";
246 Pair<String, Integer> pair = new ImmutablePair<>("myString", HttpStatus.OK.value());
248 given(changeManagementService.deleteSchedule(id)).willReturn(pair);
250 mockMvc.perform(delete(SCHEDULER_BY_SCHEDULE_ID_URL, id))
251 .andExpect(status().isOk());
255 public void deleteSchedule_shouldReturnNotFoundResponse_whenServiceReturnsNotFoundStatus() throws Exception {
257 String id = "schedule-id-1";
258 Pair<String, Integer> pair = new ImmutablePair<>("myString", HttpStatus.NOT_FOUND.value());
260 given(changeManagementService.deleteSchedule(id)).willReturn(pair);
262 mockMvc.perform(delete(SCHEDULER_BY_SCHEDULE_ID_URL, id))
263 .andExpect(status().isNotFound());
267 public void getWorkflows_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception {
269 ImmutableList<String> elements = ImmutableList.of("workflow1", "workflow2");
270 GetWorkflowsResponse response = new GetWorkflowsResponse();
271 response.setWorkflows(elements);
273 given(changeManagementService
274 .getWorkflowsForVnf(argThat(request -> matches(request, GET_VNF_WORKFLOW_RELATION_REQUEST_JSON))))
275 .willReturn(elements);
277 mockMvc.perform(post(GET_VNF_WORKFLOW_RELATION_URL)
278 .contentType(MediaType.APPLICATION_JSON)
279 .content(GET_VNF_WORKFLOW_RELATION_REQUEST_JSON))
280 .andExpect(status().isOk())
281 .andExpect(content().json(objectMapper.writeValueAsString(response)));
285 public void getWorkflows_shouldReturnNotFound_whenServiceThrowsNotFoundException() throws Exception {
287 String errorMsg = "not found";
288 VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(errorMsg));
290 willThrow(new NotFoundException(errorMsg))
291 .given(changeManagementService)
292 .getWorkflowsForVnf(argThat(request -> matches(request, GET_VNF_WORKFLOW_RELATION_REQUEST_JSON)));
294 mockMvc.perform(post(GET_VNF_WORKFLOW_RELATION_URL)
295 .contentType(MediaType.APPLICATION_JSON)
296 .content(GET_VNF_WORKFLOW_RELATION_REQUEST_JSON))
297 .andExpect(status().isNotFound())
298 .andExpect(content().json(objectMapper.writeValueAsString(response)));
302 public void getWorkflows_shouldReturnInternalServerError_whenServiceThrowsRuntimeException() throws Exception {
304 VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_GET_MSG));
306 willThrow(new RuntimeException("runtime exception message"))
307 .given(changeManagementService).getWorkflowsForVnf(isA(GetVnfWorkflowRelationRequest.class));
309 mockMvc.perform(post(GET_VNF_WORKFLOW_RELATION_URL)
310 .contentType(MediaType.APPLICATION_JSON)
311 .content(VNF_WORKFLOW_RELATION_REQUEST_JSON))
312 .andExpect(status().isInternalServerError())
313 .andExpect(content().json(objectMapper.writeValueAsString(response)));
317 public void createWorkflowRelation_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception {
319 VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse();
321 given(changeManagementService
322 .addVnfWorkflowRelation(argThat(request -> matches(request, VNF_WORKFLOW_RELATION_REQUEST_JSON))))
323 .willReturn(response);
325 mockMvc.perform(post(VNF_WORKFLOW_RELATION_URL)
326 .contentType(MediaType.APPLICATION_JSON)
327 .content(VNF_WORKFLOW_RELATION_REQUEST_JSON))
328 .andExpect(status().isOk())
329 .andExpect(content().json(objectMapper.writeValueAsString(response)));
333 public void createWorkflowRelation_shouldReturnInternalServerError_whenServiceThrowsException() throws Exception {
335 VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_ADD_MSG));
337 willThrow(new RuntimeException("runtime exception message"))
338 .given(changeManagementService).addVnfWorkflowRelation(argThat(request -> matches(request,
339 VNF_WORKFLOW_RELATION_REQUEST_JSON)));
341 mockMvc.perform(post(VNF_WORKFLOW_RELATION_URL)
342 .contentType(MediaType.APPLICATION_JSON)
343 .content(VNF_WORKFLOW_RELATION_REQUEST_JSON))
344 .andExpect(status().isInternalServerError())
345 .andExpect(content().json(objectMapper.writeValueAsString(response)));
349 public void getAllWorkflowRelation_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception {
351 VnfDetailsWithWorkflows workflows = new VnfDetailsWithWorkflows();
352 workflows.setWorkflows(ImmutableList.of("workflow1", "workflow2"));
353 VnfWorkflowRelationAllResponse response = new VnfWorkflowRelationAllResponse(ImmutableList.of(workflows));
355 given(changeManagementService.getAllVnfWorkflowRelations()).willReturn(response);
357 mockMvc.perform(get(VNF_WORKFLOW_RELATION_URL))
358 .andExpect(status().isOk())
359 .andExpect(content().json(objectMapper.writeValueAsString(response)));
363 public void getAllWorkflowRelation_shouldReturnInternalServerError_whenServiceThrowsRuntimeException()
366 VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_GET_ALL_MSG));
368 willThrow(new RuntimeException("runtime exception message"))
369 .given(changeManagementService).getAllVnfWorkflowRelations();
371 mockMvc.perform(get(VNF_WORKFLOW_RELATION_URL))
372 .andExpect(status().isInternalServerError())
373 .andExpect(content().json(objectMapper.writeValueAsString(response)));
377 public void deleteWorkflowRelation_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception {
378 VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of("abc"));
380 given(changeManagementService.deleteVnfWorkflowRelation(argThat(request -> matches(request,
381 VNF_WORKFLOW_RELATION_REQUEST_JSON))))
382 .willReturn(response);
384 mockMvc.perform(delete(VNF_WORKFLOW_RELATION_URL)
385 .contentType(MediaType.APPLICATION_JSON)
386 .content(VNF_WORKFLOW_RELATION_REQUEST_JSON))
387 .andExpect(status().isOk())
388 .andExpect(content().json(objectMapper.writeValueAsString(response)));
392 public void deleteWorkflowRelation_shouldReturnInternalServerError_whenServiceThrowsRuntimeException()
394 VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_DELETE_MSG));
396 willThrow(new RuntimeException("runtime exception message"))
397 .given(changeManagementService).deleteVnfWorkflowRelation(argThat(request -> matches(request,
398 VNF_WORKFLOW_RELATION_REQUEST_JSON)));
400 mockMvc.perform(delete(VNF_WORKFLOW_RELATION_URL)
401 .contentType(MediaType.APPLICATION_JSON)
402 .content(VNF_WORKFLOW_RELATION_REQUEST_JSON))
403 .andExpect(status().isInternalServerError())
404 .andExpect(content().json(objectMapper.writeValueAsString(response)));
407 private <T> boolean matches(T request, String expectedJson) {
409 return objectMapper.writeValueAsString(request).equals(expectedJson);
410 } catch (JsonProcessingException e) {
411 System.out.println("Exception occurred: " + e.getMessage());
416 private ArgumentMatcher<MultipartFile> multipartFileMatcher(MultipartFile otherFile) {
419 return other.getName().equals(otherFile.getName())
420 && other.getSize() == otherFile.getSize()
421 && Arrays.equals(other.getBytes(), otherFile.getBytes());
422 } catch (IOException e) {
423 System.out.println("IOException occurred: " + e.getMessage());
429 private Request createRequest(String networkInstanceId, String statusMessage) {
430 Request req = new Request();
431 InstanceIds instanceIds = new InstanceIds();
432 instanceIds.setNetworkInstanceId(networkInstanceId);
434 RequestStatus requestStatus = new RequestStatus();
435 requestStatus.setStatusMessage(statusMessage);
437 req.setInstanceIds(instanceIds);
438 req.setRequestStatus(requestStatus);
443 private String getRequestContent(String filename) {
444 InputStream inputStream = classLoader.getResourceAsStream(filename);
445 return new Scanner(inputStream).useDelimiter("\\A").next().replaceAll("\\s+", "");