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.controller;
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;
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;
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;
76 @RunWith(MockitoJUnitRunner.class)
77 public class ChangeManagementControllerTest {
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";
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";
96 private final ObjectMapper objectMapper = new ObjectMapper();
97 private ChangeManagementController controller;
98 private MockMvc mockMvc;
100 private WorkflowService workflowService;
102 private ChangeManagementService changeManagementService;
104 private Response mockResponse;
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");
114 public void setUp() {
115 controller = new ChangeManagementController(workflowService, changeManagementService, objectMapper);
116 BasicConfigurator.configure();
117 mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
121 public void getWorkflow_shouldReturnListOfVnfs_whenServiceReturnsCorrectValue() throws Exception {
123 Collection<String> givenVnfs = ImmutableList.of("vnf1", "vnf2", "vnf3");
124 Collection<String> resultWorkflows = ImmutableList.of("workflow1", "workflow2");
127 workflowService.getWorkflowsForVNFs(argThat(other -> CollectionUtils.isEqualCollection(givenVnfs, other))))
128 .willReturn(resultWorkflows);
130 mockMvc.perform(get(WORKFLOW_URL)
131 .param(VNFS, StringUtils.join(givenVnfs, ",")))
132 .andExpect(status().isOk())
133 .andExpect(content().json(objectMapper.writeValueAsString(resultWorkflows)));
137 public void getMSOChangeManagements_shouldReturnCollectionOfRequests_whenServiceReturnsCorrectValue()
140 Collection<Request> requests = ImmutableList.of(
141 createRequest("network-instance-id-1", "status-message-1"),
142 createRequest("network-instance-id-2", "status-message-2"));
144 given(changeManagementService.getMSOChangeManagements()).willReturn(requests);
146 mockMvc.perform(get(MSO_URL))
147 .andExpect(status().isOk())
148 .andExpect(content().json(objectMapper.writeValueAsString(requests)));
152 public void changeManagement_shouldReturnOkResponse_whenServiceReturnsCorrectValue() throws Exception {
154 String vnfName = "vnfName1";
155 String jsonBody = "{'param1': 'paramparam'}";
157 given(changeManagementService.doChangeManagement(
158 argThat(request -> matches(request, CHANGE_MANAGEMENT_REQUEST_JSON)), eq(vnfName)))
159 .willReturn(ResponseEntity.ok().body(jsonBody));
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));
169 public void uploadConfigUpdateFile_shouldReturnOkResponse_whenServiceReturnsCorrectJson() throws Exception {
171 String jsonString = "{'param1': 'paramparam'}";
172 byte[] fileContent = "some file content".getBytes(StandardCharsets.UTF_8);
173 MockMultipartFile file = new MockMultipartFile(FILE_NAME, fileContent);
175 given(changeManagementService
176 .uploadConfigUpdateFile(argThat(multipartFileMatcher(file))))
177 .willReturn(jsonString);
179 mockMvc.perform(MockMvcRequestBuilders
180 .fileUpload(UPLOAD_CONFIG_UPDATE_FILE_URL)
182 .andExpect(status().isOk())
183 .andExpect(content().json(jsonString));
187 public void uploadConfigUpdateFile_shouldReturnResponseStatus_whenServiceThrowsWebApplicationException()
190 byte[] fileContent = "some file content".getBytes(StandardCharsets.UTF_8);
191 MockMultipartFile file = new MockMultipartFile(FILE_NAME, fileContent);
193 given(statusType.getStatusCode()).willReturn(HttpStatus.NOT_FOUND.value());
194 given(mockResponse.getStatus()).willReturn(HttpStatus.NOT_FOUND.value());
195 given(mockResponse.getStatusInfo()).willReturn(statusType);
197 WebApplicationException exception = new WebApplicationException(mockResponse);
199 willThrow(exception).given(changeManagementService)
200 .uploadConfigUpdateFile(argThat(multipartFileMatcher(file)));
202 mockMvc.perform(MockMvcRequestBuilders
203 .fileUpload(UPLOAD_CONFIG_UPDATE_FILE_URL)
205 .andExpect(status().isNotFound())
206 .andExpect(content().json(objectMapper.writeValueAsString(new ExceptionResponse(exception))));
210 public void uploadConfigUpdateFile_shouldReturnInternalServerError_whenServiceThrowsRuntimeException()
213 byte[] fileContent = "some file content".getBytes(StandardCharsets.UTF_8);
214 MockMultipartFile file = new MockMultipartFile(FILE_NAME, fileContent);
216 RuntimeException exception = new RuntimeException("runtime exception message");
218 willThrow(exception).given(changeManagementService)
219 .uploadConfigUpdateFile(argThat(multipartFileMatcher(file)));
221 mockMvc.perform(MockMvcRequestBuilders
222 .fileUpload(UPLOAD_CONFIG_UPDATE_FILE_URL)
224 .andExpect(status().isInternalServerError())
225 .andExpect(content().json(objectMapper.writeValueAsString(new ExceptionResponse(exception))));
229 public void getSchedulerChangeManagements_shouldReturnJsonArray_whenServiceReturnsCorrectValue() throws Exception {
231 ObjectMapper mapper = new ObjectMapper();
232 ArrayNode array = mapper.createArrayNode();
233 array.add("element1");
234 array.add("element2");
236 given(changeManagementService.getSchedulerChangeManagements()).willReturn(array);
238 mockMvc.perform(get(SCHEDULER_URL))
239 .andExpect(status().isOk())
240 .andExpect(content().json(mapper.writeValueAsString(array)));
244 public void deleteSchedule_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception {
246 String id = "schedule-id-1";
247 Pair<String, Integer> pair = new ImmutablePair<>("myString", HttpStatus.OK.value());
249 given(changeManagementService.deleteSchedule(id)).willReturn(pair);
251 mockMvc.perform(delete(SCHEDULER_BY_SCHEDULE_ID_URL, id))
252 .andExpect(status().isOk());
256 public void deleteSchedule_shouldReturnNotFoundResponse_whenServiceReturnsNotFoundStatus() throws Exception {
258 String id = "schedule-id-1";
259 Pair<String, Integer> pair = new ImmutablePair<>("myString", HttpStatus.NOT_FOUND.value());
261 given(changeManagementService.deleteSchedule(id)).willReturn(pair);
263 mockMvc.perform(delete(SCHEDULER_BY_SCHEDULE_ID_URL, id))
264 .andExpect(status().isNotFound());
268 public void getWorkflows_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception {
270 ImmutableList<String> elements = ImmutableList.of("workflow1", "workflow2");
271 GetWorkflowsResponse response = new GetWorkflowsResponse();
272 response.setWorkflows(elements);
274 given(changeManagementService
275 .getWorkflowsForVnf(argThat(request -> matches(request, GET_VNF_WORKFLOW_RELATION_REQUEST_JSON))))
276 .willReturn(elements);
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)));
286 public void getWorkflows_shouldReturnNotFound_whenServiceThrowsNotFoundException() throws Exception {
288 String errorMsg = "not found";
289 VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(errorMsg));
291 willThrow(new NotFoundException(errorMsg))
292 .given(changeManagementService)
293 .getWorkflowsForVnf(argThat(request -> matches(request, GET_VNF_WORKFLOW_RELATION_REQUEST_JSON)));
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)));
303 public void getWorkflows_shouldReturnInternalServerError_whenServiceThrowsRuntimeException() throws Exception {
305 VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_GET_MSG));
307 willThrow(new RuntimeException("runtime exception message"))
308 .given(changeManagementService).getWorkflowsForVnf(isA(GetVnfWorkflowRelationRequest.class));
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)));
318 public void createWorkflowRelation_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception {
320 VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse();
322 given(changeManagementService
323 .addVnfWorkflowRelation(argThat(request -> matches(request, VNF_WORKFLOW_RELATION_REQUEST_JSON))))
324 .willReturn(response);
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)));
334 public void createWorkflowRelation_shouldReturnInternalServerError_whenServiceThrowsException() throws Exception {
336 VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_ADD_MSG));
338 willThrow(new RuntimeException("runtime exception message"))
339 .given(changeManagementService).addVnfWorkflowRelation(argThat(request -> matches(request,
340 VNF_WORKFLOW_RELATION_REQUEST_JSON)));
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)));
350 public void getAllWorkflowRelation_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception {
352 VnfDetailsWithWorkflows workflows = new VnfDetailsWithWorkflows();
353 workflows.setWorkflows(ImmutableList.of("workflow1", "workflow2"));
354 VnfWorkflowRelationAllResponse response = new VnfWorkflowRelationAllResponse(ImmutableList.of(workflows));
356 given(changeManagementService.getAllVnfWorkflowRelations()).willReturn(response);
358 mockMvc.perform(get(VNF_WORKFLOW_RELATION_URL))
359 .andExpect(status().isOk())
360 .andExpect(content().json(objectMapper.writeValueAsString(response)));
364 public void getAllWorkflowRelation_shouldReturnInternalServerError_whenServiceThrowsRuntimeException()
367 VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_GET_ALL_MSG));
369 willThrow(new RuntimeException("runtime exception message"))
370 .given(changeManagementService).getAllVnfWorkflowRelations();
372 mockMvc.perform(get(VNF_WORKFLOW_RELATION_URL))
373 .andExpect(status().isInternalServerError())
374 .andExpect(content().json(objectMapper.writeValueAsString(response)));
378 public void deleteWorkflowRelation_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception {
379 VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of("abc"));
381 given(changeManagementService.deleteVnfWorkflowRelation(argThat(request -> matches(request,
382 VNF_WORKFLOW_RELATION_REQUEST_JSON))))
383 .willReturn(response);
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)));
393 public void deleteWorkflowRelation_shouldReturnInternalServerError_whenServiceThrowsRuntimeException()
395 VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_DELETE_MSG));
397 willThrow(new RuntimeException("runtime exception message"))
398 .given(changeManagementService).deleteVnfWorkflowRelation(argThat(request -> matches(request,
399 VNF_WORKFLOW_RELATION_REQUEST_JSON)));
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)));
408 private <T> boolean matches(T request, String expectedJson) {
410 return objectMapper.writeValueAsString(request).equals(expectedJson);
411 } catch (JsonProcessingException e) {
412 System.out.println("Exception occurred: " + e.getMessage());
417 private ArgumentMatcher<MultipartFile> multipartFileMatcher(MultipartFile otherFile) {
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());
430 private Request createRequest(String networkInstanceId, String statusMessage) {
431 Request req = new Request();
432 InstanceIds instanceIds = new InstanceIds();
433 instanceIds.setNetworkInstanceId(networkInstanceId);
435 RequestStatus requestStatus = new RequestStatus();
436 requestStatus.setStatusMessage(statusMessage);
438 req.setInstanceIds(instanceIds);
439 req.setRequestStatus(requestStatus);
444 private String getRequestContent(String filename) {
445 InputStream inputStream = classLoader.getResourceAsStream(filename);
446 return new Scanner(inputStream).useDelimiter("\\A").next().replaceAll("\\s+", "");