Fix for Penetration test _ Session and cookie management
[vid.git] / vid-app-common / src / test / java / org / onap / vid / controller / ChangeManagementControllerTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
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
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
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=========================================================
20  */
21
22 package org.onap.vid.controller;
23
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;
54
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;
64
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;
74
75 @RunWith(MockitoJUnitRunner.class)
76 public class ChangeManagementControllerTest {
77
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";
89
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";
94
95     private final ObjectMapper objectMapper = new ObjectMapper();
96     private ChangeManagementController controller;
97     private MockMvc mockMvc;
98     @Mock
99     private WorkflowService workflowService;
100     @Mock
101     private ChangeManagementService changeManagementService;
102     @Mock
103     private Response mockResponse;
104     @Mock
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");
111
112     @Before
113     public void setUp() {
114         controller = new ChangeManagementController(workflowService, changeManagementService, objectMapper);
115         BasicConfigurator.configure();
116         mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
117     }
118
119     @Test
120     public void getWorkflow_shouldReturnListOfVnfs_whenServiceReturnsCorrectValue() throws Exception {
121
122         Collection<String> givenVnfs = ImmutableList.of("vnf1", "vnf2", "vnf3");
123         Collection<String> resultWorkflows = ImmutableList.of("workflow1", "workflow2");
124
125         given(
126             workflowService.getWorkflowsForVNFs(argThat(other -> CollectionUtils.isEqualCollection(givenVnfs, other))))
127             .willReturn(resultWorkflows);
128
129         mockMvc.perform(get(WORKFLOW_URL)
130             .param(VNFS, StringUtils.join(givenVnfs, ",")))
131             .andExpect(status().isOk())
132             .andExpect(content().json(objectMapper.writeValueAsString(resultWorkflows)));
133     }
134
135     @Test
136     public void getMSOChangeManagements_shouldReturnCollectionOfRequests_whenServiceReturnsCorrectValue()
137         throws Exception {
138
139         Collection<Request> requests = ImmutableList.of(
140             createRequest("network-instance-id-1", "status-message-1"),
141             createRequest("network-instance-id-2", "status-message-2"));
142
143         given(changeManagementService.getMSOChangeManagements()).willReturn(requests);
144
145         mockMvc.perform(get(MSO_URL))
146             .andExpect(status().isOk())
147             .andExpect(content().json(objectMapper.writeValueAsString(requests)));
148     }
149
150     @Test
151     public void changeManagement_shouldReturnOkResponse_whenServiceReturnsCorrectValue() throws Exception {
152
153         String vnfName = "vnfName1";
154         String jsonBody = "{'param1': 'paramparam'}";
155
156         given(changeManagementService.doChangeManagement(
157             argThat(request -> matches(request, CHANGE_MANAGEMENT_REQUEST_JSON)), eq(vnfName)))
158             .willReturn(ResponseEntity.ok().body(jsonBody));
159
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));
165     }
166
167     @Test
168     public void uploadConfigUpdateFile_shouldReturnOkResponse_whenServiceReturnsCorrectJson() throws Exception {
169
170         String jsonString = "{'param1': 'paramparam'}";
171         byte[] fileContent = "some file content".getBytes(StandardCharsets.UTF_8);
172         MockMultipartFile file = new MockMultipartFile(FILE_NAME, fileContent);
173
174         given(changeManagementService
175             .uploadConfigUpdateFile(argThat(multipartFileMatcher(file))))
176             .willReturn(jsonString);
177
178         mockMvc.perform(MockMvcRequestBuilders
179             .fileUpload(UPLOAD_CONFIG_UPDATE_FILE_URL)
180             .file(file))
181             .andExpect(status().isOk())
182             .andExpect(content().json(jsonString));
183     }
184
185     @Test
186     public void uploadConfigUpdateFile_shouldReturnResponseStatus_whenServiceThrowsWebApplicationException()
187         throws Exception {
188
189         byte[] fileContent = "some file content".getBytes(StandardCharsets.UTF_8);
190         MockMultipartFile file = new MockMultipartFile(FILE_NAME, fileContent);
191
192         given(statusType.getStatusCode()).willReturn(HttpStatus.NOT_FOUND.value());
193         given(mockResponse.getStatus()).willReturn(HttpStatus.NOT_FOUND.value());
194         given(mockResponse.getStatusInfo()).willReturn(statusType);
195
196         WebApplicationException exception = new WebApplicationException(mockResponse);
197
198         willThrow(exception).given(changeManagementService)
199             .uploadConfigUpdateFile(argThat(multipartFileMatcher(file)));
200
201         mockMvc.perform(MockMvcRequestBuilders
202             .fileUpload(UPLOAD_CONFIG_UPDATE_FILE_URL)
203             .file(file))
204             .andExpect(status().isNotFound())
205             .andExpect(content().json(objectMapper.writeValueAsString(new ExceptionResponse(exception))));
206     }
207
208     @Test
209     public void uploadConfigUpdateFile_shouldReturnInternalServerError_whenServiceThrowsRuntimeException()
210         throws Exception {
211
212         byte[] fileContent = "some file content".getBytes(StandardCharsets.UTF_8);
213         MockMultipartFile file = new MockMultipartFile(FILE_NAME, fileContent);
214
215         RuntimeException exception = new RuntimeException("runtime exception message");
216
217         willThrow(exception).given(changeManagementService)
218             .uploadConfigUpdateFile(argThat(multipartFileMatcher(file)));
219
220         mockMvc.perform(MockMvcRequestBuilders
221             .fileUpload(UPLOAD_CONFIG_UPDATE_FILE_URL)
222             .file(file))
223             .andExpect(status().isInternalServerError())
224             .andExpect(content().json(objectMapper.writeValueAsString(new ExceptionResponse(exception))));
225     }
226
227     @Test
228     public void getSchedulerChangeManagements_shouldReturnJsonArray_whenServiceReturnsCorrectValue() throws Exception {
229
230         ObjectMapper mapper = new ObjectMapper();
231         ArrayNode array = mapper.createArrayNode();
232         array.add("element1");
233         array.add("element2");
234
235         given(changeManagementService.getSchedulerChangeManagements()).willReturn(array);
236
237         mockMvc.perform(get(SCHEDULER_URL))
238             .andExpect(status().isOk())
239             .andExpect(content().json(mapper.writeValueAsString(array)));
240     }
241
242     @Test
243     public void deleteSchedule_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception {
244
245         String id = "schedule-id-1";
246         Pair<String, Integer> pair = new ImmutablePair<>("myString", HttpStatus.OK.value());
247
248         given(changeManagementService.deleteSchedule(id)).willReturn(pair);
249
250         mockMvc.perform(delete(SCHEDULER_BY_SCHEDULE_ID_URL, id))
251             .andExpect(status().isOk());
252     }
253
254     @Test
255     public void deleteSchedule_shouldReturnNotFoundResponse_whenServiceReturnsNotFoundStatus() throws Exception {
256
257         String id = "schedule-id-1";
258         Pair<String, Integer> pair = new ImmutablePair<>("myString", HttpStatus.NOT_FOUND.value());
259
260         given(changeManagementService.deleteSchedule(id)).willReturn(pair);
261
262         mockMvc.perform(delete(SCHEDULER_BY_SCHEDULE_ID_URL, id))
263             .andExpect(status().isNotFound());
264     }
265
266     @Test
267     public void getWorkflows_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception {
268
269         ImmutableList<String> elements = ImmutableList.of("workflow1", "workflow2");
270         GetWorkflowsResponse response = new GetWorkflowsResponse();
271         response.setWorkflows(elements);
272
273         given(changeManagementService
274             .getWorkflowsForVnf(argThat(request -> matches(request, GET_VNF_WORKFLOW_RELATION_REQUEST_JSON))))
275             .willReturn(elements);
276
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)));
282     }
283
284     @Test
285     public void getWorkflows_shouldReturnNotFound_whenServiceThrowsNotFoundException() throws Exception {
286
287         String errorMsg = "not found";
288         VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(errorMsg));
289
290         willThrow(new NotFoundException(errorMsg))
291             .given(changeManagementService)
292             .getWorkflowsForVnf(argThat(request -> matches(request, GET_VNF_WORKFLOW_RELATION_REQUEST_JSON)));
293
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)));
299     }
300
301     @Test
302     public void getWorkflows_shouldReturnInternalServerError_whenServiceThrowsRuntimeException() throws Exception {
303
304         VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_GET_MSG));
305
306         willThrow(new RuntimeException("runtime exception message"))
307             .given(changeManagementService).getWorkflowsForVnf(isA(GetVnfWorkflowRelationRequest.class));
308
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)));
314     }
315
316     @Test
317     public void createWorkflowRelation_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception {
318
319         VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse();
320
321         given(changeManagementService
322             .addVnfWorkflowRelation(argThat(request -> matches(request, VNF_WORKFLOW_RELATION_REQUEST_JSON))))
323             .willReturn(response);
324
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)));
330     }
331
332     @Test
333     public void createWorkflowRelation_shouldReturnInternalServerError_whenServiceThrowsException() throws Exception {
334
335         VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_ADD_MSG));
336
337         willThrow(new RuntimeException("runtime exception message"))
338             .given(changeManagementService).addVnfWorkflowRelation(argThat(request -> matches(request,
339             VNF_WORKFLOW_RELATION_REQUEST_JSON)));
340
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)));
346     }
347
348     @Test
349     public void getAllWorkflowRelation_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception {
350
351         VnfDetailsWithWorkflows workflows = new VnfDetailsWithWorkflows();
352         workflows.setWorkflows(ImmutableList.of("workflow1", "workflow2"));
353         VnfWorkflowRelationAllResponse response = new VnfWorkflowRelationAllResponse(ImmutableList.of(workflows));
354
355         given(changeManagementService.getAllVnfWorkflowRelations()).willReturn(response);
356
357         mockMvc.perform(get(VNF_WORKFLOW_RELATION_URL))
358             .andExpect(status().isOk())
359             .andExpect(content().json(objectMapper.writeValueAsString(response)));
360     }
361
362     @Test
363     public void getAllWorkflowRelation_shouldReturnInternalServerError_whenServiceThrowsRuntimeException()
364         throws Exception {
365
366         VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_GET_ALL_MSG));
367
368         willThrow(new RuntimeException("runtime exception message"))
369             .given(changeManagementService).getAllVnfWorkflowRelations();
370
371         mockMvc.perform(get(VNF_WORKFLOW_RELATION_URL))
372             .andExpect(status().isInternalServerError())
373             .andExpect(content().json(objectMapper.writeValueAsString(response)));
374     }
375
376     @Test
377     public void deleteWorkflowRelation_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception {
378         VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of("abc"));
379
380         given(changeManagementService.deleteVnfWorkflowRelation(argThat(request -> matches(request,
381             VNF_WORKFLOW_RELATION_REQUEST_JSON))))
382             .willReturn(response);
383
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)));
389     }
390
391     @Test
392     public void deleteWorkflowRelation_shouldReturnInternalServerError_whenServiceThrowsRuntimeException()
393         throws Exception {
394         VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_DELETE_MSG));
395
396         willThrow(new RuntimeException("runtime exception message"))
397             .given(changeManagementService).deleteVnfWorkflowRelation(argThat(request -> matches(request,
398             VNF_WORKFLOW_RELATION_REQUEST_JSON)));
399
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)));
405     }
406
407     private <T> boolean matches(T request, String expectedJson) {
408         try {
409             return objectMapper.writeValueAsString(request).equals(expectedJson);
410         } catch (JsonProcessingException e) {
411             System.out.println("Exception occurred: " + e.getMessage());
412         }
413         return false;
414     }
415
416     private ArgumentMatcher<MultipartFile> multipartFileMatcher(MultipartFile otherFile) {
417         return other -> {
418             try {
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());
424             }
425             return false;
426         };
427     }
428
429     private Request createRequest(String networkInstanceId, String statusMessage) {
430         Request req = new Request();
431         InstanceIds instanceIds = new InstanceIds();
432         instanceIds.setNetworkInstanceId(networkInstanceId);
433
434         RequestStatus requestStatus = new RequestStatus();
435         requestStatus.setStatusMessage(statusMessage);
436
437         req.setInstanceIds(instanceIds);
438         req.setRequestStatus(requestStatus);
439
440         return req;
441     }
442
443     private String getRequestContent(String filename) {
444         InputStream inputStream = classLoader.getResourceAsStream(filename);
445         return new Scanner(inputStream).useDelimiter("\\A").next().replaceAll("\\s+", "");
446     }
447 }