2 * ============LICENSE_START=======================================================
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
23 package org.onap.vid.controllers;
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;
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;
84 @RunWith(MockitoJUnitRunner.class)
85 public class ChangeManagementControllerTest {
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";
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";
104 private final ObjectMapper objectMapper = new ObjectMapper();
105 private ChangeManagementController controller;
106 private MockMvc mockMvc;
108 private WorkflowService workflowService;
110 private ChangeManagementService changeManagementService;
112 private Response mockResponse;
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");
122 public void setUp() {
123 controller = new ChangeManagementController(workflowService, changeManagementService, objectMapper);
124 BasicConfigurator.configure();
125 mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
129 public void getWorkflow_shouldReturnListOfVnfs_whenServiceReturnsCorrectValue() throws Exception {
131 Collection<String> givenVnfs = ImmutableList.of("vnf1", "vnf2", "vnf3");
132 Collection<String> resultWorkflows = ImmutableList.of("workflow1", "workflow2");
135 workflowService.getWorkflowsForVNFs(argThat(other -> CollectionUtils.isEqualCollection(givenVnfs, other))))
136 .willReturn(resultWorkflows);
138 mockMvc.perform(get(WORKFLOW_URL)
139 .param(VNFS, StringUtils.join(givenVnfs, ",")))
140 .andExpect(status().isOk())
141 .andExpect(content().json(objectMapper.writeValueAsString(resultWorkflows)));
145 public void getMSOChangeManagements_shouldReturnCollectionOfRequests_whenServiceReturnsCorrectValue()
148 Collection<Request> requests = ImmutableList.of(
149 createRequest("network-instance-id-1", "status-message-1"),
150 createRequest("network-instance-id-2", "status-message-2"));
152 given(changeManagementService.getMSOChangeManagements()).willReturn(requests);
154 mockMvc.perform(get(MSO_URL))
155 .andExpect(status().isOk())
156 .andExpect(content().json(objectMapper.writeValueAsString(requests)));
160 public void changeManagement_shouldReturnOkResponse_whenServiceReturnsCorrectValue() throws Exception {
162 String vnfName = "vnfName1";
163 String jsonBody = "{'param1': 'paramparam'}";
165 given(changeManagementService.doChangeManagement(
166 argThat(request -> matches(request, CHANGE_MANAGEMENT_REQUEST_JSON)), eq(vnfName)))
167 .willReturn(ResponseEntity.ok().body(jsonBody));
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));
177 public void uploadConfigUpdateFile_shouldReturnOkResponse_whenServiceReturnsCorrectJson() throws Exception {
179 String jsonString = "{'param1': 'paramparam'}";
180 byte[] fileContent = "some file content".getBytes(StandardCharsets.UTF_8);
181 MockMultipartFile file = new MockMultipartFile(FILE_NAME, fileContent);
183 given(changeManagementService
184 .uploadConfigUpdateFile(argThat(multipartFileMatcher(file))))
185 .willReturn(jsonString);
187 mockMvc.perform(MockMvcRequestBuilders
188 .fileUpload(UPLOAD_CONFIG_UPDATE_FILE_URL)
190 .andExpect(status().isOk())
191 .andExpect(content().json(jsonString));
195 public void uploadConfigUpdateFile_shouldReturnResponseStatus_whenServiceThrowsWebApplicationException()
198 byte[] fileContent = "some file content".getBytes(StandardCharsets.UTF_8);
199 MockMultipartFile file = new MockMultipartFile(FILE_NAME, fileContent);
201 given(statusType.getStatusCode()).willReturn(HttpStatus.NOT_FOUND.value());
202 given(mockResponse.getStatus()).willReturn(HttpStatus.NOT_FOUND.value());
203 given(mockResponse.getStatusInfo()).willReturn(statusType);
205 WebApplicationException exception = new WebApplicationException(mockResponse);
207 willThrow(exception).given(changeManagementService)
208 .uploadConfigUpdateFile(argThat(multipartFileMatcher(file)));
210 mockMvc.perform(MockMvcRequestBuilders
211 .fileUpload(UPLOAD_CONFIG_UPDATE_FILE_URL)
213 .andExpect(status().isNotFound())
214 .andExpect(content().json(objectMapper.writeValueAsString(new ExceptionResponse(exception))));
218 public void uploadConfigUpdateFile_shouldReturnInternalServerError_whenServiceThrowsRuntimeException()
221 byte[] fileContent = "some file content".getBytes(StandardCharsets.UTF_8);
222 MockMultipartFile file = new MockMultipartFile(FILE_NAME, fileContent);
224 RuntimeException exception = new RuntimeException("runtime exception message");
226 willThrow(exception).given(changeManagementService)
227 .uploadConfigUpdateFile(argThat(multipartFileMatcher(file)));
229 mockMvc.perform(MockMvcRequestBuilders
230 .fileUpload(UPLOAD_CONFIG_UPDATE_FILE_URL)
232 .andExpect(status().isInternalServerError())
233 .andExpect(content().json(objectMapper.writeValueAsString(new ExceptionResponse(exception))));
237 public void getSchedulerChangeManagements_shouldReturnJsonArray_whenServiceReturnsCorrectValue() throws Exception {
239 JSONArray array = new JSONArray();
240 array.add("element1");
241 array.add("element2");
243 given(changeManagementService.getSchedulerChangeManagements()).willReturn(array);
245 mockMvc.perform(get(SCHEDULER_URL))
246 .andExpect(status().isOk())
247 .andExpect(content().json(array.toJSONString()));
251 public void deleteSchedule_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception {
253 String id = "schedule-id-1";
254 Pair<String, Integer> pair = new ImmutablePair<>("myString", HttpStatus.OK.value());
256 given(changeManagementService.deleteSchedule(id)).willReturn(pair);
258 mockMvc.perform(delete(SCHEDULER_BY_SCHEDULE_ID_URL, id))
259 .andExpect(status().isOk());
263 public void deleteSchedule_shouldReturnNotFoundResponse_whenServiceReturnsNotFoundStatus() throws Exception {
265 String id = "schedule-id-1";
266 Pair<String, Integer> pair = new ImmutablePair<>("myString", HttpStatus.NOT_FOUND.value());
268 given(changeManagementService.deleteSchedule(id)).willReturn(pair);
270 mockMvc.perform(delete(SCHEDULER_BY_SCHEDULE_ID_URL, id))
271 .andExpect(status().isNotFound());
275 public void getWorkflows_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception {
277 ImmutableList<String> elements = ImmutableList.of("workflow1", "workflow2");
278 GetWorkflowsResponse response = new GetWorkflowsResponse();
279 response.setWorkflows(elements);
281 given(changeManagementService
282 .getWorkflowsForVnf(argThat(request -> matches(request, GET_VNF_WORKFLOW_RELATION_REQUEST_JSON))))
283 .willReturn(elements);
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)));
293 public void getWorkflows_shouldReturnNotFound_whenServiceThrowsNotFoundException() throws Exception {
295 String errorMsg = "not found";
296 VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(errorMsg));
298 willThrow(new NotFoundException(errorMsg))
299 .given(changeManagementService)
300 .getWorkflowsForVnf(argThat(request -> matches(request, GET_VNF_WORKFLOW_RELATION_REQUEST_JSON)));
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)));
310 public void getWorkflows_shouldReturnInternalServerError_whenServiceThrowsRuntimeException() throws Exception {
312 VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_GET_MSG));
314 willThrow(new RuntimeException("runtime exception message"))
315 .given(changeManagementService).getWorkflowsForVnf(isA(GetVnfWorkflowRelationRequest.class));
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)));
325 public void createWorkflowRelation_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception {
327 VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse();
329 given(changeManagementService
330 .addVnfWorkflowRelation(argThat(request -> matches(request, VNF_WORKFLOW_RELATION_REQUEST_JSON))))
331 .willReturn(response);
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)));
341 public void createWorkflowRelation_shouldReturnInternalServerError_whenServiceThrowsException() throws Exception {
343 VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_ADD_MSG));
345 willThrow(new RuntimeException("runtime exception message"))
346 .given(changeManagementService).addVnfWorkflowRelation(argThat(request -> matches(request,
347 VNF_WORKFLOW_RELATION_REQUEST_JSON)));
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)));
357 public void getAllWorkflowRelation_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception {
359 VnfDetailsWithWorkflows workflows = new VnfDetailsWithWorkflows();
360 workflows.setWorkflows(ImmutableList.of("workflow1", "workflow2"));
361 VnfWorkflowRelationAllResponse response = new VnfWorkflowRelationAllResponse(ImmutableList.of(workflows));
363 given(changeManagementService.getAllVnfWorkflowRelations()).willReturn(response);
365 mockMvc.perform(get(VNF_WORKFLOW_RELATION_URL))
366 .andExpect(status().isOk())
367 .andExpect(content().json(objectMapper.writeValueAsString(response)));
371 public void getAllWorkflowRelation_shouldReturnInternalServerError_whenServiceThrowsRuntimeException()
374 VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_GET_ALL_MSG));
376 willThrow(new RuntimeException("runtime exception message"))
377 .given(changeManagementService).getAllVnfWorkflowRelations();
379 mockMvc.perform(get(VNF_WORKFLOW_RELATION_URL))
380 .andExpect(status().isInternalServerError())
381 .andExpect(content().json(objectMapper.writeValueAsString(response)));
385 public void deleteWorkflowRelation_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception {
386 VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of("abc"));
388 given(changeManagementService.deleteVnfWorkflowRelation(argThat(request -> matches(request,
389 VNF_WORKFLOW_RELATION_REQUEST_JSON))))
390 .willReturn(response);
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)));
400 public void deleteWorkflowRelation_shouldReturnInternalServerError_whenServiceThrowsRuntimeException()
402 VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_DELETE_MSG));
404 willThrow(new RuntimeException("runtime exception message"))
405 .given(changeManagementService).deleteVnfWorkflowRelation(argThat(request -> matches(request,
406 VNF_WORKFLOW_RELATION_REQUEST_JSON)));
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)));
415 private <T> boolean matches(T request, String expectedJson) {
417 return objectMapper.writeValueAsString(request).equals(expectedJson);
418 } catch (JsonProcessingException e) {
419 System.out.println("Exception occurred: " + e.getMessage());
424 private ArgumentMatcher<MultipartFile> multipartFileMatcher(MultipartFile otherFile) {
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());
437 private Request createRequest(String networkInstanceId, String statusMessage) {
438 Request req = new Request();
439 InstanceIds instanceIds = new InstanceIds();
440 instanceIds.setNetworkInstanceId(networkInstanceId);
442 RequestStatus requestStatus = new RequestStatus();
443 requestStatus.setStatusMessage(statusMessage);
445 req.setInstanceIds(instanceIds);
446 req.setRequestStatus(requestStatus);
451 private String getRequestContent(String filename) {
452 InputStream inputStream = classLoader.getResourceAsStream(filename);
453 return new Scanner(inputStream).useDelimiter("\\A").next().replaceAll("\\s+", "");