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