9d5577c7dbd81f2b159552768274a260343286a2
[vid.git] / vid-app-common / src / test / java / org / onap / vid / mso / MsoBusinessLogicImplTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
4  * ================================================================================
5  * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 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.mso;
23
24 import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals;
25 import static org.assertj.core.api.Assertions.assertThat;
26 import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
27 import static org.assertj.core.api.Assertions.tuple;
28 import static org.hamcrest.Matchers.allOf;
29 import static org.hamcrest.Matchers.containsString;
30 import static org.hamcrest.Matchers.equalTo;
31 import static org.hamcrest.Matchers.hasEntry;
32 import static org.hamcrest.Matchers.instanceOf;
33 import static org.hamcrest.Matchers.is;
34 import static org.hamcrest.Matchers.startsWith;
35 import static org.junit.Assert.assertEquals;
36 import static org.mockito.ArgumentMatchers.any;
37 import static org.mockito.ArgumentMatchers.anyBoolean;
38 import static org.mockito.ArgumentMatchers.anyString;
39 import static org.mockito.ArgumentMatchers.argThat;
40 import static org.mockito.ArgumentMatchers.endsWith;
41 import static org.mockito.ArgumentMatchers.eq;
42 import static org.mockito.ArgumentMatchers.isA;
43 import static org.mockito.BDDMockito.given;
44 import static org.mockito.Mockito.doThrow;
45 import static org.mockito.Mockito.mock;
46 import static org.mockito.Mockito.when;
47 import static org.onap.vid.controller.MsoController.CONFIGURATION_ID;
48 import static org.onap.vid.controller.MsoController.REQUEST_TYPE;
49 import static org.onap.vid.controller.MsoController.SVC_INSTANCE_ID;
50 import static org.onap.vid.controller.MsoController.VNF_INSTANCE_ID;
51 import static org.onap.vid.model.probes.ExternalComponentStatus.Component.MSO;
52 import static org.onap.vid.mso.MsoBusinessLogicImpl.validateEndpointPath;
53
54 import com.fasterxml.jackson.core.type.TypeReference;
55 import com.fasterxml.jackson.databind.ObjectMapper;
56 import io.joshworks.restclient.http.HttpResponse;
57 import java.io.IOException;
58 import java.net.URL;
59 import java.nio.file.Path;
60 import java.nio.file.Paths;
61 import java.util.ArrayList;
62 import java.util.HashMap;
63 import java.util.List;
64 import java.util.Map;
65 import java.util.UUID;
66 import java.util.stream.Collectors;
67 import javax.ws.rs.BadRequestException;
68 import org.apache.commons.io.IOUtils;
69 import org.apache.http.HttpException;
70 import org.hamcrest.Matcher;
71 import org.hamcrest.MatcherAssert;
72 import org.jetbrains.annotations.NotNull;
73 import org.mockito.ArgumentMatcher;
74 import org.mockito.Mock;
75 import org.mockito.MockitoAnnotations;
76 import org.mockito.hamcrest.MockitoHamcrest;
77 import org.onap.portalsdk.core.util.SystemProperties;
78 import org.onap.vid.aai.ExceptionWithRequestInfo;
79 import org.onap.vid.aai.HttpResponseWithRequestInfo;
80 import org.onap.vid.changeManagement.ChangeManagementRequest;
81 import org.onap.vid.changeManagement.WorkflowRequestDetail;
82 import org.onap.vid.controller.OperationalEnvironmentController;
83 import org.onap.vid.exceptions.GenericUncheckedException;
84 import org.onap.vid.model.SOWorkflowList;
85 import org.onap.vid.model.SoftDeleteRequest;
86 import org.onap.vid.model.probes.ErrorMetadata;
87 import org.onap.vid.model.probes.ExternalComponentStatus;
88 import org.onap.vid.model.probes.HttpRequestMetadata;
89 import org.onap.vid.mso.model.CloudConfiguration;
90 import org.onap.vid.mso.model.ModelInfo;
91 import org.onap.vid.mso.model.OperationalEnvironmentActivateInfo;
92 import org.onap.vid.mso.model.OperationalEnvironmentDeactivateInfo;
93 import org.onap.vid.mso.model.RequestParameters;
94 import org.onap.vid.mso.rest.OperationalEnvironment.OperationEnvironmentRequestDetails;
95 import org.onap.vid.mso.rest.Request;
96 import org.onap.vid.mso.rest.RequestDetails;
97 import org.onap.vid.mso.rest.RequestDetailsWrapper;
98 import org.onap.vid.mso.rest.Task;
99 import org.onap.vid.testUtils.TestUtils;
100 import org.springframework.http.HttpMethod;
101 import org.springframework.http.HttpStatus;
102 import org.springframework.test.context.ContextConfiguration;
103 import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
104 import org.testng.annotations.BeforeClass;
105 import org.testng.annotations.DataProvider;
106 import org.testng.annotations.Test;
107 import org.togglz.core.manager.FeatureManager;
108
109 @ContextConfiguration(classes = {SystemProperties.class})
110 public class MsoBusinessLogicImplTest extends AbstractTestNGSpringContextTests {
111
112     private static final ObjectMapper objectMapper = new ObjectMapper();
113     private static final String MY_PRETTY_URL = "my pretty url";
114
115     @Mock
116     private MsoInterface msoInterface;
117
118     @Mock
119     private SOWorkflowList workflowList;
120
121     @Mock
122     private HttpResponse<SOWorkflowList> workflowListResponse;
123
124     @Mock
125     private RequestDetails msoRequest;
126
127     @Mock
128     private FeatureManager featureManager;
129
130
131
132     private MsoBusinessLogicImpl msoBusinessLogic;
133     private String userId = "testUserId";
134     private String operationalEnvironmentId = "testOperationalEnvironmentId";
135
136     @BeforeClass
137     public void setUp() {
138         MockitoAnnotations.initMocks(this);
139         msoBusinessLogic = new MsoBusinessLogicImpl(msoInterface, featureManager);
140     }
141
142     @Test
143     public void shouldProperlyCreateConfigurationInstanceWithCorrectServiceInstanceId() throws Exception {
144         // given
145         String serviceInstanceId = "3f93c7cb-2fd0-4557-9514-e189b7b04f9d";
146         String endpointTemplate = String.format("/serviceInstantiation/v7/serviceInstances/%s/configurations", serviceInstanceId);
147         RequestDetailsWrapper requestDetailsWrapper = createRequestDetails();
148         MsoResponseWrapper expectedResponse = createOkResponse();
149         given(msoInterface.createConfigurationInstance(requestDetailsWrapper, endpointTemplate))
150                 .willReturn(expectedResponse);
151
152         // when
153         MsoResponseWrapper msoResponseWrapper = msoBusinessLogic
154                 .createConfigurationInstance(requestDetailsWrapper, serviceInstanceId);
155
156         // then
157         assertThat(msoResponseWrapper).isEqualToComparingFieldByField(expectedResponse);
158     }
159
160     private RequestDetailsWrapper createRequestDetails() throws Exception {
161         final URL resource = this.getClass().getResource("/payload_jsons/mso_request_create_configuration.json");
162         RequestDetails requestDetails = objectMapper.readValue(resource, RequestDetails.class);
163         return new RequestDetailsWrapper(requestDetails);
164     }
165
166     @Test
167     public void shouldProperlyValidateEndpointPathWheEendPointIsNotEmptyAndValid() {
168         System.setProperty("TestEnv", "123");
169         String foundEndPoint = validateEndpointPath("TestEnv");
170         assertEquals("123", foundEndPoint);
171     }
172
173     @Test
174     public void shouldThrowRuntimeExceptionWhenValidateEndpointPathEndPointIsNotEmptyAndValid() {
175         assertThatExceptionOfType(RuntimeException.class)
176                 .isThrownBy(() -> validateEndpointPath("NotExists"));
177     }
178
179     @Test
180     public void shouldThrowRuntimeExceptionWhenValidateEndpointPathWhenEndPointIsNotEmptyButDoesntExists() {
181         String endPoint = "EmptyEndPoint";
182         System.setProperty(endPoint, "");
183         assertThatExceptionOfType(GenericUncheckedException.class)
184                 .isThrownBy(() -> validateEndpointPath(endPoint))
185                 .withMessage(endPoint + " env variable is not defined");
186     }
187
188     @Test
189     public void shouldProperlyCreateSvcInstanceWithProperParameters() {
190
191         MsoResponseWrapper expectedResponse = createOkResponse();
192         String svcEndpoint = SystemProperties.getProperty(MsoProperties.MSO_RESTAPI_SERVICE_INSTANCE);
193         given(msoInterface.createSvcInstance(msoRequest, svcEndpoint)).willReturn(expectedResponse);
194
195         MsoResponseWrapper response = msoBusinessLogic.createSvcInstance(msoRequest);
196
197         // then
198         assertThat(response).isEqualToComparingFieldByField(expectedResponse);
199     }
200
201     @Test
202     public void shouldProperlyCreateE2eSvcInstanceWithProperParameters() {
203         //  given
204         MsoResponseWrapper expectedResponse = createOkResponse();
205         String svcEndpoint = SystemProperties.getProperty(MsoProperties.MSO_REST_API_E2E_SVC_INSTANCE);
206         given(msoInterface.createE2eSvcInstance(msoRequest, svcEndpoint)).willReturn(expectedResponse);
207
208         //  when
209         MsoResponseWrapper response = msoBusinessLogic.createE2eSvcInstance(msoRequest);
210
211         // then
212         assertThat(response).isEqualToComparingFieldByField(expectedResponse);
213     }
214
215     @Test
216     public void shouldProperlyCreateVnfWithProperParameters() {
217
218         MsoResponseWrapper expectedResponse = createOkResponse();
219         String endpoint = SystemProperties.getProperty(MsoProperties.MSO_REST_API_VNF_INSTANCE);
220         String vnfInstanceId = "testVnfInstanceTempId";
221         String vnfEndpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, vnfInstanceId);
222
223         given(msoInterface.createVnf(msoRequest, vnfEndpoint)).willReturn(expectedResponse);
224
225         MsoResponseWrapper response = msoBusinessLogic.createVnf(msoRequest, vnfInstanceId);
226
227         // then
228         assertThat(response).isEqualToComparingFieldByField(expectedResponse);
229     }
230
231     @Test
232     public void shouldProperlyCreateNwInstanceWithProperParameters() {
233
234         MsoResponseWrapper expectedResponse = createOkResponse();
235         String vnfInstanceId = "testNwInstanceTempId";
236         String nwEndpoint = SystemProperties.getProperty(MsoProperties.MSO_REST_API_NETWORK_INSTANCE);
237         String nw_endpoint = nwEndpoint.replaceFirst(SVC_INSTANCE_ID, vnfInstanceId);
238
239         given(msoInterface.createNwInstance(msoRequest, nw_endpoint)).willReturn(expectedResponse);
240
241         MsoResponseWrapper response = msoBusinessLogic.createNwInstance(msoRequest, vnfInstanceId);
242
243         // then
244         assertThat(response).isEqualToComparingFieldByField(expectedResponse);
245     }
246
247     @Test
248     public void shouldProperlyCreateVolumeGroupInstanceWithProperParameters() {
249         MsoResponseWrapper expectedResponse = createOkResponse();
250         String serviceInstanceId = "testServiceInstanceTempId";
251         String vnfInstanceId = "testVnfInstanceTempId";
252         String nwEndpoint = SystemProperties.getProperty(MsoProperties.MSO_REST_API_VOLUME_GROUP_INSTANCE);
253         String vnfEndpoint = nwEndpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId);
254         vnfEndpoint = vnfEndpoint.replaceFirst(VNF_INSTANCE_ID, vnfInstanceId);
255
256         given(msoInterface.createVolumeGroupInstance(msoRequest, vnfEndpoint)).willReturn(expectedResponse);
257
258         MsoResponseWrapper response = msoBusinessLogic.createVolumeGroupInstance(msoRequest, serviceInstanceId, vnfInstanceId);
259
260         // then
261         assertThat(response).isEqualToComparingFieldByField(expectedResponse);
262     }
263
264     @Test
265     public void shouldProperlyCreateVfModuleInstanceWithProperParameters() {
266         MsoResponseWrapper expectedResponse = createOkResponse();
267         String serviceInstanceId = "testServiceInstanceTempId";
268         String vnfInstanceId = "testVnfInstanceTempId";
269         String partial_endpoint = SystemProperties.getProperty(MsoProperties.MSO_REST_API_VF_MODULE_INSTANCE);
270         String vf_module_endpoint = partial_endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId);
271         vf_module_endpoint = vf_module_endpoint.replaceFirst(VNF_INSTANCE_ID, vnfInstanceId);
272
273         given(msoInterface.createVfModuleInstance(msoRequest, vf_module_endpoint)).willReturn(expectedResponse);
274
275         MsoResponseWrapper response = msoBusinessLogic.createVfModuleInstance(msoRequest, serviceInstanceId, vnfInstanceId);
276
277         // then
278         assertThat(response).isEqualToComparingFieldByField(expectedResponse);
279     }
280
281     @Test
282     public void shouldProperlyDeleteE2eSvcInstanceWithProperParameters() {
283         MsoResponseWrapper expectedResponse = createOkResponse();
284         String serviceInstanceId = "testDeleteE2eSvcInstanceTempId";
285         String endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_E2E_SVC_INSTANCE) + "/" + serviceInstanceId;
286
287         given(msoInterface.deleteE2eSvcInstance(msoRequest, endpoint)).willReturn(expectedResponse);
288
289         MsoResponseWrapper response = msoBusinessLogic.deleteE2eSvcInstance(msoRequest, serviceInstanceId);
290
291         // then
292         assertThat(response).isEqualToComparingFieldByField(expectedResponse);
293     }
294
295     @DataProvider
296     public Object[][] deleteSvcInstanceShouldDelete() {
297         return new Object[][]{{"Active"}, {"unexpected-status"}};
298     }
299
300     @DataProvider
301     public Object[][] deleteSvcInstanceShouldUnassign() {
302         return new Object[][]{{"Created"}, {"Pendingdelete"}, {"pending-Delete"}, {"Assigned"}};
303     }
304
305
306     @Test(dataProvider = "deleteSvcInstanceShouldDelete")
307     public void shouldProperlyDeleteSvcInstanceWithProperParametersShouldDelete(String status) {
308         // given
309         String endpointTemplate = "/serviceInstantiation/v7/serviceInstances/%s";
310         String serviceInstanceId = "3f93c7cb-2fd0-4557-9514-e189b7b04f9d";
311         String svcEndpoint = String.format(endpointTemplate, serviceInstanceId);
312         RequestDetails requestDetails = new RequestDetails();
313         MsoResponseWrapper expectedResponse = createOkResponse();
314         given(msoInterface.deleteSvcInstance(requestDetails, svcEndpoint)).willReturn(expectedResponse);
315
316         // when
317         MsoResponseWrapper msoResponseWrapper = msoBusinessLogic
318                 .deleteSvcInstance(requestDetails, serviceInstanceId, status);
319
320         // then
321         assertThat(msoResponseWrapper).isEqualToComparingFieldByField(expectedResponse);
322     }
323
324     @Test(dataProvider = "deleteSvcInstanceShouldUnassign")
325     public void shouldProperlyDeleteSvcInstanceWithProperParametersShouldUnassign(String status) {
326         // given
327         String endpointTemplate = "/serviceInstantiation/v7/serviceInstances/%s/unassign";
328         String serviceInstanceId = "3f93c7cb-2fd0-4557-9514-e189b7b04f9d";
329         String svcEndpoint = String.format(endpointTemplate, serviceInstanceId);
330         RequestDetails requestDetails = new RequestDetails();
331         MsoResponseWrapper expectedResponse = createOkResponse();
332         given(msoInterface.unassignSvcInstance(requestDetails, svcEndpoint)).willReturn(expectedResponse);
333
334         // when
335         MsoResponseWrapper msoResponseWrapper = msoBusinessLogic
336                 .deleteSvcInstance(requestDetails, serviceInstanceId, status);
337
338         // then
339         assertThat(msoResponseWrapper).isEqualToComparingFieldByField(expectedResponse);
340     }
341
342     @Test
343     public void shouldProperlyDeleteVnfWithProperParameters() {
344         // when
345         String endpointTemplate = "/serviceInstantiation/v7/serviceInstances/%s/vnfs/%s";
346         String serviceInstanceId = "3f93c7cb-2fd0-4557-9514-e189b7b04f9d";
347         String vnfInstanceId = "testVnfInstanceTempId";
348         String vnfEndpoint = String.format(endpointTemplate, serviceInstanceId, vnfInstanceId);
349         RequestDetails requestDetails = new RequestDetails();
350         MsoResponseWrapper expectedResponse = createOkResponse();
351         given(msoInterface.deleteVnf(requestDetails, vnfEndpoint)).willReturn(expectedResponse);
352
353         // when
354         MsoResponseWrapper msoResponseWrapper = msoBusinessLogic
355                 .deleteVnf(requestDetails, serviceInstanceId, vnfInstanceId);
356
357         // then
358         assertThat(msoResponseWrapper).isEqualToComparingFieldByField(expectedResponse);
359     }
360
361     @Test
362     public void shouldProperlyDeleteVfModuleWithProperParameters() {
363         // when
364         String endpointTemplate = "/serviceInstantiation/v7/serviceInstances/%s/vnfs/%s/vfModules/%s";
365         String serviceInstanceId = "3f93c7cb-2fd0-4557-9514-e189b7b04f9d";
366         String vnfInstanceId = "testVnfInstanceTempId";
367         String vfModuleId = "testVfModuleId";
368         String vnfEndpoint = String.format(endpointTemplate, serviceInstanceId, vnfInstanceId, vfModuleId);
369         RequestDetails requestDetails = new RequestDetails();
370         MsoResponseWrapper expectedResponse = createOkResponse();
371         given(msoInterface.deleteVfModule(requestDetails, vnfEndpoint)).willReturn(expectedResponse);
372
373         // when
374         MsoResponseWrapper msoResponseWrapper = msoBusinessLogic
375                 .deleteVfModule(requestDetails, serviceInstanceId, vnfInstanceId, vfModuleId);
376         // then
377         assertThat(msoResponseWrapper).isEqualToComparingFieldByField(expectedResponse);
378     }
379
380     @Test
381     public void shouldProperlyDeleteVolumeGroupInstanceWithProperParameters() {
382         MsoResponseWrapper expectedResponse = createOkResponse();
383         String serviceInstanceId = "testServiceInstanceTempId";
384         String vnfInstanceId = "testVnfInstanceTempId";
385         String volumeGroupId = "testvolumeGroupIdTempId";
386
387         String deleteVolumeGroupEndpoint = getDeleteVolumeGroupEndpoint(serviceInstanceId, vnfInstanceId, volumeGroupId);
388
389         given(msoInterface.deleteVolumeGroupInstance(msoRequest, deleteVolumeGroupEndpoint)).willReturn(expectedResponse);
390
391         MsoResponseWrapper response = msoBusinessLogic.deleteVolumeGroupInstance(msoRequest, serviceInstanceId, vnfInstanceId, volumeGroupId);
392
393         // then
394         assertThat(response).isEqualToComparingFieldByField(expectedResponse);
395     }
396
397     @NotNull
398     private String getDeleteVolumeGroupEndpoint(String serviceInstanceId, String vnfInstanceId, String volumeGroupId) {
399         String endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VOLUME_GROUP_INSTANCE);
400         String svc_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId);
401         String vnfEndpoint = svc_endpoint.replaceFirst(VNF_INSTANCE_ID, vnfInstanceId);
402         return vnfEndpoint + "/" + volumeGroupId;
403     }
404
405     @Test
406     public void shouldProperlyDeleteNwInstanceWithProperParameters() {
407         MsoResponseWrapper expectedResponse = createOkResponse();
408         String serviceInstanceId = "testServiceInstanceTempId";
409         String networkInstanceId = "testNetworkInstanceTempId";
410
411         String endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_NETWORK_INSTANCE);
412         String svc_endpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId);
413         String delete_nw_endpoint = svc_endpoint + "/" + networkInstanceId;
414
415         given(msoInterface.deleteNwInstance(msoRequest, delete_nw_endpoint)).willReturn(expectedResponse);
416
417         MsoResponseWrapper response = msoBusinessLogic.deleteNwInstance(msoRequest, serviceInstanceId, networkInstanceId);
418
419         // then
420         assertThat(response).isEqualToComparingFieldByField(expectedResponse);
421     }
422
423     @Test
424     public void shouldProperlyGetOrchestrationRequestWithProperParameters() {
425         MsoResponseWrapper expectedResponse = createOkResponse();
426         String requestId = "testRequestTempId";
427         String p = SystemProperties.getProperty(MsoProperties.MSO_REST_API_GET_ORC_REQ);
428         String path = p + "/" + requestId;
429
430         given(msoInterface.getOrchestrationRequest(path)).willReturn(expectedResponse);
431
432         MsoResponseWrapper response = msoBusinessLogic.getOrchestrationRequest(requestId);
433         assertThat(response).isEqualToComparingFieldByField(expectedResponse);
434     }
435
436     @Test(expectedExceptions = MsoTestException.class)
437     public void shouldProperlyGetOrchestrationRequestWithWrongParameters() {
438         String requestId = "testWrongRequestTempId";
439         String p = SystemProperties.getProperty(MsoProperties.MSO_REST_API_GET_ORC_REQ);
440         String path = p + "/" + requestId;
441
442         given(msoInterface.getOrchestrationRequest(path)).willThrow(new MsoTestException("testException"));
443
444         msoBusinessLogic.getOrchestrationRequest(requestId);
445     }
446
447     @Test
448     public void shouldProperlyGetOrchestrationRequestsWithProperParameters() {
449         MsoResponseWrapper expectedResponse = createOkResponse();
450         String filterString = "testRequestsTempId";
451         String url = SystemProperties.getProperty(MsoProperties.MSO_REST_API_GET_ORC_REQS);
452         String path = url + filterString;
453
454         given(msoInterface.getOrchestrationRequest(path)).willReturn(expectedResponse);
455
456         MsoResponseWrapper response = msoBusinessLogic.getOrchestrationRequests(filterString);
457         assertThat(response).isEqualToComparingFieldByField(expectedResponse);
458     }
459
460     @Test(expectedExceptions = MsoTestException.class)
461     public void shouldThrowExceptionWhenGetOrchestrationRequestsWithWrongParameters() {
462         String filterString = "testRequestsTempId";
463         String p = SystemProperties.getProperty(MsoProperties.MSO_REST_API_GET_ORC_REQS);
464         String path = p + filterString;
465
466         given(msoInterface.getOrchestrationRequest(path)).willThrow(new MsoTestException("testException"));
467
468         msoBusinessLogic.getOrchestrationRequests(filterString);
469     }
470
471     @Test
472     public void shouldSendProperScaleOutRequest() throws IOException {
473         // given
474         String serviceInstanceId = "3f93c7cb-2fd0-4557-9514-e189b7b04f9d";
475         String vnfInstanceId = "testVnfInstanceTempId";
476         String endpointTemplate = "/serviceInstantiation/v7/serviceInstances/%s/vnfs/%s/vfModules/scaleOut";
477         String vnfEndpoint = String.format(endpointTemplate, serviceInstanceId, vnfInstanceId);
478         org.onap.vid.changeManagement.RequestDetails requestDetails = readRequest();
479         org.onap.vid.changeManagement.RequestDetailsWrapper<org.onap.vid.changeManagement.RequestDetails> expectedRequest = readExpectedRequest();
480         MsoResponseWrapper expectedMsoResponseWrapper = createOkResponse();
481         given(
482                 msoInterface
483                         .scaleOutVFModuleInstance(argThat(new MsoRequestWrapperMatcher(expectedRequest)),
484                                 eq(vnfEndpoint)))
485                 .willReturn(expectedMsoResponseWrapper);
486
487         // when
488         MsoResponseWrapper msoResponseWrapper = msoBusinessLogic
489                 .scaleOutVfModuleInstance(requestDetails, serviceInstanceId, vnfInstanceId);
490
491         // then
492         assertThat(msoResponseWrapper).isEqualToComparingFieldByField(expectedMsoResponseWrapper);
493     }
494
495     private org.onap.vid.changeManagement.RequestDetails readRequest() throws IOException {
496         Path path = Paths.get("payload_jsons", "scaleOutVfModulePayload.json");
497         URL url = this.getClass().getClassLoader().getResource(path.toString());
498         return objectMapper.readValue(url, org.onap.vid.changeManagement.RequestDetails.class);
499     }
500
501     private org.onap.vid.changeManagement.RequestDetailsWrapper<org.onap.vid.changeManagement.RequestDetails> readExpectedRequest()
502             throws IOException {
503         Path path = Paths.get("payload_jsons", "scaleOutVfModulePayloadToMso.json");
504         URL url = this.getClass().getClassLoader().getResource(path.toString());
505         return objectMapper.readValue(url,
506                 new TypeReference<org.onap.vid.changeManagement.RequestDetailsWrapper<org.onap.vid.changeManagement.RequestDetails>>() {
507                 });
508     }
509
510
511     @Test
512     public void shouldFilterOutOrchestrationRequestsNotAllowedInDashboard() throws Exception {
513         //given
514         String vnfModelTypeOrchestrationRequests = getFileContentAsString("mso_model_info_sample_response.json");
515         String scaleOutActionOrchestrationRequests = getFileContentAsString("mso_action_scaleout_sample_response.json");
516
517         HttpResponse<String> httpResponse = mockForGetOrchestrationRequest();
518         given(httpResponse.getBody())
519                 .willReturn(vnfModelTypeOrchestrationRequests, scaleOutActionOrchestrationRequests);
520
521         //when
522         List<Request> filteredOrchestrationReqs = msoBusinessLogic.getOrchestrationRequestsForDashboard();
523         //then
524         assertThat(filteredOrchestrationReqs).hasSize(3);
525         assertThat(MsoBusinessLogicImpl.DASHBOARD_ALLOWED_TYPES)
526                 .containsAll(filteredOrchestrationReqs
527                         .stream()
528                         .map(el -> el.getRequestType().toUpperCase())
529                         .collect(Collectors.toList()));
530         assertThat(filteredOrchestrationReqs)
531                 .extracting(Request::getRequestScope)
532                 .containsOnly("vnf", "vfModule");
533     }
534
535     @Test(expectedExceptions = GenericUncheckedException.class)
536     public void shouldThrowGenericUncheckedExceptionWhenGetOrchestrationRequestsForDashboardWithWrongJsonFile_() throws Exception {
537         //given
538         String vnfModelTypeOrchestrationRequests = getFileContentAsString("mso_model_info_sample_wrong_response.json");
539
540         mockForGetOrchestrationRequest(200, vnfModelTypeOrchestrationRequests);
541
542         //when
543         msoBusinessLogic.getOrchestrationRequestsForDashboard();
544     }
545
546     @Test
547     public void shouldProperlyGetManualTasksByRequestIdWithProperParameters() throws Exception {
548         //given
549         String manualTasksList = getFileContentAsString("manual_tasks_by_requestId_test.json");
550
551         MsoResponseWrapper msoResponseWrapperMock = mock(MsoResponseWrapper.class);
552         given(msoInterface
553                 .getManualTasksByRequestId(any(String.class), any(String.class), any(String.class),
554                         any(RestObject.class)))
555                 .willReturn(msoResponseWrapperMock);
556         given(msoResponseWrapperMock.getEntity())
557                 .willReturn(manualTasksList);
558
559         //when
560         List<Task> filteredOrchestrationReqs = msoBusinessLogic.getManualTasksByRequestId("TestId");
561
562         //then
563         assertThat(filteredOrchestrationReqs).hasSize(2);
564         assertThat(filteredOrchestrationReqs).extracting("taskId", "type").
565                 contains(
566                         tuple("123123abc", "testTask"),
567                         tuple("321321abc", "testTask")
568                 );
569     }
570
571     @Test(expectedExceptions = GenericUncheckedException.class)
572     public void shouldThrowGenericUncheckedExceptionWhenGetManualTasksByRequestIdWithWrongJsonFile() throws Exception {
573         //given
574         String manualTasksList = getFileContentAsString("manual_tasks_by_requestId_wrongJson_test.json");
575
576         MsoResponseWrapper msoResponseWrapperMock = mock(MsoResponseWrapper.class);
577         given(msoInterface
578                 .getManualTasksByRequestId(any(String.class), any(String.class), any(String.class),
579                         any(RestObject.class)))
580                 .willReturn(msoResponseWrapperMock);
581         given(msoResponseWrapperMock.getEntity())
582                 .willReturn(manualTasksList);
583
584         //when
585         msoBusinessLogic.getManualTasksByRequestId("TestId");
586     }
587
588     @Test(expectedExceptions = MsoTestException.class)
589     public void getManualTasksByRequestIdWithArgument_shouldThrowException() {
590         //given
591         given(msoInterface
592                 .getManualTasksByRequestId(any(String.class), any(String.class), any(String.class),
593                         any(RestObject.class)))
594                 .willThrow(MsoTestException.class);
595
596         //when
597         msoBusinessLogic.getManualTasksByRequestId("TestId");
598     }
599
600     @Test
601     public void shouldProperlyCompleteManualTaskWithProperParameters() {
602         //given
603         MsoResponseWrapper expectedResponse = createOkResponse();
604         RequestDetails requestDetails = new RequestDetails();
605         String taskId = "testTaskId";
606
607         String url = SystemProperties.getProperty(MsoProperties.MSO_REST_API_GET_MAN_TASKS);
608         String path = url + "/" + taskId + "/complete";
609
610         given(msoInterface.completeManualTask(eq(requestDetails), any(String.class), any(String.class), eq(path), any(RestObject.class))).willReturn(expectedResponse);
611
612         //when
613         MsoResponseWrapper response = msoBusinessLogic.completeManualTask(requestDetails, taskId);
614
615         //then
616         assertThat(response).isEqualToComparingFieldByField(expectedResponse);
617
618     }
619
620     @Test
621     public void shouldProperlyActivateServiceInstanceWithProperParameters() {
622         //given
623         RequestDetails detail = new RequestDetails();
624         String taskId = "testTaskId";
625
626         RestObject<String> restObjStr = new RestObject<>();
627         restObjStr.set("");
628         MsoResponseWrapper expectedResponse = MsoUtil.wrapResponse(restObjStr);
629
630         //when
631         MsoResponseWrapper response = msoBusinessLogic.activateServiceInstance(detail, taskId);
632
633         //then
634         assertThat(response).isEqualToComparingFieldByField(expectedResponse);
635
636     }
637
638     @Test(expectedExceptions = MsoTestException.class)
639     public void shouldThrowExceptionWhenManualTaskWithWrongParameters() {
640         //given
641         RequestDetails requestDetails = new RequestDetails();
642         String taskId = "";
643
644         String url = SystemProperties.getProperty(MsoProperties.MSO_REST_API_GET_MAN_TASKS);
645         String path = url + "/" + taskId + "/complete";
646
647         given(msoInterface.completeManualTask(eq(requestDetails), any(String.class), any(String.class), eq(path), any(RestObject.class))).willThrow(new MsoTestException("empty path"));
648
649         //when
650         msoBusinessLogic.completeManualTask(requestDetails, taskId);
651     }
652
653     @Test
654     public void shouldProperlyUpdateVnfWithProperParameters() {
655         //given
656         MsoResponseWrapper expectedResponse = createOkResponse();
657         org.onap.vid.changeManagement.RequestDetails requestDetails = new org.onap.vid.changeManagement.RequestDetails();
658
659         String serviceInstanceId = "testServiceId";
660         String vnfInstanceId = "testVnfInstanceId";
661
662         String endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VNF_INSTANCE);
663         String vnfEndpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId);
664         vnfEndpoint = vnfEndpoint + '/' + vnfInstanceId;
665
666         given(msoInterface.updateVnf(requestDetails, vnfEndpoint)).willReturn(expectedResponse);
667
668         //when
669         MsoResponseWrapper response = (MsoResponseWrapper) msoBusinessLogic.updateVnf(requestDetails, serviceInstanceId, vnfInstanceId);
670
671         //then
672         assertThat(response).isEqualToComparingFieldByField(expectedResponse);
673     }
674
675     @Test
676     public void shouldProperlyReplaceVnfWithProperParameters() {
677         //given
678         MsoResponseWrapper expectedResponse = createOkResponse();
679         org.onap.vid.changeManagement.RequestDetails requestDetails = new org.onap.vid.changeManagement.RequestDetails();
680
681         String serviceInstanceId = "testServiceId";
682         String vnfInstanceId = "testVnfInstanceId";
683
684         String endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_VNF_CHANGE_MANAGEMENT_INSTANCE);
685         String vnfEndpoint = endpoint.replaceFirst(SVC_INSTANCE_ID, serviceInstanceId);
686         vnfEndpoint = vnfEndpoint.replace(VNF_INSTANCE_ID, vnfInstanceId);
687         vnfEndpoint = vnfEndpoint.replace(REQUEST_TYPE, ChangeManagementRequest.MsoChangeManagementRequest.REPLACE);
688
689         given(msoInterface.replaceVnf(requestDetails, vnfEndpoint)).willReturn(expectedResponse);
690
691         //when
692         MsoResponseWrapper response = (MsoResponseWrapper) msoBusinessLogic.replaceVnf(requestDetails, serviceInstanceId, vnfInstanceId);
693
694         //then
695         assertThat(response).isEqualToComparingFieldByField(expectedResponse);
696     }
697
698     @Test
699     public void shouldProperlyGenerateInPlaceMsoRequestWithProperParameters() {
700         //given
701         org.onap.vid.changeManagement.RequestDetails requestDetails = new org.onap.vid.changeManagement.RequestDetails();
702
703         requestDetails.setVnfInstanceId("testVnfInstanceId");
704         requestDetails.setVnfName("testVnfName");
705         requestDetails.setRequestParameters(new RequestParameters());
706
707         requestDetails.getRequestParameters().setAdditionalProperty("payload", "{" +
708                 "\"existing_software_version\": \"testExistingSoftwareParam\"," +
709                 "\"new_software_version\": \"testNewSoftwareParam\"," +
710                 "\"operations_timeout\": \"100\"" +
711                 "}");
712
713         RequestDetails inPlaceSoftwareUpdateRequest = new RequestDetails();
714         inPlaceSoftwareUpdateRequest.setCloudConfiguration(requestDetails.getCloudConfiguration());
715         inPlaceSoftwareUpdateRequest.setRequestParameters(requestDetails.getRequestParameters());
716         inPlaceSoftwareUpdateRequest.setRequestInfo(requestDetails.getRequestInfo());
717         org.onap.vid.changeManagement.RequestDetailsWrapper requestDetailsWrapper = new org.onap.vid.changeManagement.RequestDetailsWrapper();
718         requestDetailsWrapper.requestDetails = inPlaceSoftwareUpdateRequest;
719
720         //when
721         org.onap.vid.changeManagement.RequestDetailsWrapper response = msoBusinessLogic.generateInPlaceMsoRequest(requestDetails);
722
723         //then
724         assertThat(response).isEqualToComparingFieldByField(requestDetailsWrapper);
725     }
726
727     @Test(expectedExceptions = BadRequestException.class)
728     public void shouldThrowExceptionWhenGenerateInPlaceMsoRequestWithParametersWithWrongCharacters() {
729         //given
730         org.onap.vid.changeManagement.RequestDetails requestDetails = new org.onap.vid.changeManagement.RequestDetails();
731
732         requestDetails.setVnfInstanceId("testVnfInstanceId");
733         requestDetails.setVnfName("testVnfName");
734         requestDetails.setRequestParameters(new RequestParameters());
735
736         requestDetails.getRequestParameters().setAdditionalProperty("payload", "{" +
737                 "\"existing_software_version\": \"#####\"," +
738                 "\"new_software_version\": \"testNewSoftwareParam\"" +
739                 "}");
740
741         //when
742         msoBusinessLogic.generateInPlaceMsoRequest(requestDetails);
743     }
744
745     @Test(expectedExceptions = BadRequestException.class)
746     public void shouldThrowExceptionWhenGenerateInPlaceMsoRequestWithWrongParameters() {
747         //given
748         org.onap.vid.changeManagement.RequestDetails requestDetails = new org.onap.vid.changeManagement.RequestDetails();
749
750         requestDetails.setVnfInstanceId("testVnfInstanceId");
751         requestDetails.setVnfName("testVnfName");
752         requestDetails.setRequestParameters(new RequestParameters());
753
754         requestDetails.getRequestParameters().setAdditionalProperty("payload", "{" +
755                 "\"test-wrong-parameter\": \"testParam\"," +
756                 "\"new_software_version\": \"testNewSoftwareParam\"" +
757                 "}");
758
759         //when
760         msoBusinessLogic.generateInPlaceMsoRequest(requestDetails);
761     }
762
763     @Test
764     public void shouldProprleyGenerateConfigMsoRequestWithProperParameters() {
765         //given
766         org.onap.vid.changeManagement.RequestDetails requestDetails = new org.onap.vid.changeManagement.RequestDetails();
767
768         requestDetails.setVnfInstanceId("testVnfInstanceId");
769         requestDetails.setVnfName("testVnfName");
770         requestDetails.setRequestParameters(new RequestParameters());
771
772         requestDetails.getRequestParameters().setAdditionalProperty("payload", "{" +
773                 "\"request-parameters\": \"testRequestParam\"," +
774                 "\"configuration-parameters\": \"testConfigParams\"" +
775                 "}");
776
777         RequestDetails configUpdateRequest = new RequestDetails();
778         configUpdateRequest.setRequestParameters(requestDetails.getRequestParameters());
779         configUpdateRequest.setRequestInfo(requestDetails.getRequestInfo());
780
781         org.onap.vid.changeManagement.RequestDetailsWrapper requestDetailsWrapper = new org.onap.vid.changeManagement.RequestDetailsWrapper();
782         requestDetailsWrapper.requestDetails = configUpdateRequest;
783
784         //when
785         org.onap.vid.changeManagement.RequestDetailsWrapper response = msoBusinessLogic.generateConfigMsoRequest(requestDetails);
786
787         //then
788         assertThat(response).isEqualToComparingFieldByField(requestDetailsWrapper);
789     }
790
791     @Test(expectedExceptions = BadRequestException.class)
792     public void shouldThrowExceptionGenerateConfigMsoRequestWithoutAdditionalParameters() {
793         //given
794         org.onap.vid.changeManagement.RequestDetails requestDetails = new org.onap.vid.changeManagement.RequestDetails();
795
796         requestDetails.setVnfInstanceId("testVnfInstanceId");
797         requestDetails.setVnfName("testVnfName");
798         requestDetails.setRequestParameters(null);
799
800         //when
801         msoBusinessLogic.generateConfigMsoRequest(requestDetails);
802     }
803
804     @Test(expectedExceptions = BadRequestException.class)
805     public void shouldThrowExceptionWhenGenerateConfigMsoRequestWithWrongPayload() {
806         //given
807         org.onap.vid.changeManagement.RequestDetails requestDetails = new org.onap.vid.changeManagement.RequestDetails();
808
809         requestDetails.setVnfInstanceId("testVnfInstanceId");
810         requestDetails.setVnfName("testVnfName");
811         requestDetails.setRequestParameters(new RequestParameters());
812
813         requestDetails.getRequestParameters().setAdditionalProperty("payload", null);
814
815         //when
816         msoBusinessLogic.generateConfigMsoRequest(requestDetails);
817     }
818
819     @Test(expectedExceptions = BadRequestException.class)
820     public void shouldThrowExceptionGenerateConfigMsoRequestWithoutAnyParameter() {
821         //given
822         org.onap.vid.changeManagement.RequestDetails requestDetails = new org.onap.vid.changeManagement.RequestDetails();
823
824         requestDetails.setVnfInstanceId("testVnfInstanceId");
825         requestDetails.setVnfName("testVnfName");
826         requestDetails.setRequestParameters(new RequestParameters());
827
828         requestDetails.getRequestParameters().setAdditionalProperty("payload", "{" +
829                 "\"test-wrong-parameter\": \"testParam\"," +
830                 "\"configuration-parameters\": \"testConfigParam\"" +
831                 "}");
832
833         //when
834         msoBusinessLogic.generateConfigMsoRequest(requestDetails);
835     }
836
837     @Test
838     public void shouldProperlyGetActivateFabricConfigurationPathWithProperParameters() {
839         // given
840         String serviceInstanceId = "testServiceId";
841         String path = validateEndpointPath(MsoProperties.MSO_RESTAPI_SERVICE_INSTANCE);
842         path += "/" + serviceInstanceId + "/activateFabricConfiguration";
843
844         // when
845         String response = msoBusinessLogic.getActivateFabricConfigurationPath(serviceInstanceId);
846
847         // then
848         assertThat(response).isEqualTo(path);
849     }
850
851     @Test
852     public void shouldProperlyGetDeactivateAndCloudDeletePathWithProperParameters() {
853
854         // when
855         String response = msoBusinessLogic.getDeactivateAndCloudDeletePath("testServiceId", "testVnfInstanceId", "testVfModuleInstanceId");
856
857         // then
858         String expectedPath = "/serviceInstantiation/v7/serviceInstances/testServiceId/vnfs/testVnfInstanceId/"+
859             "vfModules/testVfModuleInstanceId/deactivateAndCloudDelete";
860         assertThat(response).isEqualTo(expectedPath);
861     }
862
863     @Test
864     public void shouldProperlyBuildRequestDetailsForSoftDeleteWithProperParameters() throws IOException {
865         SoftDeleteRequest request = new SoftDeleteRequest("testTenantId", "testCloudId", "testUserID");
866         String expected = IOUtils.toString(this.getClass().getResource("/payload_jsons/vfModuleDeactivateAndCloudDelete.json"), "UTF-8");
867         final RequestDetails result = msoBusinessLogic.buildRequestDetailsForSoftDelete(request);
868         MatcherAssert.assertThat(result, jsonEquals(expected));
869     }
870
871     private void setRequestParametersForRequestDetails(RequestDetails requestDetails) {
872         RequestParameters requestParameters = new RequestParameters();
873         requestParameters.setTestApi("GR_API");
874         requestDetails.setRequestParameters(requestParameters);
875     }
876
877     private void setModelInfoForRequestDetails(RequestDetails requestDetails) {
878         ModelInfo modelInfo = new ModelInfo();
879         modelInfo.setModelType("vfModule");
880         requestDetails.setModelInfo(modelInfo);
881     }
882
883     @Test
884     public void shouldProperlyUpdateVnfSoftwareWithProperParameters() {
885         //  given
886         String serviceInstanceId = "testServiceId";
887         String vnfInstanceId = "testVnfInstanceId";
888
889         org.onap.vid.changeManagement.RequestDetails requestDetails = new org.onap.vid.changeManagement.RequestDetails();
890
891         requestDetails.setVnfInstanceId("testVnfInstanceId");
892         requestDetails.setVnfName("testVnfName");
893         requestDetails.setRequestParameters(new RequestParameters());
894
895         requestDetails.getRequestParameters().setAdditionalProperty("payload", "{" +
896                 "\"existing_software_version\": \"testExistingSoftwareParam\"," +
897                 "\"new_software_version\": \"testNewSoftwareParam\"," +
898                 "\"operations_timeout\": \"100\"" +
899                 "}");
900
901         MsoResponseWrapper okResponse = createOkResponse();
902
903         given(msoInterface.changeManagementUpdate(isA(org.onap.vid.changeManagement.RequestDetailsWrapper.class), any(String.class))).willReturn(okResponse);
904
905         //  when
906         MsoResponseWrapper response = (MsoResponseWrapper) msoBusinessLogic.updateVnfSoftware(requestDetails, serviceInstanceId, vnfInstanceId);
907
908         //  then
909         assertThat(response).isEqualToComparingFieldByField(okResponse);
910     }
911
912     @Test
913     public void shouldProperlyUpdateVnfConfigWithProperParameters() {
914         //  given
915         String serviceInstanceId = "testServiceId";
916         String vnfInstanceId = "testVnfInstanceId";
917
918         org.onap.vid.changeManagement.RequestDetails requestDetails = new org.onap.vid.changeManagement.RequestDetails();
919
920         requestDetails.setVnfInstanceId("testVnfInstanceId");
921         requestDetails.setVnfName("testVnfName");
922         requestDetails.setRequestParameters(new RequestParameters());
923
924         requestDetails.getRequestParameters().setAdditionalProperty("payload", "{" +
925                 "\"request-parameters\": \"testRequestParam\"," +
926                 "\"configuration-parameters\": \"testConfigParams\"" +
927                 "}");
928
929         MsoResponseWrapper okResponse = createOkResponse();
930
931         given(msoInterface.changeManagementUpdate(isA(org.onap.vid.changeManagement.RequestDetailsWrapper.class), any(String.class))).willReturn(okResponse);
932
933         //  when
934         MsoResponseWrapper response = (MsoResponseWrapper) msoBusinessLogic.updateVnfConfig(requestDetails, serviceInstanceId, vnfInstanceId);
935
936         //  then
937         assertThat(response).isEqualToComparingFieldByField(okResponse);
938     }
939
940     @Test
941     public void shouldProperlyDeleteConfigurationWithProperParameters() {
942         //  given
943         String serviceInstanceId = "testServiceId";
944         String configurationId = "testConfigurationId";
945
946         org.onap.vid.changeManagement.RequestDetails requestDetails = new org.onap.vid.changeManagement.RequestDetails();
947
948         requestDetails.setVnfInstanceId("testVnfInstanceId");
949         requestDetails.setVnfName("testVnfName");
950
951         MsoResponseWrapper okResponse = createOkResponse();
952         RequestDetailsWrapper wrappedRequestDetail = new RequestDetailsWrapper(requestDetails);
953
954         given(msoInterface.deleteConfiguration(eq(wrappedRequestDetail), any(String.class))).willReturn(okResponse);
955
956         //  when
957         MsoResponseWrapper response = msoBusinessLogic.deleteConfiguration(wrappedRequestDetail, serviceInstanceId, configurationId);
958
959         //  then
960         assertThat(response).isEqualToComparingFieldByField(okResponse);
961     }
962
963     @Test
964     public void shouldProperlySetConfigurationActiveStatusActiveWithProperParameters() {
965         //  given
966         String serviceInstanceId = "testServiceId";
967         String configurationId = "testConfigurationId";
968
969         org.onap.vid.changeManagement.RequestDetails requestDetails = new org.onap.vid.changeManagement.RequestDetails();
970
971         requestDetails.setVnfInstanceId("testVnfInstanceId");
972         requestDetails.setVnfName("testVnfName");
973
974         MsoResponseWrapper okResponse = createOkResponse();
975
976         String endpoint =
977                 validateEndpointPath(MsoProperties.MSO_REST_API_CONFIGURATION_INSTANCE)
978                         .replace(SVC_INSTANCE_ID, serviceInstanceId)
979                         .replace(CONFIGURATION_ID, configurationId)
980                         + "/activate";
981
982         given(msoInterface.setConfigurationActiveStatus(eq(requestDetails), eq(endpoint))).willReturn(okResponse);
983
984         //  when
985         MsoResponseWrapper response = msoBusinessLogic.setConfigurationActiveStatus(requestDetails, serviceInstanceId, configurationId, true);
986
987         //  then
988         assertThat(response).isEqualToComparingFieldByField(okResponse);
989     }
990
991     @Test
992     public void shouldProperlySetConfigurationActiveStatusDeactivateWithProperParameters() {
993         //  given
994         String serviceInstanceId = "testServiceId";
995         String configurationId = "testConfigurationId";
996
997         org.onap.vid.changeManagement.RequestDetails requestDetails = new org.onap.vid.changeManagement.RequestDetails();
998
999         requestDetails.setVnfInstanceId("testVnfInstanceId");
1000         requestDetails.setVnfName("testVnfName");
1001
1002         MsoResponseWrapper okResponse = createOkResponse();
1003
1004         String endpoint =
1005                 validateEndpointPath(MsoProperties.MSO_REST_API_CONFIGURATION_INSTANCE)
1006                         .replace(SVC_INSTANCE_ID, serviceInstanceId)
1007                         .replace(CONFIGURATION_ID, configurationId)
1008                         + "/deactivate";
1009
1010         given(msoInterface.setConfigurationActiveStatus(eq(requestDetails), eq(endpoint))).willReturn(okResponse);
1011
1012         //  when
1013         MsoResponseWrapper response = msoBusinessLogic.setConfigurationActiveStatus(requestDetails, serviceInstanceId, configurationId, false);
1014
1015         //  then
1016         assertThat(response).isEqualToComparingFieldByField(okResponse);
1017     }
1018
1019     @Test
1020     public void shouldProperlySetServiceInstanceStatusActiveWithProperParameters() {
1021         //  given
1022         String serviceInstanceId = "testServiceId";
1023         MsoResponseWrapper okResponse = createOkResponse();
1024
1025         org.onap.vid.changeManagement.RequestDetails requestDetails = new org.onap.vid.changeManagement.RequestDetails();
1026
1027         given(msoInterface.setServiceInstanceStatus(eq(requestDetails), endsWith(serviceInstanceId + "/activate"))).willReturn(okResponse);
1028
1029         //  when
1030         MsoResponseWrapper response = msoBusinessLogic.setServiceInstanceStatus(requestDetails, serviceInstanceId, true);
1031
1032         //  then
1033         assertThat(response).isEqualToComparingFieldByField(okResponse);
1034     }
1035
1036     @Test
1037     public void shouldProperlySetServiceInstanceStatusDeactivateWithProperParameters() {
1038         //  given
1039         String serviceInstanceId = "testServiceId";
1040         MsoResponseWrapper okResponse = createOkResponse();
1041
1042         org.onap.vid.changeManagement.RequestDetails requestDetails = new org.onap.vid.changeManagement.RequestDetails();
1043
1044         given(msoInterface.setServiceInstanceStatus(eq(requestDetails), endsWith(serviceInstanceId + "/deactivate"))).willReturn(okResponse);
1045
1046         //  when
1047         MsoResponseWrapper response = msoBusinessLogic.setServiceInstanceStatus(requestDetails, serviceInstanceId, false);
1048
1049         //  then
1050         assertThat(response).isEqualToComparingFieldByField(okResponse);
1051     }
1052
1053     @Test(expectedExceptions = MsoTestException.class)
1054     public void shouldThrowExceptionWhenSetServiceInstanceStatusWithWrongParameters() {
1055         //  given
1056         String serviceInstanceId = "testServiceId";
1057
1058         doThrow(new MsoTestException("testException")).
1059                 when(msoInterface).setServiceInstanceStatus(eq(null), any(String.class));
1060
1061         //  when
1062         msoBusinessLogic.setServiceInstanceStatus(null, serviceInstanceId, true);
1063     }
1064
1065     @Test
1066     public void shouldProperlySetPortOnConfigurationStatusEnableWithProperParameters() {
1067         //  given
1068         String serviceInstanceId = "testServiceId";
1069         String configurationId = "testConfigurationId";
1070         org.onap.vid.changeManagement.RequestDetails requestDetails = new org.onap.vid.changeManagement.RequestDetails();
1071         requestDetails.setVnfInstanceId("testVnfInstanceId");
1072         requestDetails.setVnfName("testVnfName");
1073         MsoResponseWrapper okResponse = createOkResponse();
1074
1075         String endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_CONFIGURATION_INSTANCE)
1076                 .replace(SVC_INSTANCE_ID, serviceInstanceId)
1077                 .replace(CONFIGURATION_ID, configurationId)
1078                 + "/enablePort";
1079
1080         given(msoInterface.setPortOnConfigurationStatus(eq(requestDetails), eq(endpoint))).willReturn(okResponse);
1081
1082         //  when
1083         MsoResponseWrapper response = msoBusinessLogic.setPortOnConfigurationStatus(requestDetails, serviceInstanceId, configurationId, true);
1084
1085         //  then
1086         assertThat(response).isEqualToComparingFieldByField(okResponse);
1087     }
1088
1089     @Test
1090     public void shouldProperlySetPortOnConfigurationStatusDisableWithProperParameters() {
1091         //  given
1092         String serviceInstanceId = "testServiceId";
1093         String configurationId = "testConfigurationId";
1094         org.onap.vid.changeManagement.RequestDetails requestDetails = new org.onap.vid.changeManagement.RequestDetails();
1095         requestDetails.setVnfInstanceId("testVnfInstanceId");
1096         requestDetails.setVnfName("testVnfName");
1097         MsoResponseWrapper okResponse = createOkResponse();
1098
1099         String endpoint = validateEndpointPath(MsoProperties.MSO_REST_API_CONFIGURATION_INSTANCE)
1100                 .replace(SVC_INSTANCE_ID, serviceInstanceId)
1101                 .replace(CONFIGURATION_ID, configurationId)
1102                 + "/disablePort";
1103
1104         given(msoInterface.setPortOnConfigurationStatus(eq(requestDetails), eq(endpoint))).willReturn(okResponse);
1105
1106         //  when
1107         MsoResponseWrapper response = msoBusinessLogic.setPortOnConfigurationStatus(requestDetails, serviceInstanceId, configurationId, false);
1108
1109         //  then
1110         assertThat(response).isEqualToComparingFieldByField(okResponse);
1111     }
1112
1113     @Test
1114     public void shouldProperlyCreateOperationalEnvironmentActivationRequestDetailsWithProperParameters() {
1115         //  given
1116         OperationalEnvironmentActivateInfo details = createTestOperationalEnvironmentActivateInfo();
1117         //  when
1118         org.onap.vid.changeManagement.RequestDetailsWrapper<RequestDetails> requestDetails = msoBusinessLogic.createOperationalEnvironmentActivationRequestDetails(details);
1119
1120         //  then
1121         assertThat(requestDetails.requestDetails.getRequestParameters().getAdditionalProperties().values()).contains(details.getWorkloadContext(), details.getManifest());
1122         assertThat(requestDetails.requestDetails.getRequestInfo().getRequestorId()).isEqualTo(userId);
1123     }
1124
1125     @Test
1126     public void shouldProperlyGetOperationalEnvironmentActivationPathWithProperParameters() {
1127         // given
1128         OperationalEnvironmentActivateInfo details = createTestOperationalEnvironmentActivateInfo();
1129
1130         // when
1131         String response = msoBusinessLogic.getOperationalEnvironmentActivationPath(details);
1132
1133         // then
1134         assertThat(response).contains(operationalEnvironmentId);
1135     }
1136
1137     @Test
1138     public void shouldProperlyCreateOperationalEnvironmentDeactivationRequestDetailsWithProperParameters() {
1139         // given
1140         OperationalEnvironmentDeactivateInfo details = createTestOperationalEnvironmentDeactivateInfo();
1141
1142         // when
1143         org.onap.vid.changeManagement.RequestDetailsWrapper<RequestDetails> response;
1144         response = msoBusinessLogic.createOperationalEnvironmentDeactivationRequestDetails(details);
1145
1146         // then
1147         assertThat(response.requestDetails.getRequestInfo().getRequestorId()).isEqualTo(userId);
1148     }
1149
1150     @Test
1151     public void shouldProperlyGetCloudResourcesRequestsStatusPathWithProperParameters() {
1152         // given
1153         String requestId = "testRequestId";
1154
1155         // when
1156         String response = msoBusinessLogic.getCloudResourcesRequestsStatusPath(requestId);
1157
1158         // then
1159         assertThat(response).contains(requestId);
1160     }
1161
1162     @Test
1163     public void shouldProperlyGetOperationalEnvironmentDeactivationPathWithProperParameters() {
1164         // given
1165         OperationalEnvironmentDeactivateInfo details = createTestOperationalEnvironmentDeactivateInfo();
1166
1167         // when
1168         String response = msoBusinessLogic.getOperationalEnvironmentDeactivationPath(details);
1169
1170         // then
1171         assertThat(response).contains(operationalEnvironmentId);
1172     }
1173
1174     @Test
1175     public void shouldProperlyGetOperationalEnvironmentCreationPathWithProperParameters() {
1176         // when
1177         String response = msoBusinessLogic.getOperationalEnvironmentCreationPath();
1178
1179         // then
1180         assertThat(response).isNotBlank();
1181     }
1182
1183     @Test
1184     public void shouldProperlyConvertParametersToRequestDetailsWithProperParameters() {
1185         // given
1186         OperationalEnvironmentController.OperationalEnvironmentCreateBody input = createTestOperationalEnvironmentCreateBody();
1187
1188         // when
1189         org.onap.vid.changeManagement.RequestDetailsWrapper<OperationEnvironmentRequestDetails> response
1190                 = msoBusinessLogic.convertParametersToRequestDetails(input, userId);
1191
1192         // then
1193         assertThat(response.requestDetails.getRequestInfo().getInstanceName()).isEqualTo(input.getInstanceName());
1194         assertThat(response.requestDetails.getRequestInfo().getRequestorId()).isEqualTo(userId);
1195         assertThat(response.requestDetails.getRequestParameters().getOperationalEnvironmentType()).isEqualTo(input.getOperationalEnvironmentType());
1196         assertThat(response.requestDetails.getRequestParameters().getTenantContext()).isEqualTo(input.getTenantContext());
1197         assertThat(response.requestDetails.getRequestParameters().getWorkloadContext()).isEqualTo(input.getWorkloadContext());
1198     }
1199
1200     @Test
1201     public void shouldProperlyRemoveRelationshipFromServiceInstanceWithProperParameters() {
1202         // given
1203         MsoResponseWrapper expectedResponse = createOkResponse();
1204         String serviceInstanceId = "testServiceId";
1205         org.onap.vid.changeManagement.RequestDetails requestDetails = new org.onap.vid.changeManagement.RequestDetails();
1206
1207         given(msoInterface.removeRelationshipFromServiceInstance(eq(requestDetails), endsWith("/" + serviceInstanceId + "/removeRelationships")))
1208                 .willReturn(expectedResponse);
1209
1210         // when
1211         MsoResponseWrapper response = msoBusinessLogic.removeRelationshipFromServiceInstance(requestDetails, serviceInstanceId);
1212
1213         // then
1214         assertThat(response).isEqualToComparingFieldByField(expectedResponse);
1215     }
1216
1217     @Test
1218     public void shouldProperlyAddRelationshipToServiceInstanceWithProperParameters() {
1219         // given
1220         MsoResponseWrapper expectedResponse = createOkResponse();
1221         String serviceInstanceId = "testServiceId";
1222         org.onap.vid.changeManagement.RequestDetails requestDetails = new org.onap.vid.changeManagement.RequestDetails();
1223
1224         given(msoInterface.addRelationshipToServiceInstance(eq(requestDetails), endsWith("/" + serviceInstanceId + "/addRelationships")))
1225                 .willReturn(expectedResponse);
1226
1227         // when
1228         MsoResponseWrapper response = msoBusinessLogic.addRelationshipToServiceInstance(requestDetails, serviceInstanceId);
1229
1230         // then
1231         assertThat(response).isEqualToComparingFieldByField(expectedResponse);
1232     }
1233
1234     @Test
1235     public void shouldProperlyRequestTypeFromValueWithValidParameters() {
1236         // given
1237         String testValue = "createInstance";
1238         // when
1239         MsoBusinessLogicImpl.RequestType response = MsoBusinessLogicImpl.RequestType.fromValue(testValue);
1240
1241         // then
1242         assertThat(response.toString()).isEqualTo(testValue);
1243     }
1244
1245     @Test(expectedExceptions = IllegalArgumentException.class)
1246     public void shouldThrowExceptionWhenRequestTypeFromValueWithWrongParameter() {
1247         // given
1248         String testValue = "notExistingParameter";
1249         // when
1250         MsoBusinessLogicImpl.RequestType.fromValue(testValue);
1251     }
1252
1253     @Test
1254     public void shouldProperlyInvokeVnfWorkflowWithValidParameters() {
1255         // given
1256         MsoResponseWrapper okResponse = createOkResponse();
1257         WorkflowRequestDetail request = createWorkflowRequestDetail();
1258         UUID serviceInstanceId = new UUID(1,10);
1259         UUID vnfInstanceId = new UUID(2,20);
1260         UUID workflow_UUID = new UUID(3,30);
1261         String path = "/instanceManagement/v1/serviceInstances/"+serviceInstanceId+"/vnfs/"+vnfInstanceId+"/workflows/"+workflow_UUID;
1262
1263         given(msoInterface.invokeWorkflow(eq(request), eq(path), MockitoHamcrest.argThat(allOf(hasEntry("X-RequestorID", "testRequester"),hasEntry("X-ONAP-PartnerName", "VID.VID"))))).willReturn(okResponse);
1264
1265         // when
1266         MsoResponseWrapper response = msoBusinessLogic.invokeVnfWorkflow(request, "testRequester", serviceInstanceId, vnfInstanceId, workflow_UUID);
1267
1268         // then
1269         assertThat(response).isEqualToComparingFieldByField(okResponse);
1270     }
1271
1272
1273     @Test
1274     public void shouldReturnWorkflowListForGivenModelId() {
1275         given(msoInterface.getWorkflowListByModelId(anyString())).willReturn(workflowListResponse);
1276         given(workflowListResponse.getBody()).willReturn(workflowList);
1277         given(workflowListResponse.getStatus()).willReturn(HttpStatus.ACCEPTED.value());
1278
1279         SOWorkflowList workflows = msoBusinessLogic.getWorkflowListByModelId("sampleModelId");
1280
1281         assertThat(workflows).isEqualTo(workflowList);
1282     }
1283
1284     @Test(expectedExceptions = {MsoBusinessLogicImpl.WorkflowListException.class})
1285     public void shouldRaiseExceptionWhenRetrievingWorkflowsFailed() {
1286         given(msoInterface.getWorkflowListByModelId(anyString())).willReturn(workflowListResponse);
1287         given(workflowListResponse.getStatus()).willReturn(HttpStatus.INTERNAL_SERVER_ERROR.value());
1288
1289         msoBusinessLogic.getWorkflowListByModelId("sampleModelId");
1290     }
1291
1292
1293     @Test
1294     public void probeShouldReturnOrchestrationRequestsAndConnectionStatus(){
1295         String body =
1296                 "{"
1297                 + "  \"requestList\":"
1298                 + "  [{"
1299                 + "      \"request\": {}"
1300                 + "    }"
1301                 + "  ]"
1302                 + "}";
1303         mockForGetOrchestrationRequest(200, body);
1304
1305         ExternalComponentStatus externalComponentStatus = msoBusinessLogic.probeComponent();
1306
1307         assertThat(externalComponentStatus.isAvailable()).isTrue();
1308         assertThat(externalComponentStatus.getComponent()).isEqualTo(ExternalComponentStatus.Component.MSO);
1309     }
1310
1311     private WorkflowRequestDetail createWorkflowRequestDetail() {
1312         WorkflowRequestDetail workflowRequestDetail = new WorkflowRequestDetail();
1313         org.onap.vid.changeManagement.RequestParameters requestParameters = new org.onap.vid.changeManagement.RequestParameters();
1314         HashMap<String,String> paramsMap = new HashMap<>();
1315         paramsMap.put("testKey1","testValue1");
1316         paramsMap.put("testKey2","testValue2");
1317
1318         List<Map<String,String>> mapArray= new ArrayList<>();
1319         mapArray.add(paramsMap);
1320         requestParameters.setUserParams(mapArray);
1321
1322         CloudConfiguration cloudConfiguration = new CloudConfiguration();
1323         cloudConfiguration.setCloudOwner("testOwne");
1324         cloudConfiguration.setTenantId("testId");
1325         cloudConfiguration.setLcpCloudRegionId("testLcpCloudId");
1326
1327         workflowRequestDetail.setRequestParameters(requestParameters);
1328         workflowRequestDetail.setCloudConfiguration(cloudConfiguration);
1329         return workflowRequestDetail;
1330     }
1331
1332     private OperationalEnvironmentActivateInfo createTestOperationalEnvironmentActivateInfo() {
1333         OperationalEnvironmentController.OperationalEnvironmentActivateBody operationalEnvironmentActivateBody = new OperationalEnvironmentController.OperationalEnvironmentActivateBody(
1334                 "testRelatedInstanceId",
1335                 "testRelatedInstanceName",
1336                 "testWorkloadContext",
1337                 new OperationalEnvironmentController.OperationalEnvironmentManifest()
1338         );
1339         return new OperationalEnvironmentActivateInfo(operationalEnvironmentActivateBody, userId, operationalEnvironmentId);
1340     }
1341
1342     private OperationalEnvironmentDeactivateInfo createTestOperationalEnvironmentDeactivateInfo() {
1343         return new OperationalEnvironmentDeactivateInfo(userId, operationalEnvironmentId);
1344     }
1345
1346     private OperationalEnvironmentController.OperationalEnvironmentCreateBody createTestOperationalEnvironmentCreateBody() {
1347         return new OperationalEnvironmentController.OperationalEnvironmentCreateBody(
1348                 "testInstanceName",
1349                 "testEcompInstanceId",
1350                 "testEcompInstanceName",
1351                 "testOperationalEnvironmentType",
1352                 "testTenantContext",
1353                 "testWorkloadContext"
1354         );
1355     }
1356
1357     private MsoResponseWrapper createOkResponse() {
1358         HttpStatus expectedStatus = HttpStatus.ACCEPTED;
1359         String expectedBody = " \"body\": {\n" +
1360                 "      \"requestReferences\": {\n" +
1361                 "        \"instanceId\": \" 123456 \",\n" +
1362                 "        \"requestId\": \"b6dc9806-b094-42f7-9386-a48de8218ce8\"\n" +
1363                 "      }";
1364         MsoResponseWrapper responseWrapper = new MsoResponseWrapper();
1365         responseWrapper.setEntity(expectedBody);
1366         responseWrapper.setStatus(expectedStatus.value());
1367         return responseWrapper;
1368     }
1369
1370     private String getFileContentAsString(String resourceName) throws Exception {
1371         Path path = Paths.get("payload_jsons", resourceName);
1372         URL url = this.getClass().getClassLoader().getResource(path.toString());
1373         String result = "";
1374         if (url != null) {
1375             result = IOUtils.toString(url.toURI(), "UTF-8");
1376         }
1377         return result;
1378     }
1379
1380     private static class MsoRequestWrapperMatcher implements
1381             ArgumentMatcher<org.onap.vid.changeManagement.RequestDetailsWrapper> {
1382
1383         private final org.onap.vid.changeManagement.RequestDetailsWrapper expectedRequest;
1384
1385         MsoRequestWrapperMatcher(org.onap.vid.changeManagement.RequestDetailsWrapper expectedRequest) {
1386             this.expectedRequest = expectedRequest;
1387         }
1388
1389         @Override
1390         public boolean matches(org.onap.vid.changeManagement.RequestDetailsWrapper argument) {
1391             return expectedRequest.requestDetails.equals(argument.requestDetails);
1392         }
1393     }
1394
1395     private class MsoTestException extends RuntimeException {
1396         MsoTestException(String testException) {
1397             super(testException);
1398         }
1399     }
1400
1401     //you need to add mocks to httpResponse
1402     private HttpResponse<String> mockForGetOrchestrationRequest() {
1403
1404         HttpResponse<String> httpResponse = mock(HttpResponse.class);
1405         HttpResponseWithRequestInfo<String> httpResponseWithRequestInfo = new HttpResponseWithRequestInfo<>(httpResponse, MY_PRETTY_URL, HttpMethod.GET);
1406         when(msoInterface.getOrchestrationRequest(any(String.class),anyBoolean()))
1407             .thenReturn(httpResponseWithRequestInfo);
1408         return httpResponse;
1409     }
1410
1411     private HttpResponse<String> mockForGetOrchestrationRequest(int statusCode, String body) {
1412
1413         HttpResponse<String> httpResponse = mockForGetOrchestrationRequest();
1414         when(httpResponse.getStatus()).thenReturn(statusCode);
1415         when(httpResponse.getBody()).thenReturn(body);
1416         TestUtils.mockGetRawBodyWithStringBody(httpResponse, body);
1417         return httpResponse;
1418     }
1419
1420     @Test
1421     public void probeComponent_verifyGoodRequest(){
1422         String responseString = "" +
1423             "{ " +
1424             " \"requestList\": [{ " +
1425             "   \"request\": { " +
1426             "    \"requestDetails\": { " +
1427             "     \"cloudConfiguration\": { " +
1428             "      \"lcpCloudRegionId\": \"hvf6\", " +
1429             "      \"cloudOwner\": \"irma-aic\", " +
1430             "      \"tenantId\": \"ffdf52b5e5104b0e8f329b0b1637ee2e\" " +
1431             "     }, " +
1432             "     \"modelInfo\": { " +
1433             "      \"modelCustomizationName\": \"VSP1710PID298109_vWINIFRED 0\", " +
1434             "      \"modelCustomizationId\": \"24d43fdb-9aa6-4287-a68e-1e702ea89d13\", " +
1435             "      \"modelInvariantId\": \"e7961100-cde6-4b5a-bcda-b8945086950a\", " +
1436             "      \"modelVersionId\": \"959a7ba0-89ee-4984-9af6-65d5bdda4b0e\", " +
1437             "      \"modelName\": \"VSP1710PID298109_vWINIFRED\", " +
1438             "      \"modelType\": \"vnf\", " +
1439             "      \"modelVersion\": \"1.0\" " +
1440             "     }, " +
1441             "     \"relatedModelList\": [{ " +
1442             "       \"relatedInstance\": { " +
1443             "        \"instanceId\": \"6dd0f8de-93c7-48a2-914b-1a8d58e0eb48\", " +
1444             "        \"modelInfo\": { " +
1445             "         \"modelInvariantId\": \"57e00952-0af7-4f0f-b19a-408a6f73c8df\", " +
1446             "         \"modelType\": \"service\", " +
1447             "         \"modelName\": \"ServicevWINIFREDPID298109\", " +
1448             "         \"modelVersion\": \"1.0\", " +
1449             "         \"modelVersionId\": \"fe6985cd-ea33-3346-ac12-ab121484a3fe\" " +
1450             "        } " +
1451             "       } " +
1452             "      } " +
1453             "     ], " +
1454             "     \"requestInfo\": { " +
1455             "      \"source\": \"VID\", " +
1456             "      \"suppressRollback\": false, " +
1457             "      \"requestorId\": \"ds828e\" " +
1458             "     }, " +
1459             "     \"requestParameters\": { " +
1460             "      \"userParams\": [ " +
1461             "      ], " +
1462             "      \"aLaCarte\": false, " +
1463             "      \"usePreload\": true, " +
1464             "      \"rebuildVolumeGroups\": false, " +
1465             "      \"autoBuildVfModules\": false, " +
1466             "      \"cascadeDelete\": false " +
1467             "     }, " +
1468             "     \"relatedInstanceList\": [{ " +
1469             "       \"relatedInstance\": { " +
1470             "        \"instanceId\": \"6dd0f8de-93c7-48a2-914b-1a8d58e0eb48\", " +
1471             "        \"modelInfo\": { " +
1472             "         \"modelInvariantId\": \"57e00952-0af7-4f0f-b19a-408a6f73c8df\", " +
1473             "         \"modelType\": \"service\", " +
1474             "         \"modelName\": \"ServicevWINIFREDPID298109\", " +
1475             "         \"modelVersion\": \"1.0\", " +
1476             "         \"modelVersionId\": \"fe6985cd-ea33-3346-ac12-ab121484a3fe\" " +
1477             "        } " +
1478             "       } " +
1479             "      } " +
1480             "     ] " +
1481             "    }, " +
1482             "    \"requestId\": \"d352c70d-5ef8-4977-9ea8-4c8cbe860422\", " +
1483             "    \"requestScope\": \"vnf\", " +
1484             "    \"requestStatus\": { " +
1485             "     \"percentProgress\": 100.0, " +
1486             "     \"requestState\": \"Some Unknown Value\", " +
1487             "     \"statusMessage\": \"Update Is In Progress\", " +
1488             "     \"finishTime\": \"Fri, 08 Sep 2017 19:34:33 GMT\" " +
1489             "    }, " +
1490             "    \"requestType\": \"updateInstance\", " +
1491             "    \"startTime\": \"<IN_PROGRESS_DATE>\", " +
1492             "    \"instanceReferences\": { " +
1493             "     \"serviceInstanceId\": \"6dd0f8de-93c7-48a2-914b-1a8d58e0eb48\", " +
1494             "     \"vnfInstanceId\": \"7c00cc1e-6425-4fc3-afc3-0289db288d4c\", " +
1495             "     \"requestorId\": \"ds828e\" " +
1496             "    } " +
1497             "   } " +
1498             "  } " +
1499             " ] " +
1500             "} ";
1501
1502         mockForGetOrchestrationRequest(200, responseString);
1503
1504         final ExternalComponentStatus msoStatus = msoBusinessLogic.probeComponent();
1505
1506         assertMsoStatus(msoStatus, true);
1507         assertMetadata(msoStatus, 200, startsWith(responseString.substring(0, 400)), MY_PRETTY_URL, equalTo("OK"));
1508     }
1509
1510     @Test
1511     public void probeComponent_response200OkButEmptyPayload_shouldDescribeCorrectly() {
1512         String responseString = "" +
1513             "{ " +
1514             " \"requestList\": []" +
1515             "}";
1516
1517         mockForGetOrchestrationRequest(200, responseString);
1518
1519         final ExternalComponentStatus msoStatus = msoBusinessLogic.probeComponent();
1520
1521         assertMsoStatus(msoStatus, true);
1522
1523         assertMetadata(msoStatus, 200, equalTo(responseString), MY_PRETTY_URL, containsString("OK"));
1524     }
1525
1526     @Test
1527     public void probeComponent_response200OkButInvalidPayload_shouldDescribeCorrectly() {
1528         String responseString = "this payload is an invalid json";
1529
1530         mockForGetOrchestrationRequest(200, responseString);
1531
1532         final ExternalComponentStatus msoStatus = msoBusinessLogic.probeComponent();
1533
1534         assertMsoStatus(msoStatus, false);
1535
1536         assertMetadata(msoStatus, 200, equalTo(responseString), MY_PRETTY_URL, containsString("JsonParseException: Unrecognized token"));
1537     }
1538
1539     @Test
1540     public void probeComponent_verifyResponse406() {
1541         String responseString = "my raw data";
1542
1543         when(msoInterface.getOrchestrationRequest(any(), eq(true))).thenThrow(
1544             new ExceptionWithRequestInfo(HttpMethod.GET, MY_PRETTY_URL, responseString, 406,
1545                 new GenericUncheckedException(
1546                     new HttpException("Simulating as 406 was returned (200 or 202 expected)"))));
1547
1548         final ExternalComponentStatus msoStatus = msoBusinessLogic.probeComponent();
1549
1550         assertMsoStatus(msoStatus, false);
1551
1552         assertMetadata(msoStatus, 406, equalTo(responseString), MY_PRETTY_URL, containsString("HttpException: Simulating as 406 was returned"));
1553     }
1554
1555
1556     @Test
1557     public void probeComponent_throwNullPointerException_resultIsWithErrorMetadata() {
1558         when(msoInterface.getOrchestrationRequest(any(), eq(true))).thenThrow(new NullPointerException());
1559
1560         final ExternalComponentStatus msoStatus = msoBusinessLogic.probeComponent();
1561
1562         MatcherAssert.assertThat(msoStatus.isAvailable(), is(false));
1563         MatcherAssert.assertThat(msoStatus.getComponent(), is(MSO));
1564         MatcherAssert.assertThat(msoStatus.getMetadata(), instanceOf(ErrorMetadata.class));
1565
1566         final ErrorMetadata metadata = ((ErrorMetadata) msoStatus.getMetadata());
1567         org.junit.Assert.assertThat(metadata.getDescription(), containsString("NullPointerException"));
1568     }
1569
1570     private void assertMsoStatus(ExternalComponentStatus msoStatus, boolean isAvailable) {
1571         MatcherAssert.assertThat(msoStatus.isAvailable(), is(isAvailable));
1572         MatcherAssert.assertThat(msoStatus.getComponent(), is(MSO));
1573         MatcherAssert.assertThat(msoStatus.getMetadata(), instanceOf(HttpRequestMetadata.class));
1574     }
1575
1576     private void assertMetadata(ExternalComponentStatus msoStatus, int httpCode, Matcher<String> rawData, String url, Matcher<String> descriptionMatcher) {
1577         final HttpRequestMetadata metadata = ((HttpRequestMetadata) msoStatus.getMetadata());
1578         org.junit.Assert.assertThat(metadata.getHttpMethod(), equalTo(HttpMethod.GET));
1579         org.junit.Assert.assertThat(metadata.getHttpCode(), equalTo(httpCode));
1580         org.junit.Assert.assertThat(metadata.getUrl(), equalTo(url));
1581         org.junit.Assert.assertThat(metadata.getRawData(), rawData);
1582         org.junit.Assert.assertThat(metadata.getDescription(), descriptionMatcher);
1583     }
1584 }
1585