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