21b8f3f000330b2c0a0b79a30e6cc14a6798df88
[vid.git] / vid-app-common / src / test / java / org / onap / vid / services / AsyncInstantiationBusinessLogicTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
4  * ================================================================================
5  * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.vid.services;
22
23 import static com.google.common.collect.Maps.newHashMap;
24 import static org.hamcrest.MatcherAssert.assertThat;
25 import static org.hamcrest.Matchers.contains;
26 import static org.hamcrest.Matchers.hasItem;
27 import static org.hamcrest.Matchers.hasItems;
28 import static org.hamcrest.Matchers.hasProperty;
29 import static org.hamcrest.Matchers.is;
30 import static org.hamcrest.Matchers.matchesPattern;
31 import static org.hamcrest.Matchers.not;
32 import static org.hamcrest.core.Every.everyItem;
33 import static org.hamcrest.core.IsEqual.equalTo;
34 import static org.mockito.Matchers.any;
35 import static org.mockito.Mockito.anyInt;
36 import static org.mockito.Mockito.anyString;
37 import static org.mockito.Mockito.doNothing;
38 import static org.mockito.Mockito.doThrow;
39 import static org.mockito.Mockito.eq;
40 import static org.mockito.Mockito.mock;
41 import static org.mockito.Mockito.times;
42 import static org.mockito.Mockito.verify;
43 import static org.mockito.Mockito.when;
44 import static org.onap.vid.job.Job.JobStatus.COMPLETED;
45 import static org.onap.vid.job.Job.JobStatus.FAILED;
46 import static org.onap.vid.job.Job.JobStatus.IN_PROGRESS;
47 import static org.onap.vid.job.Job.JobStatus.PAUSE;
48 import static org.onap.vid.job.Job.JobStatus.PENDING;
49 import static org.onap.vid.job.Job.JobStatus.STOPPED;
50 import static org.testng.Assert.assertEquals;
51 import static org.testng.Assert.assertFalse;
52 import static org.testng.Assert.assertNotNull;
53 import static org.testng.Assert.assertNull;
54 import static org.testng.Assert.assertTrue;
55
56 import com.fasterxml.jackson.databind.JsonNode;
57 import com.fasterxml.jackson.databind.ObjectMapper;
58 import com.google.common.collect.ImmutableList;
59 import com.google.common.collect.ImmutableMap;
60 import java.io.IOException;
61 import java.lang.reflect.Method;
62 import java.net.URL;
63 import java.time.Instant;
64 import java.time.LocalDateTime;
65 import java.time.ZoneId;
66 import java.util.ArrayList;
67 import java.util.Arrays;
68 import java.util.Collections;
69 import java.util.Comparator;
70 import java.util.Date;
71 import java.util.HashMap;
72 import java.util.List;
73 import java.util.Map;
74 import java.util.Optional;
75 import java.util.Set;
76 import java.util.UUID;
77 import java.util.concurrent.Callable;
78 import java.util.concurrent.ExecutorService;
79 import java.util.concurrent.Executors;
80 import java.util.stream.Collectors;
81 import java.util.stream.IntStream;
82 import javax.inject.Inject;
83 import net.javacrumbs.jsonunit.JsonAssert;
84 import org.apache.commons.io.IOUtils;
85 import org.hibernate.SessionFactory;
86 import org.json.JSONException;
87 import org.mockito.ArgumentCaptor;
88 import org.mockito.Mock;
89 import org.mockito.Mockito;
90 import org.mockito.MockitoAnnotations;
91 import org.mockito.stubbing.Answer;
92 import org.onap.portalsdk.core.domain.FusionObject;
93 import org.onap.portalsdk.core.service.DataAccessService;
94 import org.onap.portalsdk.core.util.SystemProperties;
95 import org.onap.vid.aai.ExceptionWithRequestInfo;
96 import org.onap.vid.aai.model.ResourceType;
97 import org.onap.vid.changeManagement.RequestDetailsWrapper;
98 import org.onap.vid.config.DataSourceConfig;
99 import org.onap.vid.config.MockedAaiClientAndFeatureManagerConfig;
100 import org.onap.vid.exceptions.GenericUncheckedException;
101 import org.onap.vid.exceptions.MaxRetriesException;
102 import org.onap.vid.exceptions.OperationNotAllowedException;
103 import org.onap.vid.job.Job;
104 import org.onap.vid.job.Job.JobStatus;
105 import org.onap.vid.job.JobAdapter;
106 import org.onap.vid.job.JobType;
107 import org.onap.vid.job.JobsBrokerService;
108 import org.onap.vid.job.impl.JobDaoImpl;
109 import org.onap.vid.job.impl.JobSharedData;
110 import org.onap.vid.model.Action;
111 import org.onap.vid.model.JobAuditStatus;
112 import org.onap.vid.model.JobAuditStatus.SourceStatus;
113 import org.onap.vid.model.NameCounter;
114 import org.onap.vid.model.ServiceInfo;
115 import org.onap.vid.model.serviceInstantiation.InstanceGroup;
116 import org.onap.vid.model.serviceInstantiation.Network;
117 import org.onap.vid.model.serviceInstantiation.ServiceInstantiation;
118 import org.onap.vid.model.serviceInstantiation.VfModule;
119 import org.onap.vid.model.serviceInstantiation.Vnf;
120 import org.onap.vid.mso.MsoOperationalEnvironmentTest;
121 import org.onap.vid.mso.model.InstanceGroupInstantiationRequestDetails;
122 import org.onap.vid.mso.model.ModelInfo;
123 import org.onap.vid.mso.model.NetworkInstantiationRequestDetails;
124 import org.onap.vid.mso.model.ServiceDeletionRequestDetails;
125 import org.onap.vid.mso.model.ServiceInstantiationRequestDetails;
126 import org.onap.vid.mso.model.VfModuleInstantiationRequestDetails;
127 import org.onap.vid.mso.model.VfModuleMacro;
128 import org.onap.vid.mso.model.VnfInstantiationRequestDetails;
129 import org.onap.vid.mso.model.VolumeGroupRequestDetails;
130 import org.onap.vid.mso.rest.AsyncRequestStatus;
131 import org.onap.vid.properties.Features;
132 import org.onap.vid.testUtils.TestUtils;
133 import org.onap.vid.utils.DaoUtils;
134 import org.springframework.beans.factory.annotation.Autowired;
135 import org.springframework.test.context.ContextConfiguration;
136 import org.testng.Assert;
137 import org.testng.annotations.AfterMethod;
138 import org.testng.annotations.BeforeClass;
139 import org.testng.annotations.BeforeMethod;
140 import org.testng.annotations.DataProvider;
141 import org.testng.annotations.Test;
142
143 @ContextConfiguration(classes = {DataSourceConfig.class, SystemProperties.class, MockedAaiClientAndFeatureManagerConfig.class})
144 public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseTest {
145
146     @Inject
147     private DataAccessService dataAccessService;
148
149     @Mock
150     private JobAdapter jobAdapterMock;
151
152     @Mock
153     private JobsBrokerService jobsBrokerServiceMock;
154
155
156     @Autowired
157     private SessionFactory sessionFactory;
158
159     private AsyncInstantiationBusinessLogicImpl asyncInstantiationBL;
160
161     private int serviceCount = 0;
162
163     private static final String UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE =
164             "Failed to retrieve job with uuid .* from ServiceInfo table. Instances found: .*";
165
166     private static final String DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE =
167             "Service status does not allow deletion from the queue";
168
169     @BeforeClass
170     void initServicesInfoService() {
171         MockitoAnnotations.initMocks(this);
172         asyncInstantiationBL = new AsyncInstantiationBusinessLogicImpl(dataAccessService, jobAdapterMock, jobsBrokerServiceMock, sessionFactory, aaiClient, featureManager, cloudOwnerService);
173         createInstanceParamsMaps();
174     }
175
176     @BeforeMethod
177     void defineMocks() {
178         Mockito.reset(aaiClient);
179         Mockito.reset(jobAdapterMock);
180         Mockito.reset(jobsBrokerServiceMock);
181         mockAaiClientAnyNameFree();
182         enableAddCloudOwnerOnMsoRequest();
183     }
184
185     private void enableAddCloudOwnerOnMsoRequest() {
186         enableAddCloudOwnerOnMsoRequest(true);
187     }
188
189     private void enableAddCloudOwnerOnMsoRequest(boolean isActive) {
190         // always turn on the feature flag
191         when(featureManager.isActive(Features.FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST)).thenReturn(isActive);
192         when(aaiClient.getCloudOwnerByCloudRegionId(anyString())).thenReturn("att-aic");
193     }
194
195     @BeforeMethod
196     void resetServiceCount() {
197         serviceCount = 0;
198     }
199
200     @AfterMethod
201     void clearDb() {
202         dataAccessService.deleteDomainObjects(JobDaoImpl.class, "1=1", getPropsMap());
203         dataAccessService.deleteDomainObjects(ServiceInfo.class, "1=1", getPropsMap());
204         dataAccessService.deleteDomainObjects(JobAuditStatus.class, "1=1", getPropsMap());
205         dataAccessService.deleteDomainObjects(NameCounter.class, "1=1", getPropsMap());
206     }
207
208
209     private void createNewTestServicesInfoForFilter(String userId) {
210         LocalDateTime createdDate, modifiedDate;
211         LocalDateTime NOW = LocalDateTime.now();
212         UUID uuid;
213
214         // Old job
215         uuid = UUID.randomUUID();
216         addNewJob(uuid);
217         createdDate = NOW.minusYears(1);
218         addNewServiceInfo(uuid, userId, "Old", createdDate, createdDate, COMPLETED, false);
219
220         uuid = UUID.randomUUID();
221         addNewJob(uuid);
222         createdDate = NOW.minusDays(20);
223         modifiedDate = NOW.minusDays(19);
224         addNewServiceInfo(uuid, userId, "Hidden", createdDate, modifiedDate, PAUSE, true);
225
226         createNewTestServicesInfo(String.valueOf(userId));
227     }
228
229     private void createNewTestServicesInfo(String userId) {
230
231         LocalDateTime createdDate, modifiedDate;
232         LocalDateTime NOW = LocalDateTime.now();
233         UUID uuid;
234
235         uuid = UUID.randomUUID();
236         addNewJob(uuid);
237
238         createdDate = NOW.minusDays(40);
239         addNewServiceInfo(uuid, userId, "service instance 5", createdDate, createdDate, COMPLETED, false);
240         addNewServiceInfo(uuid, userId, "service instance 6", createdDate, createdDate, STOPPED, false);
241
242         uuid = UUID.randomUUID();
243         addNewJob(uuid);
244
245         createdDate = NOW.minusDays(20);
246         modifiedDate = NOW.minusDays(10);
247         addNewServiceInfo(uuid, userId, "service instance 4", createdDate, modifiedDate, STOPPED, false);
248         addNewServiceInfo(uuid, userId, "service instance 2", createdDate, modifiedDate, COMPLETED, false);
249         addNewServiceInfo(uuid, userId, "service instance 3", createdDate, modifiedDate, PAUSE, false);
250
251         modifiedDate = NOW.minusDays(19);
252         addNewServiceInfo(uuid, userId, "service instance 1", createdDate, modifiedDate, FAILED, false);
253
254
255         // Job to a different user
256         uuid = UUID.randomUUID();
257         addNewJob(uuid);
258
259         createdDate = NOW.minusMonths(2);
260         addNewServiceInfo(uuid, "2221", "service instance 7", createdDate, createdDate, COMPLETED, false);
261
262     }
263
264     private UUID createServicesInfoWithDefaultValues(Job.JobStatus status) {
265
266         LocalDateTime NOW = LocalDateTime.now();
267         UUID uuid;
268
269         uuid = UUID.randomUUID();
270         addNewJob(uuid, status);
271
272         addNewServiceInfo(uuid, null, "service instance 1", NOW, NOW, status, false);
273
274         return uuid;
275
276     }
277
278     private List<ServiceInfo> getFullList() {
279         List<ServiceInfo> expectedOrderServiceInfo = dataAccessService.getList(ServiceInfo.class, getPropsMap());
280         assertThat("Failed to retrieve all predefined services", expectedOrderServiceInfo.size(), equalTo(serviceCount));
281         expectedOrderServiceInfo.sort(new ServiceInfoComparator());
282         return expectedOrderServiceInfo;
283     }
284
285     private static Date toDate(LocalDateTime localDateTime) {
286         return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
287     }
288
289     private LocalDateTime fromDate(Date date) {
290         return Instant.ofEpochMilli(date.getTime())
291                 .atZone(ZoneId.systemDefault())
292                 .toLocalDateTime();
293     }
294
295     private void addNewServiceInfo(UUID uuid, String userId, String serviceName, LocalDateTime createDate, LocalDateTime statusModifiedDate, Job.JobStatus status, boolean isHidden) {
296         ServiceInfo serviceInfo = new ServiceInfo();
297         serviceInfo.setJobId(uuid);
298         serviceInfo.setUserId(userId);
299         serviceInfo.setServiceInstanceName(serviceName);
300         serviceInfo.setStatusModifiedDate(toDate(statusModifiedDate));
301         serviceInfo.setJobStatus(status);
302         serviceInfo.setPause(false);
303         serviceInfo.setOwningEntityId("1234");
304         serviceInfo.setCreatedBulkDate(toDate(createDate));
305
306         serviceInfo.setHidden(isHidden);
307         dataAccessService.saveDomainObject(serviceInfo, getPropsMap());
308         setCreateDateToServiceInfo(uuid, createDate);
309         serviceCount++;
310
311     }
312
313     private void setCreateDateToServiceInfo(UUID jobUuid, LocalDateTime createDate) {
314         List<ServiceInfo> serviceInfoList = dataAccessService.getList(ServiceInfo.class, getPropsMap());
315         DaoUtils.tryWithSessionAndTransaction(sessionFactory, session -> {
316             serviceInfoList.stream()
317                     .filter(serviceInfo -> jobUuid.equals(serviceInfo.getJobId()))
318                     .forEach(serviceInfo -> {
319                         serviceInfo.setCreated(toDate(createDate));
320                         session.saveOrUpdate(serviceInfo);
321                     });
322             return 1;
323         });
324     }
325
326     private void addNewJob(UUID uuid) {
327         addNewJob(uuid, null);
328     }
329
330     private void addNewJob(UUID uuid, Job.JobStatus status) {
331         JobDaoImpl jobDao = new JobDaoImpl();
332         jobDao.setUuid(uuid);
333         jobDao.setStatus(status);
334         dataAccessService.saveDomainObject(jobDao, getPropsMap());
335     }
336
337     @Test
338     public void testServiceInfoAreOrderedAsExpected() {
339         int userId = 2222;
340         createNewTestServicesInfo(String.valueOf(userId));
341         List<ServiceInfo> expectedOrderServiceInfo = getFullList();
342         List<ServiceInfo> serviceInfoListResult = asyncInstantiationBL.getAllServicesInfo();
343         assertThat("Services aren't ordered as expected", serviceInfoListResult, equalTo(expectedOrderServiceInfo));
344     }
345
346     @Test
347     public void testServiceInfoAreFilteredAsExpected() {
348         int userId = 2222;
349         createNewTestServicesInfoForFilter(String.valueOf(userId));
350         List<ServiceInfo> expectedOrderServiceInfo = getFullList();
351
352         List<ServiceInfo> expectedFilterByUser = expectedOrderServiceInfo.stream().filter(x ->
353                 !x.getServiceInstanceName().equals("Old") && !x.getServiceInstanceName().equals("Hidden")
354
355         ).collect(Collectors.toList());
356
357
358         List<ServiceInfo> serviceInfoFilteredByUser = asyncInstantiationBL.getAllServicesInfo();
359         assertThat("Services aren't ordered filtered as expected", serviceInfoFilteredByUser, equalTo(expectedFilterByUser));
360     }
361
362     @Test(dataProvider = "pauseAndInstanceParams")
363     public void createMacroServiceInstantiationMsoRequestUniqueName(Boolean isPause, HashMap<String, String> vfModuleInstanceParamsMap, List vnfInstanceParams) throws Exception {
364         defineMocks();
365         ServiceInstantiation serviceInstantiationPayload = generateMockMacroServiceInstantiationPayload(isPause, createVnfList(vfModuleInstanceParamsMap, vnfInstanceParams, true), 2, true, PROJECT_NAME, false);
366         final URL resource = this.getClass().getResource("/payload_jsons/bulk_service_request_unique_names.json");
367         when(jobAdapterMock.createServiceInstantiationJob(any(), any(), any(), any(), anyString(), any())).thenAnswer(invocation -> {
368             Object[] args = invocation.getArguments();
369             return new MockedJob((String)args[4]);
370         });
371
372         when(jobsBrokerServiceMock.add(any(MockedJob.class))).thenAnswer((Answer<UUID>) invocation -> {
373             Object[] args = invocation.getArguments();
374             MockedJob job = (MockedJob) args[0];
375             MockedJob.putJob(job.uuid, job);
376             return job.getUuid();
377         });
378
379         when(featureManager.isActive(Features.FLAG_SHIFT_VFMODULE_PARAMS_TO_VNF)).thenReturn(true);
380
381         List<UUID> uuids = asyncInstantiationBL.pushBulkJob(serviceInstantiationPayload, "az2016");
382         for (int i = 0; i < 2; i++) {
383             UUID currentUuid = uuids.get(i);
384             RequestDetailsWrapper<ServiceInstantiationRequestDetails> result =
385                     asyncInstantiationBL.generateMacroServiceInstantiationRequest(currentUuid, serviceInstantiationPayload,
386                             MockedJob.getJob(currentUuid).getOptimisticUniqueServiceInstanceName(), "az2016");
387             String unique =  i==0 ? "" : String.format("_00%s", i);
388             String expected = IOUtils.toString(resource, "UTF-8")
389                     .replace("{SERVICE_UNIQENESS}", unique)
390                     .replace("{VNF_UNIQENESS}", unique)
391                     .replace("{VF_MODULE_UNIQENESS}", unique)
392                     .replace("{VF_MODULE_2_UNIQENESS}", unique)
393                     .replace("{VG_UNIQUENESS}", unique);
394             MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
395             Optional<ServiceInfo> optionalServiceInfo = getJobById(currentUuid);
396             assertThat(optionalServiceInfo.get().getServiceInstanceName(), equalTo("vPE_Service" + unique));
397             verifySearchNodeTypeByName(unique, "vPE_Service", ResourceType.SERVICE_INSTANCE);
398             verifySearchNodeTypeByName(unique, VNF_NAME, ResourceType.GENERIC_VNF);
399             verifySearchNodeTypeByName(unique, "vmxnjr001_AVPN_base_vPE_BV_base", ResourceType.VF_MODULE);
400             verifySearchNodeTypeByName(unique, "vmxnjr001_AVPN_base_vRE_BV_expansion", ResourceType.VF_MODULE);
401             verifySearchNodeTypeByName(unique, "myVgName", ResourceType.VOLUME_GROUP);
402         }
403     }
404
405     protected void verifySearchNodeTypeByName(String unique, String resourceName, ResourceType serviceInstance) {
406         verify(aaiClient, times(1)).isNodeTypeExistsByName(resourceName + unique, serviceInstance);
407     }
408
409     private HashMap<String, Object> getPropsMap() {
410         HashMap<String, Object> props = new HashMap<>();
411         props.put(FusionObject.Parameters.PARAM_USERID, 0);
412         return props;
413     }
414
415
416     @DataProvider
417     public static Object[][] dataProviderForInstanceNames() {
418         return new Object[][]{
419                 {true, ImmutableList.of("vPE_Service", "vPE_Service_001", "vPE_Service_002")},
420                 {false, ImmutableList.of("", "", "")},
421         };
422     }
423
424     @Test(dataProvider="dataProviderForInstanceNames")
425     public void pushBulkJob_bulkWithSize3_instancesNamesAreExactlyAsExpected(boolean isUserProvidedNaming, List<String> expectedNames) {
426         int bulkSize = 3;
427
428         final ServiceInstantiation request = generateMockMacroServiceInstantiationPayload(
429                 false,
430                 createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true),
431                 bulkSize, isUserProvidedNaming, PROJECT_NAME, true
432         );
433
434         // in "createServiceInstantiationJob()" we will probe the service, with the generated names
435         configureMockitoWithMockedJob();
436
437
438         asyncInstantiationBL.pushBulkJob(request, "myUserId");
439
440         List<ServiceInfo> serviceInfoList = dataAccessService.getList(ServiceInfo.class, getPropsMap());
441         assertEquals(serviceInfoList.stream().map(ServiceInfo::getServiceInstanceName).collect(Collectors.toList()), expectedNames);
442     }
443
444     @Test(dataProvider = "aLaCarteAndMacroPayload")
445     public void generateMockServiceInstantiationPayload_serializeBackAndForth_sourceShouldBeTheSame(ServiceInstantiation serviceInstantiationPayload) throws IOException {
446         ObjectMapper mapper = new ObjectMapper();
447         final String asString = mapper.writeValueAsString(serviceInstantiationPayload);
448
449         final ServiceInstantiation asObject = mapper.readValue(asString, ServiceInstantiation.class);
450         final String asString2 = mapper.writeValueAsString(asObject);
451
452         JsonAssert.assertJsonEquals(asString, asString2);
453     }
454
455     @DataProvider
456     public Object[][] aLaCarteAndMacroPayload() {
457         ServiceInstantiation macroPayload = generateMockMacroServiceInstantiationPayload(
458                 false,
459                 createVnfList(instanceParamsMapWithoutParams, ImmutableList.of(vnfInstanceParamsMapWithParamsToRemove, vnfInstanceParamsMapWithParamsToRemove), true),
460                 2, false,PROJECT_NAME, false);
461         ServiceInstantiation aLaCartePayload = generateALaCarteServiceInstantiationPayload();
462
463         return new Object[][]{
464                 {macroPayload},
465                 {aLaCartePayload}
466         };
467     }
468
469     public static class ServiceInfoComparator implements Comparator<ServiceInfo> {
470
471         @Override
472         public int compare(ServiceInfo o1, ServiceInfo o2) {
473             int compare;
474
475             compare = o1.getCreatedBulkDate().compareTo(o2.getCreatedBulkDate());
476             if (compare != 0) {
477                 return -compare;
478             }
479
480             // check jobStatus priority
481             int o1Priority = getPriority(o1);
482             int o2Priority = getPriority(o2);
483             compare = o1Priority - o2Priority;
484             if (compare != 0) {
485                 return compare;
486             }
487
488             // check statusModifiedDate
489             return o1.getStatusModifiedDate().compareTo(o2.getStatusModifiedDate());
490         }
491
492         private int getPriority(ServiceInfo o) throws JSONException {
493             Job.JobStatus status = o.getJobStatus();
494             switch (status) {
495                 case COMPLETED:
496                 case FAILED:
497                     return 1;
498                 case IN_PROGRESS:
499                     return 2;
500                 case PAUSE:
501                     return 3;
502                 case STOPPED:
503                 case PENDING:
504                     return 4;
505                 default:
506                     return 5;
507             }
508         }
509     }
510
511     @DataProvider
512     public Object[][] pauseAndInstanceParams() {
513         return new Object[][]{
514                 {Boolean.TRUE, instanceParamsMapWithoutParams, Collections.EMPTY_LIST},
515                 {Boolean.FALSE, instanceParamsMapWithoutParams, Collections.EMPTY_LIST},
516                 {Boolean.TRUE, vfModuleInstanceParamsMapWithParamsToRemove, Collections.singletonList(vnfInstanceParamsMapWithParamsToRemove)}
517         };
518     }
519
520     private ServiceInstantiation generateMacroMockServiceInstantiationPayload(boolean isPause, Map<String, Vnf> vnfs) {
521         return generateMockMacroServiceInstantiationPayload(isPause, vnfs, 1, true, PROJECT_NAME, false);
522     }
523
524     @Test
525     public void testUpdateServiceInfo_WithExistingServiceInfo_ServiceInfoIsUpdated() {
526         UUID uuid = createFakedJobAndServiceInfo();
527         final String STEPH_CURRY = "Steph Curry";
528         asyncInstantiationBL.updateServiceInfo(uuid, x -> {
529             x.setServiceInstanceName(STEPH_CURRY);
530             x.setJobStatus(Job.JobStatus.IN_PROGRESS);
531         });
532         Optional<ServiceInfo> optionalServiceInfo = getJobById(uuid);
533         assertThat(optionalServiceInfo.get().getServiceInstanceName(), equalTo(STEPH_CURRY));
534         assertThat(optionalServiceInfo.get().getJobStatus(), equalTo(Job.JobStatus.IN_PROGRESS));
535     }
536
537     private Optional<ServiceInfo> getJobById(UUID jobId) {
538         List<ServiceInfo> serviceInfoList = dataAccessService.getList(ServiceInfo.class, null);
539         return serviceInfoList.stream().filter(x -> jobId.equals(x.getJobId())).findFirst();
540     }
541
542     private UUID createFakedJobAndServiceInfo() {
543         UUID uuid = UUID.randomUUID();
544         addNewJob(uuid);
545         ServiceInfo serviceInfo = new ServiceInfo();
546         serviceInfo.setServiceInstanceName("Lebron James");
547         serviceInfo.setJobId(uuid);
548         serviceInfo.setJobStatus(Job.JobStatus.PENDING);
549         dataAccessService.saveDomainObject(serviceInfo, getPropsMap());
550         return uuid;
551     }
552
553     @Test(expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE)
554     public void testUpdateServiceInfo_WithNonExisting_ThrowException() {
555         asyncInstantiationBL.updateServiceInfo(UUID.randomUUID(), x -> x.setServiceInstanceName("not matter"));
556     }
557
558     @Test(expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE)
559     public void testUpdateServiceInfo_WithDoubleServiceWithSameJobUuid_ThrowException() {
560         UUID uuid = createFakedJobAndServiceInfo();
561         ServiceInfo serviceInfo = new ServiceInfo();
562         serviceInfo.setJobId(uuid);
563         dataAccessService.saveDomainObject(serviceInfo, getPropsMap());
564         asyncInstantiationBL.updateServiceInfo(UUID.randomUUID(), x -> x.setServiceInstanceName("not matter"));
565     }
566
567
568     @DataProvider
569     public static Object[][] isPauseAndPropertyDataProvider() {
570         return new Object[][]{
571                 {true, "mso.restapi.serviceInstanceAssign"},
572                 {false, "mso.restapi.serviceInstanceCreate"},
573         };
574     }
575
576
577     @Test(dataProvider = "isPauseAndPropertyDataProvider")
578     public void testServiceInstantiationPath_RequestPathIsAsExpected(boolean isPause, String expectedProperty) {
579         ServiceInstantiation serviceInstantiationPauseFlagTrue = generateMacroMockServiceInstantiationPayload(isPause, createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true));
580         String path = asyncInstantiationBL.getServiceInstantiationPath(serviceInstantiationPauseFlagTrue);
581         Assert.assertEquals(path, SystemProperties.getProperty(expectedProperty));
582     }
583
584     @Test
585     public void testCreateVnfEndpoint_useProvidedInstanceId() {
586         String path = asyncInstantiationBL.getVnfInstantiationPath("myGreatId");
587         assertThat(path, matchesPattern("/serviceInstances/v./myGreatId/vnfs"));
588     }
589
590     @Test
591     public void createServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected() throws IOException {
592         createMacroServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(true);
593     }
594
595     @Test
596     public void createServiceInfo_WithUserProvidedNamingFalseAndNoVfmodules_ServiceInfoIsAsExpected() throws IOException {
597         createMacroServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(false);
598     }
599
600     private void createMacroServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(boolean withVfmodules) throws IOException {
601         when(featureManager.isActive(Features.FLAG_SHIFT_VFMODULE_PARAMS_TO_VNF)).thenReturn(true);
602
603         ServiceInstantiation serviceInstantiationPayload = generateMockMacroServiceInstantiationPayload(true,
604                 createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, Collections.EMPTY_LIST, false),
605                 1,
606                 false, PROJECT_NAME, true);
607         URL resource;
608         if (withVfmodules) {
609             resource = this.getClass().getResource("/payload_jsons/bulk_service_request_ecomp_naming.json");
610         } else {
611             // remove the vf modules
612             serviceInstantiationPayload.getVnfs().values().forEach(vnf -> vnf.getVfModules().clear());
613             resource = this.getClass().getResource("/payload_jsons/bulk_service_request_no_vfmodule_ecomp_naming.json");
614         }
615
616         RequestDetailsWrapper<ServiceInstantiationRequestDetails> result =
617                 asyncInstantiationBL.generateMacroServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016");
618
619         String expected = IOUtils.toString(resource, "UTF-8");
620         MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
621     }
622
623     @Test
624     public void createALaCarteService_WithUserProvidedNamingFalse_RequestDetailsIsAsExpected() throws IOException {
625         ServiceInstantiation serviceInstantiationPayload = generateMockALaCarteServiceInstantiationPayload(false,
626                 newHashMap(),
627                 newHashMap(),
628                 newHashMap(),
629                 1,
630                 false, PROJECT_NAME, true, null);
631
632         RequestDetailsWrapper<ServiceInstantiationRequestDetails> result =
633                 asyncInstantiationBL.generateALaCarteServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016");
634
635         URL resource = this.getClass().getResource("/payload_jsons/bulk_alacarte_service_request_naming_false.json");
636         String expected = IOUtils.toString(resource, "UTF-8");
637         MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
638     }
639
640     @Test
641     public void generateALaCarteServiceInstantiationRequest_withVnfList_HappyFllow() throws IOException {
642         ServiceInstantiation serviceInstantiationPayload = generateALaCarteWithVnfsServiceInstantiationPayload();
643         RequestDetailsWrapper<ServiceInstantiationRequestDetails> result =
644                 asyncInstantiationBL.generateALaCarteServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016");
645
646         String serviceExpected = IOUtils.toString(this.getClass().getResource("/payload_jsons/bulk_alacarte_service_request.json"), "UTF-8");
647         MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(serviceExpected, result);
648     }
649
650     @Test(dataProvider = "createVnfParameters")
651     public void createVnfRequestDetails_detailsAreAsExpected(boolean isFlagAddCloudOwnerActive, boolean isUserProvidedNaming, String file) throws IOException {
652
653         final List<Vnf> vnfList = new ArrayList<>(createVnfList(new HashMap<>(), null, isUserProvidedNaming, true).values());
654         ModelInfo siModelInfo = createServiceModelInfo();
655         String serviceInstanceId = "aa3514e3-5a33-55df-13ab-12abad84e7aa";
656
657         //we validate that the asyncInstantiationBL call to getUniqueName by simulate that aai retrun that original
658         //vnf name is used, and only next picked name is free.
659         Mockito.reset(aaiClient);
660         mockAaiClientAaiStatusOK();
661         when(aaiClient.isNodeTypeExistsByName(eq(VNF_NAME), eq(ResourceType.GENERIC_VNF))).thenReturn(true);
662         when(aaiClient.isNodeTypeExistsByName(eq(VNF_NAME+"_001"), eq(ResourceType.GENERIC_VNF))).thenReturn(false);
663         enableAddCloudOwnerOnMsoRequest(isFlagAddCloudOwnerActive);
664
665         String expected = IOUtils.toString(this.getClass().getResource(file), "UTF-8");
666         final RequestDetailsWrapper<VnfInstantiationRequestDetails> result = asyncInstantiationBL.generateVnfInstantiationRequest(vnfList.get(0), siModelInfo, serviceInstanceId, "pa0916");
667         MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
668     }
669
670     @DataProvider
671     public static Object[][] createVnfParameters() {
672         return new Object[][]{
673                 {true, true, "/payload_jsons/bulk_vnf_request.json"},
674                 {false, true, "/payload_jsons/bulk_vnf_request_without_cloud_owner.json"},
675                 {true, false, "/payload_jsons/bulk_vnf_request_without_instance_name.json"},
676         };
677     }
678
679     @DataProvider
680     public static Object[][] vfModuleRequestDetails(Method test) {
681         return new Object[][]{
682                 {"cc3514e3-5a33-55df-13ab-12abad84e7cc", true, "/payload_jsons/vfmodule_instantiation_request.json"},
683                 {null, true, "/payload_jsons/vfmodule_instantiation_request_without_volume_group.json"},
684                 {null, false, "/payload_jsons/vfmodule_instantiation_request_without_instance_name.json"}
685         };
686     }
687
688     @Test(dataProvider = "vfModuleRequestDetails")
689     public void createVfModuleRequestDetails_detailsAreAsExpected(String volumeGroupInstanceId, boolean isUserProvidedNaming, String fileName) throws IOException {
690
691         ModelInfo siModelInfo = createServiceModelInfo();
692         ModelInfo vnfModelInfo = createVnfModelInfo(true);
693         List<Map<String, String>> instanceParams = ImmutableList.of(ImmutableMap.of("vmx_int_net_len", "24",
694                 "vre_a_volume_size_0" , "120"));
695         Map<String, String> supplementaryParams = ImmutableMap.of("vre_a_volume_size_0" , "100",
696                 "availability_zone_0" , "mtpocdv-kvm-az01");
697         VfModule vfModule = createVfModule("201673MowAvpnVpeBvL..AVPN_vRE_BV..module-1", "56e2b103-637c-4d1a-adc8-3a7f4a6c3240",
698                 "72d9d1cd-f46d-447a-abdb-451d6fb05fa8", instanceParams, supplementaryParams,
699                 (isUserProvidedNaming ? "vmxnjr001_AVPN_base_vRE_BV_expansion": null), "myVgName", true);
700
701         String serviceInstanceId = "aa3514e3-5a33-55df-13ab-12abad84e7aa";
702         String vnfInstanceId = "bb3514e3-5a33-55df-13ab-12abad84e7bb";
703
704         Mockito.reset(aaiClient);
705         mockAaiClientAaiStatusOK();
706         enableAddCloudOwnerOnMsoRequest();
707         when(aaiClient.isNodeTypeExistsByName(eq("vmxnjr001_AVPN_base_vRE_BV_expansion"), eq(ResourceType.VF_MODULE))).thenReturn(false);
708
709         String expected = IOUtils.toString(this.getClass().getResource(fileName), "UTF-8");
710         final RequestDetailsWrapper<VfModuleInstantiationRequestDetails> result = asyncInstantiationBL.generateVfModuleInstantiationRequest(
711                 vfModule, siModelInfo, serviceInstanceId,
712                 vnfModelInfo, vnfInstanceId, volumeGroupInstanceId, "pa0916");
713         MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
714     }
715
716     @DataProvider
717     public static Object[][] expectedAggregatedParams() {
718         return new Object[][]{
719                 {ImmutableMap.of("a", "b", "c", "d"), ImmutableMap.of("e", "f", "g", "h"), ImmutableList.of(ImmutableMap.of("c", "d", "a", "b", "e", "f", "g", "h"))},
720                 {ImmutableMap.of("a", "b", "c", "g"), ImmutableMap.of("c", "d", "e", "f"), ImmutableList.of(ImmutableMap.of("a", "b", "c", "d", "e", "f"))},
721                 {ImmutableMap.of(), ImmutableMap.of("c", "d", "e", "f"), ImmutableList.of(ImmutableMap.of("c", "d", "e", "f"))},
722                 {ImmutableMap.of("a", "b", "c", "g"), ImmutableMap.of(), ImmutableList.of(ImmutableMap.of("a", "b", "c", "g"))},
723                 {ImmutableMap.of(), ImmutableMap.of(), ImmutableList.of()},
724                 {null, ImmutableMap.of(), ImmutableList.of()},
725                 {ImmutableMap.of(), null, ImmutableList.of()},
726         };
727     }
728
729     @Test(dataProvider = "expectedAggregatedParams")
730     public void testAggregateInstanceParamsAndSuppFile(Map<String, String> instanceParams, Map<String, String> suppParams, List<VfModuleInstantiationRequestDetails.UserParamMap<String, String>> expected) {
731         List<VfModuleInstantiationRequestDetails.UserParamMap<String, String>> aggParams = ((AsyncInstantiationBusinessLogicImpl)asyncInstantiationBL).aggregateAllInstanceParams(instanceParams, suppParams);
732         assertThat("Aggregated params are not as expected", aggParams, equalTo(expected));
733     }
734
735     @DataProvider
736     public static Object[][] expectedNetworkRequestDetailsParameters() {
737         return new Object[][]{
738             {true, "/payload_jsons/network_instantiation_request.json"},
739             {false, "/payload_jsons/network_instantiation_request_without_instance_name.json"}
740         };
741     }
742
743     @Test(dataProvider = "expectedNetworkRequestDetailsParameters")
744     public void createNetworkRequestDetails_detailsAreAsExpected(boolean isUserProvidedNaming, String filePath) throws IOException {
745
746         final List<Network> networksList = new ArrayList<>(createNetworkList(null, isUserProvidedNaming, true).values());
747         ModelInfo siModelInfo = createServiceModelInfo();
748         String serviceInstanceId = "aa3514e3-5a33-55df-13ab-12abad84e7aa";
749
750         Mockito.reset(aaiClient);
751         mockAaiClientAaiStatusOK();
752         enableAddCloudOwnerOnMsoRequest();
753         when(aaiClient.isNodeTypeExistsByName(eq(VNF_NAME), eq(ResourceType.L3_NETWORK))).thenReturn(true);
754         when(aaiClient.isNodeTypeExistsByName(eq(VNF_NAME+"_001"), eq(ResourceType.L3_NETWORK))).thenReturn(false);
755
756         String expected = IOUtils.toString(this.getClass().getResource(filePath), "UTF-8");
757         final RequestDetailsWrapper<NetworkInstantiationRequestDetails> result = asyncInstantiationBL.generateNetworkInstantiationRequest(networksList.get(0), siModelInfo, serviceInstanceId, "pa0916");
758         MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
759     }
760
761     @Test
762     public void createInstanceGroupRequestDetails_detailsAreAsExpected() throws IOException {
763
764         final InstanceGroup instanceGroup = createInstanceGroup(true, Action.Create);
765         ModelInfo siModelInfo = createServiceModelInfo();
766         String serviceInstanceId = "aa3514e3-5a33-55df-13ab-12abad84e7aa";
767
768         Mockito.reset(aaiClient);
769         mockAaiClientAaiStatusOK();
770         enableAddCloudOwnerOnMsoRequest();
771         when(aaiClient.isNodeTypeExistsByName(eq(VNF_GROUP_NAME), eq(ResourceType.INSTANCE_GROUP))).thenReturn(true);
772         when(aaiClient.isNodeTypeExistsByName(eq(VNF_GROUP_NAME+"_001"), eq(ResourceType.INSTANCE_GROUP))).thenReturn(false);
773
774         String expected = IOUtils.toString(this.getClass().getResource("/payload_jsons/instance_group_instantiation_request.json"), "UTF-8");
775         final RequestDetailsWrapper<InstanceGroupInstantiationRequestDetails> result = asyncInstantiationBL.generateInstanceGroupInstantiationRequest(instanceGroup, siModelInfo, serviceInstanceId, "az2018");
776         MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
777     }
778
779     @Test
780     public void checkIfNullProjectNameSentToMso(){
781         ServiceInstantiation serviceInstantiationPayload = generateMockMacroServiceInstantiationPayload(true,
782                 createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, Collections.EMPTY_LIST, false),
783                 1,
784                 false,null,false);
785         RequestDetailsWrapper<ServiceInstantiationRequestDetails> result =
786                 asyncInstantiationBL.generateMacroServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016");
787         JsonNode jsonNode = new ObjectMapper().valueToTree(result.requestDetails);
788         Assert.assertTrue(jsonNode.get("project").isNull());
789         serviceInstantiationPayload = generateMockMacroServiceInstantiationPayload(true,
790                 createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, Collections.EMPTY_LIST, false),
791                 1,
792                 false,"not null",false);
793         result = asyncInstantiationBL.generateMacroServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016");
794         jsonNode = new ObjectMapper().valueToTree(result.requestDetails);
795         Assert.assertTrue(jsonNode.get("project").get("projectName").asText().equalsIgnoreCase("not null"));
796
797
798
799     }
800
801     @Test
802     public void pushBulkJob_macroServiceverifyCreatedDateBehavior_createdDateIsTheSameForAllServicesInSameBulk() {
803         LocalDateTime startTestDate = LocalDateTime.now().withNano(0);
804         final ServiceInstantiation request = generateMockMacroServiceInstantiationPayload(
805                 false,
806                 createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true),
807                 100, true,PROJECT_NAME, true
808         );
809
810         pushJobAndAssertDates(startTestDate, request);
811     }
812
813     @Test
814     public void whenCreateServiceInfo_thenModelId_isModelVersionId() {
815         ServiceInfo serviceInfo = asyncInstantiationBL.createServiceInfo("userID",
816                 generateALaCarteWithVnfsServiceInstantiationPayload(),
817                 UUID.randomUUID(),
818                 UUID.randomUUID(),
819                 new Date(),
820                 "myName", ServiceInfo.ServiceAction.INSTANTIATE);
821         assertEquals(SERVICE_MODEL_VERSION_ID, serviceInfo.getServiceModelId());
822
823     }
824
825     @Test
826     public void pushBulkJob_aLaCarteServiceverifyCreatedDateBehavior_createdDateIsTheSameForAllServicesInSameBulk() {
827         LocalDateTime startTestDate = LocalDateTime.now().withNano(0);
828         final ServiceInstantiation request = generateALaCarteServiceInstantiationPayload();
829         pushJobAndAssertDates(startTestDate, request);
830     }
831
832     protected void pushJobAndAssertDates(LocalDateTime startTestDate, ServiceInstantiation request) {
833         // in "createServiceInstantiationJob()" we will probe the service, with the generated names
834         configureMockitoWithMockedJob();
835
836         asyncInstantiationBL.pushBulkJob(request, "myUserId");
837         List<ServiceInfo> serviceInfoList = dataAccessService.getList(ServiceInfo.class, getPropsMap());
838
839         List<Date> creationDates = new ArrayList<>();
840         for (ServiceInfo serviceInfo : serviceInfoList) {
841             creationDates.add(serviceInfo.getCreatedBulkDate());
842         }
843         LocalDateTime endTestDate = LocalDateTime.now();
844
845         //creation date of all services is the same
846         Assert.assertTrue(creationDates.stream().distinct().count() <= 1);
847         LocalDateTime creationDate = fromDate(creationDates.get(0));
848         assertFalse(creationDate.isBefore(startTestDate));
849         assertFalse(creationDate.isAfter(endTestDate));
850     }
851
852     protected void configureMockitoWithMockedJob() {
853         Mockito.reset(jobAdapterMock);
854         final Job job = mock(Job.class);
855         when(job.getStatus()).thenReturn(PENDING);
856         when(jobAdapterMock.createServiceInstantiationJob(any(), any(), any(), any(), any(), any())).thenReturn(job);
857     }
858
859     @DataProvider
860     public static Object[][] msoToJobStatusDataProvider() {
861         return new Object[][]{
862                 {"IN_PROGRESS", JobStatus.IN_PROGRESS},
863                 {"INPROGRESS", JobStatus.IN_PROGRESS},
864                 {"IN ProGREsS", JobStatus.IN_PROGRESS},
865                 {"JAMES_HARDEN", JobStatus.IN_PROGRESS},
866                 {"FAILED", JobStatus.FAILED},
867                 {"COMpleTE", JobStatus.COMPLETED},
868                 {"PENDING", JobStatus.IN_PROGRESS},
869                 {"Paused", JobStatus.PAUSE},
870                 {"Pause", JobStatus.PAUSE},
871                 {"PENDING_MANUAL_TASK", JobStatus.PAUSE},
872                 {"UNLOCKED", JobStatus.IN_PROGRESS}
873         };
874     }
875
876     @Test(dataProvider = "msoToJobStatusDataProvider")
877     public void whenGetStatusFromMso_calcRightJobStatus(String msoStatus, Job.JobStatus expectedJobStatus) {
878         AsyncRequestStatus asyncRequestStatus = asyncRequestStatusResponse(msoStatus);
879         assertThat(asyncInstantiationBL.calcStatus(asyncRequestStatus), equalTo(expectedJobStatus));
880     }
881
882     private void createNewAuditStatus(JobAuditStatus auditStatus)
883     {
884         Date createdDate= auditStatus.getCreated();
885         dataAccessService.saveDomainObject(auditStatus, getPropsMap());
886         setDateToStatus(auditStatus.getSource(), auditStatus.getJobStatus(), createdDate);
887     }
888
889
890
891     private static final String MSO_ARBITRARY_STATUS = "completed mso status";
892
893     @DataProvider
894     public static Object[][] auditStatuses(Method test) {
895         return new Object[][]{
896                 {
897                         SourceStatus.VID,
898                         new String[]{ JobStatus.PENDING.toString(), JobStatus.IN_PROGRESS.toString()}
899                 },
900                 {       SourceStatus.MSO,
901                         new String[]{ JobStatus.IN_PROGRESS.toString(), MSO_ARBITRARY_STATUS }
902                 }
903         };
904
905     }
906
907     private void setDateToStatus(SourceStatus source, String status, Date date) {
908         List<JobAuditStatus> jobAuditStatusList = dataAccessService.getList(JobAuditStatus.class, getPropsMap());
909         DaoUtils.tryWithSessionAndTransaction(sessionFactory, session -> {
910             jobAuditStatusList.stream()
911                     .filter(auditStatus -> source.equals(auditStatus.getSource()) && status.equals(auditStatus.getJobStatus()))
912                     .forEach(auditStatus -> {
913                         auditStatus.setCreated(date);
914                         session.saveOrUpdate(auditStatus);
915                     });
916             return 1;
917         });
918     }
919
920
921     @Test(dataProvider = "auditStatuses")
922     public void givenSomeAuditStatuses_getStatusesOfSpecificSourceAndJobId_getSortedResultsMatchingToParameters(SourceStatus expectedSource, String [] expectedSortedStatuses){
923         UUID jobUuid = UUID.randomUUID();
924         List<JobAuditStatus> auditStatusList = com.google.common.collect.ImmutableList.of(
925                 new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.VID, toDate(LocalDateTime.now().minusHours(2))),
926                 new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, UUID.randomUUID(),"",toDate(LocalDateTime.now().minusHours(30))),
927                 new JobAuditStatus(jobUuid, MSO_ARBITRARY_STATUS, SourceStatus.MSO, UUID.randomUUID(),"",toDate(LocalDateTime.now().minusHours(3))),
928                 new JobAuditStatus(jobUuid, PENDING.toString(), SourceStatus.VID, toDate(LocalDateTime.now().minusHours(3))),
929                 new JobAuditStatus(UUID.randomUUID(), PENDING.toString(), SourceStatus.VID, toDate(LocalDateTime.now().minusHours(3))));
930         auditStatusList.forEach((auditStatus) -> createNewAuditStatus(auditStatus));
931         List<JobAuditStatus> statuses = asyncInstantiationBL.getAuditStatuses(jobUuid, expectedSource);
932         List<String> statusesList = statuses.stream().map(status -> status.getJobStatus()).collect(Collectors.toList());
933         Assert.assertTrue(statuses.stream().allMatch(status -> (status.getSource().equals(expectedSource)&& status.getJobId().equals(jobUuid))),"Only statuses of " + expectedSource + " for " + jobUuid + " should be returned. Returned statuses: " + String.join(",", statusesList ));
934         assertThat(statusesList, contains(expectedSortedStatuses));
935     }
936
937
938
939     @Test
940     public void addSomeVidStatuses_getThem_verifyGetInsertedWithoutDuplicates(){
941         ImmutableList<JobStatus> statusesToBeInserted = ImmutableList.of(PENDING, IN_PROGRESS, IN_PROGRESS, COMPLETED);
942         UUID jobUuid = UUID.randomUUID();
943         statusesToBeInserted.forEach(status->
944             {
945                 asyncInstantiationBL.auditVidStatus(jobUuid, status);
946             });
947         List<String> statusesFromDB = asyncInstantiationBL.getAuditStatuses(jobUuid, SourceStatus.VID).stream().map(auditStatus -> auditStatus.getJobStatus()).collect(Collectors.toList());
948         List<String> statusesWithoutDuplicates = statusesToBeInserted.stream().distinct().map(x -> x.toString()).collect(Collectors.toList());
949         assertThat(statusesFromDB, is(statusesWithoutDuplicates));
950     }
951
952     @DataProvider
953     public static Object[][] msoAuditStatuses(Method test) {
954         UUID jobUuid = UUID.randomUUID();
955         UUID requestId = UUID.randomUUID();
956         return new Object[][]{
957                 {
958                         jobUuid,
959                         ImmutableList.of(
960                                 new JobAuditStatus(jobUuid, PENDING.toString(), SourceStatus.MSO, null, null),
961                                 new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, requestId, null),
962                                 new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, requestId, null),
963                                 new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, requestId, null),
964                                 new JobAuditStatus(jobUuid, COMPLETED.toString(), SourceStatus.MSO, requestId, null)),
965                         ImmutableList.of(PENDING.toString(), IN_PROGRESS.toString(), COMPLETED.toString()),
966                         "All distinct statuses should be without duplicates"
967                 },
968                 {
969                         jobUuid,
970                         ImmutableList.of(
971                                 new JobAuditStatus(jobUuid, PENDING.toString(), SourceStatus.MSO, null, null),
972                                 new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, requestId, null),
973                                 new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, requestId, "aa"),
974                                 new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, requestId, "aa"),
975                                 new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, UUID.randomUUID(), "aa"),
976                                 new JobAuditStatus(jobUuid, COMPLETED.toString(), SourceStatus.MSO, requestId, null)),
977                         ImmutableList.of(PENDING.toString(), IN_PROGRESS.toString(), IN_PROGRESS.toString(),IN_PROGRESS.toString(), COMPLETED.toString()),
978                         "Statuses should be without duplicates only with same requestId and additionalInfo"
979
980                 }
981         };
982     }
983
984     @Test(dataProvider = "msoAuditStatuses")
985     public void addSomeMsoStatuses_getThem_verifyGetInsertedWithoutDuplicates(UUID jobUuid, ImmutableList<JobAuditStatus> msoStatuses, ImmutableList<String> expectedStatuses, String assertionReason) {
986         msoStatuses.forEach(status -> {
987             asyncInstantiationBL.auditMsoStatus(status.getJobId(), status.getJobStatus(), status.getRequestId() != null ? status.getRequestId().toString() : null, status.getAdditionalInfo());
988         });
989         List<String> statusesFromDB = asyncInstantiationBL.getAuditStatuses(jobUuid, SourceStatus.MSO).stream().map(auditStatus -> auditStatus.getJobStatus()).collect(Collectors.toList());
990         assertThat( assertionReason, statusesFromDB, is(expectedStatuses));
991     }
992
993     @Test
994     public void addSameStatusOfVidAndMso_verifyThatBothWereAdded(){
995         UUID jobUuid = UUID.randomUUID();
996         JobStatus sameStatus = IN_PROGRESS;
997         asyncInstantiationBL.auditMsoStatus(jobUuid, sameStatus.toString(),null,null);
998         asyncInstantiationBL.auditVidStatus(jobUuid, sameStatus);
999         List<JobAuditStatus> list = dataAccessService.getList(
1000                 JobAuditStatus.class,
1001                 String.format(" where JOB_ID = '%s'", jobUuid),
1002                 null, null);
1003         Assert.assertEquals(list.size(),2);
1004         assertThat(list,everyItem(hasProperty("jobStatus", is(sameStatus.toString()))));
1005     }
1006
1007     @DataProvider
1008     public static Object[][] msoRequestStatusFiles(Method test) {
1009         return new Object[][]{
1010                 {"/responses/mso/orchestrationRequestsServiceInstance.json"},
1011                 {"/responses/mso/orchestrationRequestsVnf.json"},
1012                 {"/responses/mso/orchestrationRequestsMockedMinimalResponse.json"}
1013         };
1014     }
1015
1016     @Test(dataProvider="msoRequestStatusFiles")
1017     public void verifyAsyncRequestStatus_canBeReadFromSample(String msoResponseFile) throws IOException {
1018         AsyncRequestStatus asyncRequestStatus = TestUtils.readJsonResourceFileAsObject(
1019                 msoResponseFile,
1020                 AsyncRequestStatus.class);
1021         assertThat(asyncRequestStatus.request.requestStatus.getRequestState(), equalTo("COMPLETE"));
1022     }
1023
1024     @Test
1025     public void deleteJobInfo_pending_deleted() {
1026         doNothing().when(jobsBrokerServiceMock).delete(any());
1027         UUID uuid = createServicesInfoWithDefaultValues(PENDING);
1028         asyncInstantiationBL.deleteJob(uuid);
1029         assertNotNull(asyncInstantiationBL.getServiceInfoByJobId(uuid).getDeletedAt(), "service info wasn't deleted");
1030     }
1031
1032     @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE)
1033     public void deleteJobInfo_notAllowdStatus_shouldSendError() {
1034         UUID uuid = createServicesInfoWithDefaultValues(COMPLETED);
1035         doThrow(new IllegalStateException(DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE)).when(jobsBrokerServiceMock).delete(any());
1036         try {
1037             asyncInstantiationBL.deleteJob(uuid);
1038         } catch (Exception e) {
1039             assertNull(asyncInstantiationBL.getServiceInfoByJobId(uuid).getDeletedAt(), "service info shouldn't deleted");
1040             throw e;
1041         }
1042     }
1043
1044     @DataProvider
1045     public Object[][] jobStatusesFinal() {
1046         return Arrays.stream(Job.JobStatus.values())
1047                 .filter(t -> ImmutableList.of(COMPLETED, FAILED, STOPPED).contains(t))
1048                 .map(v -> new Object[]{v}).collect(Collectors.toList()).toArray(new Object[][]{});
1049     }
1050
1051     @Test(dataProvider = "jobStatusesFinal")
1052     public void whenHideService_theServiceNotReturnedInServiceList(JobStatus jobStatus) {
1053         UUID uuidToHide = createServicesInfoWithDefaultValues(jobStatus);
1054         UUID uuidToShown = createServicesInfoWithDefaultValues(jobStatus);
1055         List<UUID> serviceInfoList = listServicesUUID();
1056         assertThat(serviceInfoList, hasItems(uuidToHide, uuidToShown));
1057
1058         asyncInstantiationBL.hideServiceInfo(uuidToHide);
1059         serviceInfoList = listServicesUUID();
1060         assertThat(serviceInfoList, hasItem(uuidToShown));
1061         assertThat(serviceInfoList, not(hasItem(uuidToHide)));
1062
1063     }
1064
1065     protected List<UUID> listServicesUUID() {
1066         return asyncInstantiationBL.getAllServicesInfo().stream().map(ServiceInfo::getJobId).collect(Collectors.toList());
1067     }
1068
1069     @DataProvider
1070     public Object[][] jobStatusesNotFinal() {
1071         return Arrays.stream(Job.JobStatus.values())
1072                 .filter(t -> ImmutableList.of(PENDING, IN_PROGRESS, PAUSE).contains(t))
1073                 .map(v -> new Object[]{v}).collect(Collectors.toList()).toArray(new Object[][]{});
1074     }
1075
1076     @Test(dataProvider = "jobStatusesNotFinal",
1077             expectedExceptions = OperationNotAllowedException.class,
1078             expectedExceptionsMessageRegExp = "jobId.*Service status does not allow hide service, status = .*")
1079     public void hideServiceInfo_notAllowedStatus_shouldSendError(JobStatus jobStatus) {
1080         UUID uuid = createServicesInfoWithDefaultValues(jobStatus);
1081         try {
1082             asyncInstantiationBL.hideServiceInfo(uuid);
1083         } catch (Exception e) {
1084             assertFalse(asyncInstantiationBL.getServiceInfoByJobId(uuid).isHidden(), "service info shouldn't be hidden");
1085             throw e;
1086         }
1087     }
1088
1089     @Test
1090     public void whenUseGetCounterInMultiThreads_EachThreadGetDifferentCounter() throws InterruptedException {
1091         int SIZE = 200;
1092         ExecutorService executor = Executors.newFixedThreadPool(SIZE);
1093         List<Callable<Integer>> tasks = IntStream.rangeClosed(0, SIZE)
1094                 .mapToObj(x-> ((Callable<Integer>)() -> asyncInstantiationBL.getCounterForName("a")))
1095                 .collect(Collectors.toList());
1096         Set<Integer> expectedResults = IntStream.rangeClosed(0, SIZE).boxed().collect(Collectors.toSet());
1097         executor.invokeAll(tasks)
1098                 .forEach(future -> {
1099                     try {
1100                         assertTrue( expectedResults.remove(future.get()), "got unexpected counter");
1101                     }
1102                     catch (Exception e) {
1103                         throw new RuntimeException(e);
1104                     }
1105                 });
1106
1107         assertThat(expectedResults.size(), is(0));
1108     }
1109
1110     @Test
1111     public void whenUseGetCounterForSameName_numbersReturnedByOrder() {
1112
1113         String name = UUID.randomUUID().toString();
1114         int SIZE=10;
1115         for (int i=0; i<SIZE; i++) {
1116             assertThat(asyncInstantiationBL.getCounterForName(name), is(i));
1117         }
1118     }
1119
1120     @Test
1121     public void whenNamedInUsedInAai_getNextNumber() {
1122         String name = someCommonStepsAndGetName();
1123         ResourceType type = ResourceType.GENERIC_VNF;
1124         when(aaiClient.isNodeTypeExistsByName(name, type)).thenReturn(true);
1125         when(aaiClient.isNodeTypeExistsByName(name+"_001", type)).thenReturn(false);
1126         assertThat(asyncInstantiationBL.getUniqueName(name, type), equalTo(name+"_001"));
1127     }
1128
1129     private String someCommonStepsAndGetName() {
1130         mockAaiClientAaiStatusOK();
1131         return UUID.randomUUID().toString();
1132     }
1133
1134     private void mockAaiClientAaiStatusOK() {
1135         when(aaiClient.isNodeTypeExistsByName(eq(AsyncInstantiationBusinessLogicImpl.NAME_FOR_CHECK_AAI_STATUS), any())).thenReturn(false);
1136     }
1137
1138     @Test(expectedExceptions=ExceptionWithRequestInfo.class)
1139     public void whenAaiBadResponseCode_throwInvalidAAIResponseException() {
1140         String name = someCommonStepsAndGetName();
1141         ResourceType type = ResourceType.SERVICE_INSTANCE;
1142         when(aaiClient.isNodeTypeExistsByName(name, type)).thenThrow(aaiNodeQueryBadResponseException());
1143         asyncInstantiationBL.getUniqueName(name, type);
1144     }
1145
1146     @Test(expectedExceptions=MaxRetriesException.class)
1147     public void whenAaiAlwaysReturnNameUsed_throwInvalidAAIResponseException() {
1148         String name = someCommonStepsAndGetName();
1149         ResourceType type = ResourceType.VF_MODULE;
1150         when(aaiClient.isNodeTypeExistsByName(any(), eq(type))).thenReturn(true);
1151         asyncInstantiationBL.setMaxRetriesGettingFreeNameFromAai(10);
1152         asyncInstantiationBL.getUniqueName(name, type);
1153     }
1154
1155     @Test
1156     public void testFormattingOfNameAndCounter() {
1157         AsyncInstantiationBusinessLogicImpl bl = (AsyncInstantiationBusinessLogicImpl) asyncInstantiationBL;
1158         assertThat(bl.formatNameAndCounter("x", 0), equalTo("x"));
1159         assertThat(bl.formatNameAndCounter("x", 3), equalTo("x_003"));
1160         assertThat(bl.formatNameAndCounter("x", 99), equalTo("x_099"));
1161         assertThat(bl.formatNameAndCounter("x", 100), equalTo("x_100"));
1162         assertThat(bl.formatNameAndCounter("x", 1234), equalTo("x_1234"));
1163     }
1164
1165     @Test
1166     public void pushBulkJob_verifyAlacarteFlow_useALaCartServiceInstantiationJobType(){
1167         final ServiceInstantiation request = generateALaCarteServiceInstantiationPayload();
1168
1169         // in "createServiceInstantiationJob()" we will probe the service, with the generated names
1170         configureMockitoWithMockedJob();
1171
1172         ArgumentCaptor<JobType> argumentCaptor = ArgumentCaptor.forClass(JobType.class);
1173         asyncInstantiationBL.pushBulkJob(request, "myUserId");
1174         verify(jobAdapterMock).createServiceInstantiationJob(argumentCaptor.capture(),any(),any(),anyString(), anyString(), anyInt());
1175         assertTrue(argumentCaptor.getValue().equals(JobType.ALaCarteServiceInstantiation));
1176     }
1177
1178     @Test
1179     public void pushBulkJob_verifyMacroFlow_useMacroServiceInstantiationJobType(){
1180         final ServiceInstantiation request = generateMacroMockServiceInstantiationPayload(false, Collections.emptyMap());
1181
1182         // in "createServiceInstantiationJob()" we will probe the service, with the generated names
1183         configureMockitoWithMockedJob();
1184
1185         ArgumentCaptor<JobType> argumentCaptor = ArgumentCaptor.forClass(JobType.class);
1186         asyncInstantiationBL.pushBulkJob(request, "myUserId");
1187         verify(jobAdapterMock).createServiceInstantiationJob(argumentCaptor.capture(),any(),any(),anyString(), anyString(), anyInt());
1188         assertTrue(argumentCaptor.getValue().equals(JobType.MacroServiceInstantiation));
1189     }
1190
1191     @Test
1192     public void generateALaCarteServiceInstantiationRequest_verifyRequestIsAsExpected() throws IOException {
1193         ServiceInstantiation serviceInstantiationPayload = generateALaCarteServiceInstantiationPayload();
1194         final URL resource = this.getClass().getResource("/payload_jsons/bulk_alacarte_service_request.json");
1195         RequestDetailsWrapper<ServiceInstantiationRequestDetails> result =
1196                 asyncInstantiationBL.generateALaCarteServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016");
1197         String expected = IOUtils.toString(resource, "UTF-8");
1198         MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
1199     }
1200
1201     @Test
1202     public void generateALaCarteServiceDeletionRequest_verifyRequestIsAsExpected() throws IOException {
1203         final URL resource = this.getClass().getResource("/payload_jsons/bulk_alacarte_service_deletion_request.json");
1204         String expected = IOUtils.toString(resource, "UTF-8");
1205
1206         ServiceInstantiation serviceDeletionPayload = generateALaCarteServiceDeletionPayload();
1207         RequestDetailsWrapper<ServiceDeletionRequestDetails> result =
1208                 asyncInstantiationBL.generateALaCarteServiceDeletionRequest(null, serviceDeletionPayload, "az2016");
1209
1210         MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
1211     }
1212
1213     @Test
1214     public void getALaCarteServiceDeletionPath_verifyPathIsAsExpected() throws IOException {
1215
1216         String expected = "/serviceInstantiation/v./serviceInstances/f36f5734-e9df-4fbf-9f35-61be13f028a1";
1217
1218         String result = asyncInstantiationBL.getServiceDeletionPath("f36f5734-e9df-4fbf-9f35-61be13f028a1");
1219
1220         assertThat(result, matchesPattern(expected));
1221     }
1222
1223     @Test
1224     public void getInstanceGroupsDeletionPath_verifyPathIsAsExpected()  {
1225
1226         assertEquals(asyncInstantiationBL.getInstanceGroupDeletePath("9aada4af-0f9b-424f-ae21-e693bd3e005b"),
1227                 "/serviceInstantiation/v7/instanceGroups/9aada4af-0f9b-424f-ae21-e693bd3e005b");
1228     }
1229
1230     @DataProvider
1231     public static Object[][] testBuildVnfInstanceParamsDataProvider(Method test) {
1232         return new Object[][]{
1233                 {
1234                     Collections.EMPTY_LIST,
1235                     ImmutableList.of(
1236                         ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2")),
1237                         ImmutableList.of(ImmutableMap.of("k3","v3","k2","v2"))
1238                     ),
1239                     true,
1240                     ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2","k3","v3"))
1241                 },
1242                 {
1243                         ImmutableList.of(ImmutableMap.of("j1", "w1", "k1","v1", "vnf_name","w2", "vf_module_name","w3")), //vnf_name, vf_module_name are excluded
1244                         ImmutableList.of(
1245                                 ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2")),
1246                                 ImmutableList.of(ImmutableMap.of("k3","v3","k2","v2")),
1247                                 ImmutableList.of(Collections.EMPTY_MAP),
1248                                 Collections.singletonList(null)
1249                         ),
1250                         true,
1251                         ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2","k3","v3","j1", "w1"))
1252                 },
1253                 {
1254                         Collections.EMPTY_LIST,
1255                         Arrays.asList(null, null),
1256                         true,
1257                         Collections.EMPTY_LIST //mso is expect to empty list and not list with empty map
1258                 },
1259                 {
1260                         ImmutableList.of(Collections.EMPTY_MAP),
1261                         ImmutableList.of(
1262                                 ImmutableList.of(Collections.EMPTY_MAP),
1263                                 ImmutableList.of(Collections.EMPTY_MAP)
1264                         ),
1265                         true,
1266                         Collections.EMPTY_LIST //mso is expect to empty list and not list with empty map
1267                 },
1268                 {
1269                         Collections.EMPTY_LIST,
1270                         ImmutableList.of(
1271                                 ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2")),
1272                                 ImmutableList.of(ImmutableMap.of("k3","v3","k2","v2"))
1273                         ),
1274                         false,
1275                         Collections.EMPTY_LIST //mso is expect to empty list and not list with empty map
1276                 },
1277                 {
1278                         ImmutableList.of(ImmutableMap.of("j1", "w1", "k1","v1", "vnf_name","w2", "vf_module_name","w3")),
1279                         ImmutableList.of(
1280                                 ImmutableList.of(Collections.EMPTY_MAP)
1281                         ),
1282                         false,
1283                         ImmutableList.of(ImmutableMap.of("j1", "w1", "k1","v1"))
1284                 },
1285                 {
1286                         ImmutableList.of(ImmutableMap.of("vnf_name","w2", "vf_module_name", "w3", "j2", "w2", "j4","w4")),
1287                         ImmutableList.of(
1288                                 ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2")),
1289                                 ImmutableList.of(ImmutableMap.of("k3","v3","k2","v2"))
1290                         ),
1291                         false,
1292                         ImmutableList.of(ImmutableMap.of("j2", "w2", "j4","w4"))
1293                 },
1294
1295         };
1296     }
1297
1298     @Test(dataProvider="testBuildVnfInstanceParamsDataProvider")
1299     public void testBuildVnfInstanceParams(List<Map<String, String>> currentVnfInstanceParams,
1300                                            List<List<Map<String, String>>> vfModulesInstanceParams,
1301                                            boolean isFeatureActive,
1302                                            List<Map<String,String>> expectedResult){
1303         when(featureManager.isActive(Features.FLAG_SHIFT_VFMODULE_PARAMS_TO_VNF)).thenReturn(isFeatureActive);
1304         List<VfModuleMacro> vfModules =
1305                 vfModulesInstanceParams.stream().map(params-> new VfModuleMacro(new ModelInfo(), null, null, params)).collect(Collectors.toList());
1306         List<Map<String,String>> actual = asyncInstantiationBL.buildVnfInstanceParams(currentVnfInstanceParams, vfModules);
1307         assertThat(actual, equalTo(expectedResult));
1308
1309     }
1310
1311     @Test
1312     public void whenLcpRegionNotEmpty_thenCloudRegionIdOfResourceIsLegacy() {
1313         String legacyCloudRegion = "legacyCloudRegion";
1314         Vnf vnf = new Vnf(new ModelInfo(), null, null, Action.Create.name(), null, "anyCloudRegion", legacyCloudRegion, null, null, null, false, null, null);
1315         assertThat(vnf.getLcpCloudRegionId(), equalTo(legacyCloudRegion));
1316
1317
1318     }
1319
1320     @Test
1321     public void whenLcpRegionNotEmpty_thenCloudRegionIdOfServiceIsLegacy() {
1322         String legacyCloudRegion = "legacyCloudRegion";
1323         ServiceInstantiation service = new ServiceInstantiation(new ModelInfo(), null, null, null, null, null, null,
1324                 null, null, "anyCloudRegion", legacyCloudRegion, null, null, null, null, null, null, null, null,
1325                 false, 1,false, false, null, null, Action.Create.name());
1326         assertThat(service.getLcpCloudRegionId(), equalTo(legacyCloudRegion));
1327     }
1328
1329     @Test
1330     public void createVolumeGroup_verifyResultAsExpected() throws IOException {
1331         final URL resource = this.getClass().getResource("/payload_jsons/volumegroup_instantiation_request.json");
1332         VfModule vfModule = createVfModule("201673MowAvpnVpeBvL..AVPN_vRE_BV..module-1",
1333                 "56e2b103-637c-4d1a-adc8-3a7f4a6c3240",
1334                 "72d9d1cd-f46d-447a-abdb-451d6fb05fa8",
1335                 Collections.emptyList(),
1336                 Collections.emptyMap(),
1337                 "vmxnjr001_AVPN_base_vRE_BV_expansion",
1338                 "myVgName",
1339                 true);
1340         vfModule.getModelInfo().setModelInvariantId("ff5256d2-5a33-55df-13ab-12abad84e7ff");
1341         vfModule.getModelInfo().setModelVersion("1");
1342         ModelInfo vnfModelInfo = createVnfModelInfo(true);
1343         RequestDetailsWrapper<VolumeGroupRequestDetails> result =
1344                 asyncInstantiationBL.generateVolumeGroupInstantiationRequest(vfModule,
1345                         createServiceModelInfo(),
1346                        "ff3514e3-5a33-55df-13ab-12abad84e7ff",
1347                         vnfModelInfo,
1348                         "vnfInstanceId",
1349                         "az2016");
1350         String expected = IOUtils.toString(resource, "UTF-8");
1351         MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
1352     }
1353
1354     @Test
1355     public void getJobTypeByRequest_verifyResultAsExpected(){
1356         ServiceInstantiation service = new ServiceInstantiation(new ModelInfo(), null, null, null, null, null, null,
1357                 null, null, null, null, null, null, null, null, null, null, null, null,
1358                 false, 1,false, false, null, null, Action.Create.name());
1359         JobType jobType = asyncInstantiationBL.getJobType(service) ;
1360         assertThat(jobType, equalTo(JobType.MacroServiceInstantiation));
1361         service = new ServiceInstantiation(new ModelInfo(), null, null, null, null, null, null,
1362                 null, null, null, null, null, null, null, null, null, null, null, null,
1363                 false, 1,false, true, null, null, Action.Create.name());
1364         jobType = asyncInstantiationBL.getJobType(service);
1365         assertThat(jobType, equalTo(JobType.ALaCarteServiceInstantiation));
1366         service = new ServiceInstantiation(new ModelInfo(), null, null, null, null, null, null,
1367                 null, null, null, null, null, null, null, null, null, null, null, null,
1368                 false, 1,false, true, null, null, Action.Delete.name());
1369         jobType = asyncInstantiationBL.getJobType(service);
1370         assertThat(jobType, equalTo(JobType.ALaCarteService));
1371     }
1372
1373     protected ServiceInstantiation generateALaCarteServiceInstantiationPayload() {
1374         return generateMockALaCarteServiceInstantiationPayload(false, Collections.EMPTY_MAP, Collections.EMPTY_MAP, Collections.EMPTY_MAP, 1, true, PROJECT_NAME, false, "VNF_API");
1375     }
1376
1377     private ServiceInstantiation generateALaCarteServiceDeletionPayload() {
1378         return generateMockALaCarteServiceDeletionPayload(false, Collections.EMPTY_MAP, Collections.EMPTY_MAP, Collections.EMPTY_MAP, 1, true, PROJECT_NAME, false, "VNF_API", "1234567890");
1379     }
1380
1381     static class MockedJob implements Job {
1382
1383         private static Map<UUID, MockedJob> uuidToJob = new HashMap<>();
1384
1385         public static void putJob(UUID uuid, MockedJob job) {
1386             uuidToJob.put(uuid, job);
1387         }
1388
1389         public static MockedJob getJob(UUID uuid) {
1390             return uuidToJob.get(uuid);
1391         }
1392
1393
1394         private String optimisticUniqueServiceInstanceName;
1395
1396         public MockedJob(String optimisticUniqueServiceInstanceName) {
1397             this.optimisticUniqueServiceInstanceName = optimisticUniqueServiceInstanceName;
1398         }
1399
1400         private UUID uuid = UUID.randomUUID();
1401
1402         @Override
1403         public UUID getUuid() {
1404             return uuid;
1405         }
1406
1407         @Override
1408         public void setUuid(UUID uuid) {
1409             this.uuid = uuid;
1410         }
1411
1412         @Override
1413         public JobStatus getStatus() {
1414             return JobStatus.PENDING;
1415         }
1416
1417         @Override
1418         public void setStatus(JobStatus status) {
1419
1420         }
1421
1422         @Override
1423         public Map<String, Object> getData() {
1424             return null;
1425         }
1426
1427         @Override
1428         public JobSharedData getSharedData() {
1429             return new JobSharedData(uuid, "", null);
1430         }
1431
1432         @Override
1433         public void setTypeAndData(JobType jobType, Map<String, Object> commandData) {
1434
1435         }
1436
1437         @Override
1438         public UUID getTemplateId() {
1439             return null;
1440         }
1441
1442         @Override
1443         public void setTemplateId(UUID templateId) {
1444
1445         }
1446
1447         @Override
1448         public Integer getIndexInBulk() {
1449             return null;
1450         }
1451
1452         @Override
1453         public void setIndexInBulk(Integer indexInBulk) {
1454
1455         }
1456
1457         @Override
1458         public JobType getType() {
1459             return null;
1460         }
1461
1462         public String getOptimisticUniqueServiceInstanceName() {
1463             return optimisticUniqueServiceInstanceName;
1464         }
1465     }
1466 }