718e22fb4e56adb746fa865bf86c64082cc69b44
[vid.git] / vid-app-common / src / test / java / org / onap / vid / mso / MsoBusinessLogicImplTest.java
1 /*
2  * ============LICENSE_START==========================================
3  * ===================================================================
4  * Modifications Copyright (C) 2018 Nokia. All rights reserved.
5  * ===================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *        http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  * ============LICENSE_END============================================
18  *
19  *
20  */
21 package org.onap.vid.mso;
22
23 import com.fasterxml.jackson.core.type.TypeReference;
24 import com.fasterxml.jackson.databind.ObjectMapper;
25 import org.junit.Before;
26 import org.junit.Test;
27 import org.junit.runner.RunWith;
28 import org.mockito.ArgumentMatcher;
29 import org.mockito.Mock;
30 import org.mockito.MockitoAnnotations;
31 import org.onap.portalsdk.core.util.SystemProperties;
32 import org.onap.vid.exceptions.GenericUncheckedException;
33 import org.onap.vid.mso.rest.Request;
34 import org.onap.vid.mso.rest.RequestDetails;
35 import org.onap.vid.mso.rest.RequestDetailsWrapper;
36 import org.onap.vid.properties.Features;
37 import org.springframework.http.HttpStatus;
38 import org.springframework.test.context.ContextConfiguration;
39 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
40 import org.togglz.core.manager.FeatureManager;
41
42 import java.io.IOException;
43 import java.net.URL;
44 import java.nio.file.Files;
45 import java.nio.file.Path;
46 import java.nio.file.Paths;
47 import java.util.List;
48 import java.util.stream.Collectors;
49
50 import static org.assertj.core.api.Assertions.assertThat;
51 import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
52 import static org.junit.Assert.assertEquals;
53 import static org.mockito.ArgumentMatchers.*;
54 import static org.mockito.BDDMockito.given;
55 import static org.mockito.Mockito.mock;
56 import static org.onap.vid.mso.MsoBusinessLogicImpl.validateEndpointPath;
57
58 @ContextConfiguration(classes = {SystemProperties.class})
59 @RunWith(SpringJUnit4ClassRunner.class)
60 public class MsoBusinessLogicImplTest {
61
62     private static final ObjectMapper objectMapper = new ObjectMapper();
63
64     @Mock
65     private FeatureManager featureManager;
66
67     @Mock
68     private MsoInterface msoInterface;
69
70     private MsoBusinessLogicImpl msoBusinessLogic;
71
72     @Before
73     public void setUp() {
74         MockitoAnnotations.initMocks(this);
75         msoBusinessLogic = new MsoBusinessLogicImpl(msoInterface, featureManager);
76     }
77
78     @Test
79     public void createConfigurationInstance_shouldCallMsoInterface_withCorrectServiceInstanceId() throws Exception {
80         // given
81         String serviceInstanceId = "3f93c7cb-2fd0-4557-9514-e189b7b04f9d";
82         String endpointTemplate = String.format("/serviceInstances/v6/%s/configurations", serviceInstanceId);
83         RequestDetailsWrapper requestDetailsWrapper = createRequestDetails("mso_request_create_configuration.json");
84         MsoResponseWrapper expectedResponse = createOkResponse();
85         given(msoInterface.createConfigurationInstance(requestDetailsWrapper, endpointTemplate))
86             .willReturn(expectedResponse);
87
88         // when
89         MsoResponseWrapper msoResponseWrapper = msoBusinessLogic
90             .createConfigurationInstance(requestDetailsWrapper, serviceInstanceId);
91
92         // then
93         assertThat(msoResponseWrapper).isEqualToComparingFieldByField(expectedResponse);
94     }
95
96     private RequestDetailsWrapper createRequestDetails(String bodyFileName) throws Exception {
97         final URL resource = this.getClass().getResource("/payload_jsons/" + bodyFileName);
98         RequestDetails requestDetails = objectMapper.readValue(resource, RequestDetails.class);
99         return new RequestDetailsWrapper(requestDetails);
100     }
101
102     @Test
103     public void validateEndpointPath_endPointIsNotEmptyAndVaild_returnProperty() {
104         System.setProperty("TestEnv", "123");
105         String foundEndPoint = validateEndpointPath("TestEnv");
106         assertEquals("123", foundEndPoint);
107     }
108
109     @Test
110     public void validateEndpointPath_endPointIsNull_throwRuntimeException() {
111         assertThatExceptionOfType(RuntimeException.class)
112             .isThrownBy(() -> validateEndpointPath("NotExists"));
113     }
114
115     @Test
116     public void validateEndpointPath_endPointIsNotEmptyButDoesntExists_throwRuntimeException() {
117         String endPoint = "EmptyEndPoint";
118         System.setProperty(endPoint, "");
119         assertThatExceptionOfType(GenericUncheckedException.class)
120             .isThrownBy(() -> validateEndpointPath(endPoint))
121             .withMessage(endPoint + " env variable is not defined");
122     }
123
124     @Test
125     public void deleteSvcInstance_verifyEndPointPathConstructing_unAssignFeatureOffOrUnAssignFlagIsFalse() {
126         // given
127         String endpointTemplate = "/serviceInstances/v5/%s";
128         String serviceInstanceId = "3f93c7cb-2fd0-4557-9514-e189b7b04f9d";
129         String svcEndpoint = String.format(endpointTemplate, serviceInstanceId);
130         RequestDetails requestDetails = new RequestDetails();
131         MsoResponseWrapper expectedResponse = createOkResponse();
132         given(msoInterface.deleteSvcInstance(requestDetails, svcEndpoint)).willReturn(expectedResponse);
133         given(featureManager.isActive(Features.FLAG_UNASSIGN_SERVICE)).willReturn(false);
134
135         // when
136         MsoResponseWrapper msoResponseWrapper = msoBusinessLogic
137             .deleteSvcInstance(requestDetails, serviceInstanceId, "unAssignOrDeleteParams");
138
139         // then
140         assertThat(msoResponseWrapper).isEqualToComparingFieldByField(expectedResponse);
141     }
142
143     @Test
144     public void deleteSvcInstance_verifyEndPointPathConstructing_unAssignFeatureOnAndUnAssignFlagIsTrue() {
145         // given
146         String endpointTemplate = "/serviceInstantiation/v5/serviceInstances/%s/unassign";
147         String serviceInstanceId = "3f93c7cb-2fd0-4557-9514-e189b7b04f9d";
148         String svcEndpoint = String.format(endpointTemplate, serviceInstanceId);
149         RequestDetails requestDetails = new RequestDetails();
150         MsoResponseWrapper expectedResponse = createOkResponse();
151         given(msoInterface.unassignSvcInstance(requestDetails, svcEndpoint)).willReturn(expectedResponse);
152         given(featureManager.isActive(Features.FLAG_UNASSIGN_SERVICE)).willReturn(true);
153
154         // when
155         MsoResponseWrapper msoResponseWrapper = msoBusinessLogic
156             .deleteSvcInstance(requestDetails, serviceInstanceId, "assigned");
157
158         // then
159         assertThat(msoResponseWrapper).isEqualToComparingFieldByField(expectedResponse);
160     }
161
162     @Test
163     public void deleteVnf_verifyEndPointPathConstructing() {
164         // when
165         String endpointTemplate = "/serviceInstances/v5/%s/vnfs/%s";
166         String serviceInstanceId = "3f93c7cb-2fd0-4557-9514-e189b7b04f9d";
167         String vnfInstanceId = "testVnfInstanceTempId";
168         String vnfEndpoint = String.format(endpointTemplate, serviceInstanceId, vnfInstanceId);
169         RequestDetails requestDetails = new RequestDetails();
170         MsoResponseWrapper expectedResponse = createOkResponse();
171         given(msoInterface.deleteVnf(requestDetails, vnfEndpoint)).willReturn(expectedResponse);
172
173         // when
174         MsoResponseWrapper msoResponseWrapper = msoBusinessLogic
175             .deleteVnf(requestDetails, serviceInstanceId, vnfInstanceId);
176
177         // then
178         assertThat(msoResponseWrapper).isEqualToComparingFieldByField(expectedResponse);
179     }
180
181     @Test
182     public void deleteVfModule_verifyEndPointPathConstructing() {
183         // when
184         String endpointTemplate = "/serviceInstances/v7/%s/vnfs/%s/vfModules/%s";
185         String serviceInstanceId = "3f93c7cb-2fd0-4557-9514-e189b7b04f9d";
186         String vnfInstanceId = "testVnfInstanceTempId";
187         String vfModuleId = "testVfModuleId";
188         String vnfEndpoint = String.format(endpointTemplate, serviceInstanceId, vnfInstanceId, vfModuleId);
189         RequestDetails requestDetails = new RequestDetails();
190         MsoResponseWrapper expectedResponse = createOkResponse();
191         given(msoInterface.deleteVfModule(requestDetails, vnfEndpoint)).willReturn(expectedResponse);
192
193         // when
194         MsoResponseWrapper msoResponseWrapper = msoBusinessLogic
195             .deleteVfModule(requestDetails, serviceInstanceId, vnfInstanceId, vfModuleId);
196         // then
197         assertThat(msoResponseWrapper).isEqualToComparingFieldByField(expectedResponse);
198     }
199
200     @Test
201     public void shouldSendProperScaleOutRequest() throws IOException {
202         // given
203         String serviceInstanceId = "3f93c7cb-2fd0-4557-9514-e189b7b04f9d";
204         String vnfInstanceId = "testVnfInstanceTempId";
205         String endpointTemplate = "/serviceInstantiation/v7/serviceInstances/%s/vnfs/%s/vfModules/scaleOut";
206         String vnfEndpoint = String.format(endpointTemplate, serviceInstanceId, vnfInstanceId);
207         org.onap.vid.changeManagement.RequestDetails requestDetails = readRequest(
208             "scaleOutVfModulePayload.json");
209         org.onap.vid.changeManagement.RequestDetailsWrapper expectedRequest = readExpectedRequest(
210             "scaleOutVfModulePayloadToMso.json");
211         MsoResponseWrapper expectedMsoResponseWrapper = createOkResponse();
212         given(
213             msoInterface
214                 .scaleOutVFModuleInstance(argThat(new MsoRequestWrapperMatcher(expectedRequest)),
215                     eq(vnfEndpoint)))
216             .willReturn(expectedMsoResponseWrapper);
217
218         // when
219         MsoResponseWrapper msoResponseWrapper = msoBusinessLogic
220             .scaleOutVfModuleInstance(requestDetails, serviceInstanceId, vnfInstanceId);
221
222         // then
223         assertThat(msoResponseWrapper).isEqualToComparingFieldByField(expectedMsoResponseWrapper);
224     }
225
226     private org.onap.vid.changeManagement.RequestDetails readRequest(String requestJsonFilename) throws IOException {
227         Path path = Paths.get("payload_jsons", requestJsonFilename);
228         URL url = this.getClass().getClassLoader().getResource(path.toString());
229         return objectMapper.readValue(url, org.onap.vid.changeManagement.RequestDetails.class);
230     }
231
232     private org.onap.vid.changeManagement.RequestDetailsWrapper readExpectedRequest(String requestJsonFilename)
233         throws IOException {
234         Path path = Paths.get("payload_jsons", requestJsonFilename);
235         URL url = this.getClass().getClassLoader().getResource(path.toString());
236         return objectMapper.readValue(url,
237             new TypeReference<org.onap.vid.changeManagement.RequestDetailsWrapper<org.onap.vid.changeManagement.RequestDetails>>() {
238             });
239     }
240
241     private MsoResponseWrapper createOkResponse() {
242         HttpStatus expectedStatus = HttpStatus.ACCEPTED;
243         String expectedBody = " \"body\": {\n" +
244             "      \"requestReferences\": {\n" +
245             "        \"instanceId\": \" 123456 \",\n" +
246             "        \"requestId\": \"b6dc9806-b094-42f7-9386-a48de8218ce8\"\n" +
247             "      }";
248         MsoResponseWrapper responseWrapper = new MsoResponseWrapper();
249         responseWrapper.setEntity(expectedBody);
250         responseWrapper.setStatus(expectedStatus.value());
251         return responseWrapper;
252     }
253
254     @Test
255     public void shouldFilterOutOrchestrationRequestsNotAllowedInDashboard() throws IOException {
256         //given
257         String vnfModelTypeOrchestrationRequests = getFileContentAsString("mso_model_info_sample_response.json");
258         String scaleOutActionOrchestrationRequests = getFileContentAsString("mso_action_scaleout_sample_response.json");
259
260         MsoResponseWrapper msoResponseWrapperMock = mock(MsoResponseWrapper.class);
261         given(msoInterface
262             .getOrchestrationRequestsForDashboard(any(String.class), any(String.class), any(String.class),
263                 any(RestObject.class)))
264             .willReturn(msoResponseWrapperMock);
265         given(msoResponseWrapperMock.getEntity())
266             .willReturn(vnfModelTypeOrchestrationRequests, scaleOutActionOrchestrationRequests);
267
268         //when
269         List<Request> filteredOrchestrationReqs = msoBusinessLogic.getOrchestrationRequestsForDashboard();
270
271         //then
272         assertThat(filteredOrchestrationReqs).hasSize(3);
273         assertThat(MsoBusinessLogicImpl.DASHBOARD_ALLOWED_TYPES)
274             .containsAll(filteredOrchestrationReqs
275                 .stream()
276                 .map(el -> el.getRequestType().toUpperCase())
277                 .collect(Collectors.toList()));
278         assertThat(filteredOrchestrationReqs)
279             .extracting(org.onap.vid.domain.mso.Request::getRequestScope)
280             .containsOnly("vnf", "vfModule");
281     }
282
283     private String getFileContentAsString(String resourceName) throws IOException {
284         URL url = this.getClass().getClassLoader().getResource(".");
285         Path path = Paths.get(url.getPath(), "payload_jsons", resourceName);
286         return new String(Files.readAllBytes(path));
287     }
288
289     private static class MsoRequestWrapperMatcher implements
290         ArgumentMatcher<org.onap.vid.changeManagement.RequestDetailsWrapper> {
291
292         private final org.onap.vid.changeManagement.RequestDetailsWrapper expectedRequest;
293
294         public MsoRequestWrapperMatcher(org.onap.vid.changeManagement.RequestDetailsWrapper expectedRequest) {
295             this.expectedRequest = expectedRequest;
296         }
297
298         @Override
299         public boolean matches(org.onap.vid.changeManagement.RequestDetailsWrapper argument) {
300             return expectedRequest.requestDetails.equals(argument.requestDetails);
301         }
302     }
303 }
304