aboutsummaryrefslogtreecommitdiffstats
path: root/vid-app-common/src/test/java/org/onap/vid/controllers/ChangeManagementControllerTest.java
blob: 3c8250b26df9870b72e1fe84999871a04309ba3e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
/*-
 * ============LICENSE_START=======================================================
 * VID
 * ================================================================================
 * Copyright © 2018 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Modifications Copyright 2018 Nokia
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.vid.controllers;

import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willThrow;
import static org.mockito.Matchers.argThat;
import static org.mockito.Matchers.isA;
import static org.onap.vid.controllers.ChangeManagementController.CHANGE_MANAGEMENT;
import static org.onap.vid.controllers.ChangeManagementController.GET_VNF_WORKFLOW_RELATION;
import static org.onap.vid.controllers.ChangeManagementController.SCHEDULER_BY_SCHEDULE_ID;
import static org.onap.vid.controllers.ChangeManagementController.VNF_WORKFLOW_RELATION;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collection;
import java.util.Scanner;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.log4j.BasicConfigurator;
import org.json.simple.JSONArray;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatcher;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.onap.vid.changeManagement.GetVnfWorkflowRelationRequest;
import org.onap.vid.changeManagement.GetWorkflowsResponse;
import org.onap.vid.changeManagement.VnfDetailsWithWorkflows;
import org.onap.vid.changeManagement.VnfWorkflowRelationAllResponse;
import org.onap.vid.changeManagement.VnfWorkflowRelationResponse;
import org.onap.vid.domain.mso.InstanceIds;
import org.onap.vid.domain.mso.RequestStatus;
import org.onap.vid.exceptions.NotFoundException;
import org.onap.vid.model.ExceptionResponse;
import org.onap.vid.mso.rest.Request;
import org.onap.vid.services.ChangeManagementService;
import org.onap.vid.services.WorkflowService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.multipart.MultipartFile;

@RunWith(MockitoJUnitRunner.class)
public class ChangeManagementControllerTest {

    private static final String FILE_NAME = "file";
    private static final String GET_VNF_WORKFLOW_RELATION_URL =
        "/" + CHANGE_MANAGEMENT + "/" + GET_VNF_WORKFLOW_RELATION;
    private static final String WORKFLOW_URL = "/" + CHANGE_MANAGEMENT + "/workflow";
    private static final String WORKFLOW_NAME_URL = WORKFLOW_URL + "/{name}";
    private static final String MSO_URL = "/" + CHANGE_MANAGEMENT + "/mso";
    private static final String UPLOAD_CONFIG_UPDATE_FILE_URL = "/" + CHANGE_MANAGEMENT + "/uploadConfigUpdateFile";
    private static final String SCHEDULER_URL = "/" + CHANGE_MANAGEMENT + "/scheduler";
    private static final String SCHEDULER_BY_SCHEDULE_ID_URL = "/" + CHANGE_MANAGEMENT + SCHEDULER_BY_SCHEDULE_ID;
    private static final String VNF_WORKFLOW_RELATION_URL = "/" + CHANGE_MANAGEMENT + "/" + VNF_WORKFLOW_RELATION;
    private static final String VNFS = "vnfs";

    private static final String FAILED_TO_GET_MSG = "Failed to get workflows for vnf";
    private static final String FAILED_TO_ADD_MSG = "Failed to add vnf to workflow relation";
    private static final String FAILED_TO_GET_ALL_MSG = "Failed to get all vnf to workflow relations";
    private static final String FAILED_TO_DELETE_MSG = "Failed to delete vnf from workflow relation";

    private final ObjectMapper objectMapper = new ObjectMapper();
    private ChangeManagementController controller;
    private MockMvc mockMvc;
    @Mock
    private WorkflowService workflowService;
    @Mock
    private ChangeManagementService changeManagementService;
    @Mock
    private Response mockResponse;
    @Mock
    private Response.StatusType statusType;
    private ClassLoader classLoader = getClass().getClassLoader();
    private final String CHANGE_MANAGEMENT_REQUEST_JSON = getRequestContent("change-management-request.json");
    private final String GET_VNF_WORKFLOW_RELATION_REQUEST_JSON = getRequestContent(
        "get-vnf-workflow-relation-request.json");
    private final String VNF_WORKFLOW_RELATION_REQUEST_JSON = getRequestContent("vnf-workflow-relation-request.json");

    @Before
    public void setUp() {
        controller = new ChangeManagementController(workflowService, changeManagementService, objectMapper);
        BasicConfigurator.configure();
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
    }

    @Test
    public void getWorkflow_shouldReturnListOfVnfs_whenServiceReturnsCorrectValue() throws Exception {

        Collection<String> givenVnfs = ImmutableList.of("vnf1", "vnf2", "vnf3");
        Collection<String> resultWorkflows = ImmutableList.of("workflow1", "workflow2");

        given(
            workflowService.getWorkflowsForVNFs(argThat(other -> CollectionUtils.isEqualCollection(givenVnfs, other))))
            .willReturn(resultWorkflows);

        mockMvc.perform(get(WORKFLOW_URL)
            .param(VNFS, StringUtils.join(givenVnfs, ",")))
            .andExpect(status().isOk())
            .andExpect(content().json(objectMapper.writeValueAsString(resultWorkflows)));
    }

    @Test
    public void getMSOChangeManagements_shouldReturnCollectionOfRequests_whenServiceReturnsCorrectValue()
        throws Exception {

        Collection<Request> requests = ImmutableList.of(
            createRequest("network-instance-id-1", "status-message-1"),
            createRequest("network-instance-id-2", "status-message-2"));

        given(changeManagementService.getMSOChangeManagements()).willReturn(requests);

        mockMvc.perform(get(MSO_URL))
            .andExpect(status().isOk())
            .andExpect(content().json(objectMapper.writeValueAsString(requests)));
    }

    @Test
    public void changeManagement_shouldReturnOkResponse_whenServiceReturnsCorrectValue() throws Exception {

        String vnfName = "vnfName1";
        String jsonBody = "{'param1': 'paramparam'}";

        given(changeManagementService.doChangeManagement(
            argThat(request -> matches(request, CHANGE_MANAGEMENT_REQUEST_JSON)), eq(vnfName)))
            .willReturn(ResponseEntity.ok().body(jsonBody));

        mockMvc.perform(post(WORKFLOW_NAME_URL, vnfName)
            .contentType(MediaType.APPLICATION_JSON)
            .content(CHANGE_MANAGEMENT_REQUEST_JSON))
            .andExpect(status().isOk())
            .andExpect(content().json(jsonBody));
    }

    @Test
    public void uploadConfigUpdateFile_shouldReturnOkResponse_whenServiceReturnsCorrectJson() throws Exception {

        String jsonString = "{'param1': 'paramparam'}";
        byte[] fileContent = "some file content".getBytes(StandardCharsets.UTF_8);
        MockMultipartFile file = new MockMultipartFile(FILE_NAME, fileContent);

        given(changeManagementService
            .uploadConfigUpdateFile(argThat(multipartFileMatcher(file))))
            .willReturn(jsonString);

        mockMvc.perform(MockMvcRequestBuilders
            .fileUpload(UPLOAD_CONFIG_UPDATE_FILE_URL)
            .file(file))
            .andExpect(status().isOk())
            .andExpect(content().json(jsonString));
    }

    @Test
    public void uploadConfigUpdateFile_shouldReturnResponseStatus_whenServiceThrowsWebApplicationException()
        throws Exception {

        byte[] fileContent = "some file content".getBytes(StandardCharsets.UTF_8);
        MockMultipartFile file = new MockMultipartFile(FILE_NAME, fileContent);

        given(statusType.getStatusCode()).willReturn(HttpStatus.NOT_FOUND.value());
        given(mockResponse.getStatus()).willReturn(HttpStatus.NOT_FOUND.value());
        given(mockResponse.getStatusInfo()).willReturn(statusType);

        WebApplicationException exception = new WebApplicationException(mockResponse);

        willThrow(exception).given(changeManagementService)
            .uploadConfigUpdateFile(argThat(multipartFileMatcher(file)));

        mockMvc.perform(MockMvcRequestBuilders
            .fileUpload(UPLOAD_CONFIG_UPDATE_FILE_URL)
            .file(file))
            .andExpect(status().isNotFound())
            .andExpect(content().json(objectMapper.writeValueAsString(new ExceptionResponse(exception))));
    }

    @Test
    public void uploadConfigUpdateFile_shouldReturnInternalServerError_whenServiceThrowsRuntimeException()
        throws Exception {

        byte[] fileContent = "some file content".getBytes(StandardCharsets.UTF_8);
        MockMultipartFile file = new MockMultipartFile(FILE_NAME, fileContent);

        RuntimeException exception = new RuntimeException("runtime exception message");

        willThrow(exception).given(changeManagementService)
            .uploadConfigUpdateFile(argThat(multipartFileMatcher(file)));

        mockMvc.perform(MockMvcRequestBuilders
            .fileUpload(UPLOAD_CONFIG_UPDATE_FILE_URL)
            .file(file))
            .andExpect(status().isInternalServerError())
            .andExpect(content().json(objectMapper.writeValueAsString(new ExceptionResponse(exception))));
    }

    @Test
    public void getSchedulerChangeManagements_shouldReturnJsonArray_whenServiceReturnsCorrectValue() throws Exception {

        JSONArray array = new JSONArray();
        array.add("element1");
        array.add("element2");

        given(changeManagementService.getSchedulerChangeManagements()).willReturn(array);

        mockMvc.perform(get(SCHEDULER_URL))
            .andExpect(status().isOk())
            .andExpect(content().json(array.toJSONString()));
    }

    @Test
    public void deleteSchedule_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception {

        String id = "schedule-id-1";
        Pair<String, Integer> pair = new ImmutablePair<>("myString", HttpStatus.OK.value());

        given(changeManagementService.deleteSchedule(id)).willReturn(pair);

        mockMvc.perform(delete(SCHEDULER_BY_SCHEDULE_ID_URL, id))
            .andExpect(status().isOk());
    }

    @Test
    public void deleteSchedule_shouldReturnNotFoundResponse_whenServiceReturnsNotFoundStatus() throws Exception {

        String id = "schedule-id-1";
        Pair<String, Integer> pair = new ImmutablePair<>("myString", HttpStatus.NOT_FOUND.value());

        given(changeManagementService.deleteSchedule(id)).willReturn(pair);

        mockMvc.perform(delete(SCHEDULER_BY_SCHEDULE_ID_URL, id))
            .andExpect(status().isNotFound());
    }

    @Test
    public void getWorkflows_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception {

        ImmutableList<String> elements = ImmutableList.of("workflow1", "workflow2");
        GetWorkflowsResponse response = new GetWorkflowsResponse();
        response.setWorkflows(elements);

        given(changeManagementService
            .getWorkflowsForVnf(argThat(request -> matches(request, GET_VNF_WORKFLOW_RELATION_REQUEST_JSON))))
            .willReturn(elements);

        mockMvc.perform(post(GET_VNF_WORKFLOW_RELATION_URL)
            .contentType(MediaType.APPLICATION_JSON)
            .content(GET_VNF_WORKFLOW_RELATION_REQUEST_JSON))
            .andExpect(status().isOk())
            .andExpect(content().json(objectMapper.writeValueAsString(response)));
    }

    @Test
    public void getWorkflows_shouldReturnNotFound_whenServiceThrowsNotFoundException() throws Exception {

        String errorMsg = "not found";
        VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(errorMsg));

        willThrow(new NotFoundException(errorMsg))
            .given(changeManagementService)
            .getWorkflowsForVnf(argThat(request -> matches(request, GET_VNF_WORKFLOW_RELATION_REQUEST_JSON)));

        mockMvc.perform(post(GET_VNF_WORKFLOW_RELATION_URL)
            .contentType(MediaType.APPLICATION_JSON)
            .content(GET_VNF_WORKFLOW_RELATION_REQUEST_JSON))
            .andExpect(status().isNotFound())
            .andExpect(content().json(objectMapper.writeValueAsString(response)));
    }

    @Test
    public void getWorkflows_shouldReturnInternalServerError_whenServiceThrowsRuntimeException() throws Exception {

        VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_GET_MSG));

        willThrow(new RuntimeException("runtime exception message"))
            .given(changeManagementService).getWorkflowsForVnf(isA(GetVnfWorkflowRelationRequest.class));

        mockMvc.perform(post(GET_VNF_WORKFLOW_RELATION_URL)
            .contentType(MediaType.APPLICATION_JSON)
            .content(VNF_WORKFLOW_RELATION_REQUEST_JSON))
            .andExpect(status().isInternalServerError())
            .andExpect(content().json(objectMapper.writeValueAsString(response)));
    }

    @Test
    public void createWorkflowRelation_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception {

        VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse();

        given(changeManagementService
            .addVnfWorkflowRelation(argThat(request -> matches(request, VNF_WORKFLOW_RELATION_REQUEST_JSON))))
            .willReturn(response);

        mockMvc.perform(post(VNF_WORKFLOW_RELATION_URL)
            .contentType(MediaType.APPLICATION_JSON)
            .content(VNF_WORKFLOW_RELATION_REQUEST_JSON))
            .andExpect(status().isOk())
            .andExpect(content().json(objectMapper.writeValueAsString(response)));
    }

    @Test
    public void createWorkflowRelation_shouldReturnInternalServerError_whenServiceThrowsException() throws Exception {

        VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_ADD_MSG));

        willThrow(new RuntimeException("runtime exception message"))
            .given(changeManagementService).addVnfWorkflowRelation(argThat(request -> matches(request,
            VNF_WORKFLOW_RELATION_REQUEST_JSON)));

        mockMvc.perform(post(VNF_WORKFLOW_RELATION_URL)
            .contentType(MediaType.APPLICATION_JSON)
            .content(VNF_WORKFLOW_RELATION_REQUEST_JSON))
            .andExpect(status().isInternalServerError())
            .andExpect(content().json(objectMapper.writeValueAsString(response)));
    }

    @Test
    public void getAllWorkflowRelation_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception {

        VnfDetailsWithWorkflows workflows = new VnfDetailsWithWorkflows();
        workflows.setWorkflows(ImmutableList.of("workflow1", "workflow2"));
        VnfWorkflowRelationAllResponse response = new VnfWorkflowRelationAllResponse(ImmutableList.of(workflows));

        given(changeManagementService.getAllVnfWorkflowRelations()).willReturn(response);

        mockMvc.perform(get(VNF_WORKFLOW_RELATION_URL))
            .andExpect(status().isOk())
            .andExpect(content().json(objectMapper.writeValueAsString(response)));
    }

    @Test
    public void getAllWorkflowRelation_shouldReturnInternalServerError_whenServiceThrowsRuntimeException()
        throws Exception {

        VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_GET_ALL_MSG));

        willThrow(new RuntimeException("runtime exception message"))
            .given(changeManagementService).getAllVnfWorkflowRelations();

        mockMvc.perform(get(VNF_WORKFLOW_RELATION_URL))
            .andExpect(status().isInternalServerError())
            .andExpect(content().json(objectMapper.writeValueAsString(response)));
    }

    @Test
    public void deleteWorkflowRelation_shouldReturnOkResponse_whenServiceReturnsOkStatus() throws Exception {
        VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of("abc"));

        given(changeManagementService.deleteVnfWorkflowRelation(argThat(request -> matches(request,
            VNF_WORKFLOW_RELATION_REQUEST_JSON))))
            .willReturn(response);

        mockMvc.perform(delete(VNF_WORKFLOW_RELATION_URL)
            .contentType(MediaType.APPLICATION_JSON)
            .content(VNF_WORKFLOW_RELATION_REQUEST_JSON))
            .andExpect(status().isOk())
            .andExpect(content().json(objectMapper.writeValueAsString(response)));
    }

    @Test
    public void deleteWorkflowRelation_shouldReturnInternalServerError_whenServiceThrowsRuntimeException()
        throws Exception {
        VnfWorkflowRelationResponse response = new VnfWorkflowRelationResponse(ImmutableList.of(FAILED_TO_DELETE_MSG));

        willThrow(new RuntimeException("runtime exception message"))
            .given(changeManagementService).deleteVnfWorkflowRelation(argThat(request -> matches(request,
            VNF_WORKFLOW_RELATION_REQUEST_JSON)));

        mockMvc.perform(delete(VNF_WORKFLOW_RELATION_URL)
            .contentType(MediaType.APPLICATION_JSON)
            .content(VNF_WORKFLOW_RELATION_REQUEST_JSON))
            .andExpect(status().isInternalServerError())
            .andExpect(content().json(objectMapper.writeValueAsString(response)));
    }

    private <T> boolean matches(T request, String expectedJson) {
        try {
            return objectMapper.writeValueAsString(request).equals(expectedJson);
        } catch (JsonProcessingException e) {
            System.out.println("Exception occurred: " + e.getMessage());
        }
        return false;
    }

    private ArgumentMatcher<MultipartFile> multipartFileMatcher(MultipartFile otherFile) {
        return other -> {
            try {
                return other.getName().equals(otherFile.getName())
                    && other.getSize() == otherFile.getSize()
                    && Arrays.equals(other.getBytes(), otherFile.getBytes());
            } catch (IOException e) {
                System.out.println("IOException occurred: " + e.getMessage());
            }
            return false;
        };
    }

    private Request createRequest(String networkInstanceId, String statusMessage) {
        Request req = new Request();
        InstanceIds instanceIds = new InstanceIds();
        instanceIds.setNetworkInstanceId(networkInstanceId);

        RequestStatus requestStatus = new RequestStatus();
        requestStatus.setStatusMessage(statusMessage);

        req.setInstanceIds(instanceIds);
        req.setRequestStatus(requestStatus);

        return req;
    }

    private String getRequestContent(String filename) {
        InputStream inputStream = classLoader.getResourceAsStream(filename);
        return new Scanner(inputStream).useDelimiter("\\A").next().replaceAll("\\s+", "");
    }
}