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