Merge "Change template properties for AAI"
[vid.git] / vid-app-common / src / test / java / org / onap / vid / services / AsyncInstantiationBusinessLogicTest.java
1 package org.onap.vid.services;
2
3 import org.onap.portalsdk.core.util.SystemProperties;
4 import org.onap.vid.config.DataSourceConfig;
5 import org.onap.vid.config.MockedAaiClientAndFeatureManagerConfig;
6 import org.springframework.test.context.ContextConfiguration;
7
8 @ContextConfiguration(classes = {DataSourceConfig.class, SystemProperties.class, MockedAaiClientAndFeatureManagerConfig.class})
9 public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseTest {
10 /*
11 TO BE FIXED
12     @Inject
13     private DataAccessService dataAccessService;
14
15     @Mock
16     private JobAdapter jobAdapter;
17
18     @Mock
19     private JobsBrokerService jobsBrokerService;
20
21
22
23     @Autowired
24     private SessionFactory sessionFactory;
25
26     private AsyncInstantiationBusinessLogic asyncInstantiationBL;
27
28     private int serviceCount = 0;
29
30     private static final String UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE =
31             "Failed to retrieve job with uuid .* from ServiceInfo table. Instances found: .*";
32
33     private static final String DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE =
34             "Service status does not allow deletion from the queue";
35
36     @BeforeClass
37     void initServicesInfoService() {
38         MockitoAnnotations.initMocks(this);
39         asyncInstantiationBL = new AsyncInstantiationBusinessLogicImpl(dataAccessService, jobAdapter, jobsBrokerService, sessionFactory, aaiClient);
40         createInstanceParamsMaps();
41     }
42
43     @BeforeMethod
44     void defineMocks() {
45         mockAaiClientAnyNameFree();
46     }
47
48     @BeforeMethod
49     void resetServiceCount() {
50         serviceCount = 0;
51     }
52
53     @AfterMethod
54     void clearDb() {
55         dataAccessService.deleteDomainObjects(JobDaoImpl.class, "1=1", getPropsMap());
56         dataAccessService.deleteDomainObjects(ServiceInfo.class, "1=1", getPropsMap());
57         dataAccessService.deleteDomainObjects(JobAuditStatus.class, "1=1", getPropsMap());
58         dataAccessService.deleteDomainObjects(NameCounter.class, "1=1", getPropsMap());
59     }
60
61
62     private void createNewTestServicesInfoForFilter(String userId) {
63         LocalDateTime createdDate, modifiedDate;
64         LocalDateTime NOW = LocalDateTime.now();
65         UUID uuid;
66
67         // Old job
68         uuid = UUID.randomUUID();
69         addNewJob(uuid);
70         createdDate = NOW.minusYears(1);
71         addNewServiceInfo(uuid, userId, "Old", createdDate, createdDate, COMPLETED, false);
72
73         uuid = UUID.randomUUID();
74         addNewJob(uuid);
75         createdDate = NOW.minusDays(20);
76         modifiedDate = NOW.minusDays(19);
77         addNewServiceInfo(uuid, userId, "Hidden", createdDate, modifiedDate, PAUSE, true);
78
79         createNewTestServicesInfo(String.valueOf(userId));
80     }
81
82     private void createNewTestServicesInfo(String userId) {
83
84         LocalDateTime createdDate, modifiedDate;
85         LocalDateTime NOW = LocalDateTime.now();
86         UUID uuid;
87
88         uuid = UUID.randomUUID();
89         addNewJob(uuid);
90
91         createdDate = NOW.minusDays(40);
92         addNewServiceInfo(uuid, userId, "service instance 5", createdDate, createdDate, COMPLETED, false);
93         addNewServiceInfo(uuid, userId, "service instance 6", createdDate, createdDate, STOPPED, false);
94
95         uuid = UUID.randomUUID();
96         addNewJob(uuid);
97
98         createdDate = NOW.minusDays(20);
99         modifiedDate = NOW.minusDays(10);
100         addNewServiceInfo(uuid, userId, "service instance 4", createdDate, modifiedDate, STOPPED, false);
101         addNewServiceInfo(uuid, userId, "service instance 2", createdDate, modifiedDate, COMPLETED, false);
102         addNewServiceInfo(uuid, userId, "service instance 3", createdDate, modifiedDate, PAUSE, false);
103
104         modifiedDate = NOW.minusDays(19);
105         addNewServiceInfo(uuid, userId, "service instance 1", createdDate, modifiedDate, FAILED, false);
106
107
108         // Job to a different user
109         uuid = UUID.randomUUID();
110         addNewJob(uuid);
111
112         createdDate = NOW.minusMonths(2);
113         addNewServiceInfo(uuid, "2221", "service instance 7", createdDate, createdDate, COMPLETED, false);
114
115     }
116
117     private UUID createServicesInfoWithDefaultValues(Job.JobStatus status) {
118
119         LocalDateTime NOW = LocalDateTime.now();
120         UUID uuid;
121
122         uuid = UUID.randomUUID();
123         addNewJob(uuid, status);
124
125         addNewServiceInfo(uuid, null, "service instance 1", NOW, NOW, status, false);
126
127         return uuid;
128
129     }
130
131     private List<ServiceInfo> getFullList() {
132         List<ServiceInfo> expectedOrderServiceInfo = dataAccessService.getList(ServiceInfo.class, getPropsMap());
133         assertThat("Failed to retrieve all predefined services", expectedOrderServiceInfo.size(), equalTo(serviceCount));
134         expectedOrderServiceInfo.sort(new ServiceInfoComparator());
135         return expectedOrderServiceInfo;
136     }
137
138     private static Date toDate(LocalDateTime localDateTime) {
139         return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
140     }
141
142     private LocalDateTime fromDate(Date date) {
143         return Instant.ofEpochMilli(date.getTime())
144                 .atZone(ZoneId.systemDefault())
145                 .toLocalDateTime();
146     }
147
148     private void addNewServiceInfo(UUID uuid, String userId, String serviceName, LocalDateTime createDate, LocalDateTime statusModifiedDate, Job.JobStatus status, boolean isHidden) {
149         ServiceInfo serviceInfo = new ServiceInfo();
150         serviceInfo.setJobId(uuid);
151         serviceInfo.setUserId(userId);
152         serviceInfo.setServiceInstanceName(serviceName);
153         serviceInfo.setStatusModifiedDate(toDate(statusModifiedDate));
154         serviceInfo.setJobStatus(status);
155         serviceInfo.setPause(false);
156         serviceInfo.setOwningEntityId("1234");
157         serviceInfo.setCreatedBulkDate(toDate(createDate));
158
159         serviceInfo.setHidden(isHidden);
160         dataAccessService.saveDomainObject(serviceInfo, getPropsMap());
161         setCreateDateToServiceInfo(uuid, createDate);
162         serviceCount++;
163
164     }
165
166     private void setCreateDateToServiceInfo(UUID jobUuid, LocalDateTime createDate) {
167         List<ServiceInfo> serviceInfoList = dataAccessService.getList(ServiceInfo.class, getPropsMap());
168         DaoUtils.tryWithSessionAndTransaction(sessionFactory, session -> {
169             serviceInfoList.stream()
170                     .filter(serviceInfo -> jobUuid.equals(serviceInfo.getJobId()))
171                     .forEach(serviceInfo -> {
172                         serviceInfo.setCreated(toDate(createDate));
173                         session.saveOrUpdate(serviceInfo);
174                     });
175             return 1;
176         });
177     }
178
179     private void addNewJob(UUID uuid) {
180         addNewJob(uuid, null);
181     }
182
183     private void addNewJob(UUID uuid, Job.JobStatus status) {
184         JobDaoImpl jobDao = new JobDaoImpl();
185         jobDao.setUuid(uuid);
186         jobDao.setStatus(status);
187         dataAccessService.saveDomainObject(jobDao, getPropsMap());
188     }
189
190     @Test
191     public void testServiceInfoAreOrderedAsExpected() {
192         int userId = 2222;
193         createNewTestServicesInfo(String.valueOf(userId));
194         List<ServiceInfo> expectedOrderServiceInfo = getFullList();
195         List<ServiceInfo> serviceInfoListResult = asyncInstantiationBL.getAllServicesInfo();
196         assertThat("Services aren't ordered as expected", serviceInfoListResult, equalTo(expectedOrderServiceInfo));
197     }
198
199     @Test
200     public void testServiceInfoAreFilteredAsExpected() {
201         int userId = 2222;
202         createNewTestServicesInfoForFilter(String.valueOf(userId));
203         List<ServiceInfo> expectedOrderServiceInfo = getFullList();
204
205         List<ServiceInfo> expectedFilterByUser = expectedOrderServiceInfo.stream().filter(x ->
206                 !x.getServiceInstanceName().equals("Old") && !x.getServiceInstanceName().equals("Hidden")
207
208         ).collect(Collectors.toList());
209
210
211         List<ServiceInfo> serviceInfoFilteredByUser = asyncInstantiationBL.getAllServicesInfo();
212         assertThat("Services aren't ordered filtered as expected", serviceInfoFilteredByUser, equalTo(expectedFilterByUser));
213     }
214
215     @Test(dataProvider = "pauseAndInstanceParams", enabled = false) //Test is irrelevant with unique names feature
216     public void createServiceInstantiationMsoRequest(Boolean isPause, HashMap<String, String> vfModuleInstanceParamsMap, List vnfInstanceParams) throws Exception {
217         ServiceInstantiation serviceInstantiationPayload = generateMockServiceInstantiationPayload(isPause, createVnfList(vfModuleInstanceParamsMap, vnfInstanceParams, true));
218         final URL resource = this.getClass().getResource("/payload_jsons/bulk_service_request.json");
219             RequestDetailsWrapper<ServiceInstantiationRequestDetails> result =
220                     asyncInstantiationBL.generateServiceInstantiationRequest(null, serviceInstantiationPayload, "az2016");
221             String expected = IOUtils.toString(resource, "UTF-8");
222             MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
223     }
224
225     @Test(dataProvider = "pauseAndInstanceParams")
226     public void createServiceInstantiationMsoRequestUniqueName(Boolean isPause, HashMap<String, String> vfModuleInstanceParamsMap, List vnfInstanceParams) throws Exception {
227         Mockito.reset(aaiClient);
228         mockAaiClientAnyNameFree();
229         ServiceInstantiation serviceInstantiationPayload = generateMockServiceInstantiationPayload(isPause, createVnfList(vfModuleInstanceParamsMap, vnfInstanceParams, true));
230         final URL resource = this.getClass().getResource("/payload_jsons/bulk_service_request_unique_names.json");
231         List<UUID> uuids = new ArrayList<>();
232         for (int i = 0; i < 2; i++) {
233             UUID currentUuid = createJobAndServiceInfo();
234             uuids.add(currentUuid);
235             RequestDetailsWrapper<ServiceInstantiationRequestDetails> result =
236                     asyncInstantiationBL.generateServiceInstantiationRequest(currentUuid, serviceInstantiationPayload, "az2016");
237             String unique =  String.format("00%s", i + 1);
238             String expected = IOUtils.toString(resource, "UTF-8")
239                     .replace("{SERVICE_UNIQENESS}", unique)
240                     .replace("{VNF_UNIQENESS}", unique)
241                     .replace("{VF_MODULE_UNIQENESS}", unique)
242                     .replace("{VF_MODULE_2_UNIQENESS}", unique)
243                     .replace("{VG_UNIQUENESS}", unique);
244             MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
245             Optional<ServiceInfo> optionalServiceInfo = getJobById(currentUuid);
246             assertThat(optionalServiceInfo.get().getServiceInstanceName(), equalTo("vPE_Service_" + unique));
247             verifySearchNodeTypeByName(unique, "vPE_Service_", ResourceType.SERVICE_INSTANCE);
248             verifySearchNodeTypeByName(unique, "vmxnjr001_", ResourceType.GENERIC_VNF);
249             verifySearchNodeTypeByName(unique, "vmxnjr001_AVPN_base_vPE_BV_base_", ResourceType.VF_MODULE);
250             verifySearchNodeTypeByName(unique, "vmxnjr001_AVPN_base_vRE_BV_expansion_", ResourceType.VF_MODULE);
251             verifySearchNodeTypeByName(unique, "myVgName_", ResourceType.VOLUME_GROUP);
252         }
253     }
254
255     protected void verifySearchNodeTypeByName(String unique, String resourceName, ResourceType serviceInstance) {
256         verify(aaiClient, times(1)).searchNodeTypeByName(resourceName + unique, serviceInstance);
257     }
258
259     private HashMap<String, Object> getPropsMap() {
260         HashMap<String, Object> props = new HashMap<>();
261         props.put(FusionObject.Parameters.PARAM_USERID, 0);
262         return props;
263     }
264
265     @Test(enabled = false) //probably not needed with name uniqueness feature
266     public void pushBulkJob_bulkWithSize3_instancesNamesAreExactlyAsExpected() {
267         int bulkSize = 3;
268
269         final ServiceInstantiation request = generateMockServiceInstantiationPayload(
270                 false,
271                 createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true),
272                 bulkSize, true,PROJECT_NAME, true
273         );
274
275         // in "createJob()" we will probe the service, with the generated names
276         final Job job = mock(Job.class);
277         when(job.getStatus()).thenReturn(PENDING);
278         when(jobAdapter.createJob(any(), any(), any(), any(), any())).thenReturn(job);
279
280
281         final List<UUID> uuids = asyncInstantiationBL.pushBulkJob(request, "myUserId");
282
283
284         ArgumentCaptor<ServiceInstantiation> serviceInstantiationCaptor = new ArgumentCaptor<ServiceInstantiation>();
285         verify(jobAdapter, times(bulkSize)).createJob(any(), serviceInstantiationCaptor.capture(), any(), any(), any());
286
287         assertThat(serviceInstantiationCaptor.getAllValues().stream().map(v -> v.getInstanceName()).collect(Collectors.toList()),
288                 containsInAnyOrder("vPE_Service_001", "vPE_Service_002", "vPE_Service_003"));
289
290         assertThat(uuids, hasSize(bulkSize));
291     }
292
293     @Test
294     public void generateMockServiceInstantiationPayload_serializeBackAndForth_sourceShouldBeTheSame() throws IOException {
295         ServiceInstantiation serviceInstantiationPayload = generateMockServiceInstantiationPayload(
296                 false,
297                 createVnfList(instanceParamsMapWithoutParams, ImmutableList.of(vnfInstanceParamsMapWithParamsToRemove, vnfInstanceParamsMapWithParamsToRemove), true),
298                 2, false,PROJECT_NAME, false);
299         ObjectMapper mapper = new ObjectMapper();
300         final String asString = mapper.writeValueAsString(serviceInstantiationPayload);
301
302         final ServiceInstantiation asObject = mapper.readValue(asString, ServiceInstantiation.class);
303         final String asString2 = mapper.writeValueAsString(asObject);
304
305         JsonAssert.assertJsonEquals(asString, asString2);
306     }
307
308     public static class ServiceInfoComparator implements Comparator<ServiceInfo> {
309
310         @Override
311         public int compare(ServiceInfo o1, ServiceInfo o2) {
312             int compare;
313
314             compare = o1.getCreatedBulkDate().compareTo(o2.getCreatedBulkDate());
315             if (compare != 0) {
316                 return -compare;
317             }
318
319             // check jobStatus priority
320             int o1Priority = getPriority(o1);
321             int o2Priority = getPriority(o2);
322             compare = o1Priority - o2Priority;
323             if (compare != 0) {
324                 return compare;
325             }
326
327             // check statusModifiedDate
328             return o1.getStatusModifiedDate().compareTo(o2.getStatusModifiedDate());
329         }
330
331         private int getPriority(ServiceInfo o) throws JSONException {
332             Job.JobStatus status = o.getJobStatus();
333             switch (status) {
334                 case COMPLETED:
335                 case FAILED:
336                     return 1;
337                 case IN_PROGRESS:
338                     return 2;
339                 case PAUSE:
340                     return 3;
341                 case STOPPED:
342                 case PENDING:
343                     return 4;
344                 default:
345                     return 5;
346             }
347         }
348     }
349
350     @DataProvider
351     public Object[][] pauseAndInstanceParams() {
352         return new Object[][]{
353                 {Boolean.TRUE, instanceParamsMapWithoutParams, Collections.EMPTY_LIST},
354                 {Boolean.FALSE, instanceParamsMapWithoutParams, Collections.EMPTY_LIST},
355                 {Boolean.TRUE, vfModuleInstanceParamsMapWithParamsToRemove, Collections.singletonList(vnfInstanceParamsMapWithParamsToRemove)}
356         };
357     }
358
359     private ServiceInstantiation generateMockServiceInstantiationPayload(boolean isPause, Map<String, Vnf> vnfs) {
360         return generateMockServiceInstantiationPayload(isPause, vnfs, 1, true, PROJECT_NAME, false);
361     }
362
363     @Test
364     public void testUpdateServiceInfo_WithExistingServiceInfo_ServiceInfoIsUpdated() {
365         UUID uuid = createJobAndServiceInfo();
366         final String STEPH_CURRY = "Steph Curry";
367         asyncInstantiationBL.updateServiceInfo(uuid, x -> {
368             x.setServiceInstanceName(STEPH_CURRY);
369             x.setJobStatus(Job.JobStatus.IN_PROGRESS);
370         });
371         Optional<ServiceInfo> optionalServiceInfo = getJobById(uuid);
372         assertThat(optionalServiceInfo.get().getServiceInstanceName(), equalTo(STEPH_CURRY));
373         assertThat(optionalServiceInfo.get().getJobStatus(), equalTo(Job.JobStatus.IN_PROGRESS));
374     }
375
376     private Optional<ServiceInfo> getJobById(UUID jobId) {
377         List<ServiceInfo> serviceInfoList = dataAccessService.getList(ServiceInfo.class, null);
378         return serviceInfoList.stream().filter(x -> jobId.equals(x.getJobId())).findFirst();
379     }
380
381     private UUID createJobAndServiceInfo() {
382         UUID uuid = UUID.randomUUID();
383         addNewJob(uuid);
384         ServiceInfo serviceInfo = new ServiceInfo();
385         serviceInfo.setServiceInstanceName("Lebron James");
386         serviceInfo.setJobId(uuid);
387         serviceInfo.setJobStatus(Job.JobStatus.PENDING);
388         dataAccessService.saveDomainObject(serviceInfo, getPropsMap());
389         return uuid;
390     }
391
392     @Test(expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE)
393     public void testUpdateServiceInfo_WithNonExisting_ThrowException() {
394         asyncInstantiationBL.updateServiceInfo(UUID.randomUUID(), x -> x.setServiceInstanceName("not matter"));
395     }
396
397     @Test(expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE)
398     public void testUpdateServiceInfo_WithDoubleServiceWithSameJobUuid_ThrowException() {
399         UUID uuid = createJobAndServiceInfo();
400         ServiceInfo serviceInfo = new ServiceInfo();
401         serviceInfo.setJobId(uuid);
402         dataAccessService.saveDomainObject(serviceInfo, getPropsMap());
403         asyncInstantiationBL.updateServiceInfo(UUID.randomUUID(), x -> x.setServiceInstanceName("not matter"));
404     }
405
406
407
408     @Test
409     public void testRequestPath_WithPauseFlagTrue_RequestPathIsAsExpected() {
410         ServiceInstantiation serviceInstantiationPauseFlagTrue = generateMockServiceInstantiationPayload(true, createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true));
411         String path = asyncInstantiationBL.getServiceInstantiationPath(serviceInstantiationPauseFlagTrue);
412         Assert.assertEquals(path, SystemProperties.getProperty("mso.restapi.serviceInstanceAssign"));
413     }
414
415     @Test
416     public void testRequestPath_WithPauseFlagFalse_RequestPathIsAsExpected() {
417         ServiceInstantiation serviceInstantiationPauseFlagFalse = generateMockServiceInstantiationPayload(false, createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true));
418         String path = asyncInstantiationBL.getServiceInstantiationPath(serviceInstantiationPauseFlagFalse);
419         Assert.assertEquals(path, SystemProperties.getProperty("mso.restapi.serviceInstanceCreate"));
420     }
421
422     @Test
423     public void createServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected() throws IOException {
424         createServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(true);
425     }
426
427     @Test
428     public void createServiceInfo_WithUserProvidedNamingFalseAndNoVfmodules_ServiceInfoIsAsExpected() throws IOException {
429         createServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(false);
430     }
431
432     private void createServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(boolean withVfmodules) throws IOException {
433         ServiceInstantiation serviceInstantiationPayload = generateMockServiceInstantiationPayload(true,
434                 createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, Collections.EMPTY_LIST, false),
435                 1,
436                 false,PROJECT_NAME, true);
437         URL resource;
438         if (withVfmodules) {
439             resource = this.getClass().getResource("/payload_jsons/bulk_service_request_ecomp_naming.json");
440         } else {
441             // remove the vf modules
442             serviceInstantiationPayload.getVnfs().values().forEach(vnf -> vnf.getVfModules().clear());
443             resource = this.getClass().getResource("/payload_jsons/bulk_service_request_no_vfmodule_ecomp_naming.json");
444         }
445
446         RequestDetailsWrapper<ServiceInstantiationRequestDetails> result =
447                 asyncInstantiationBL.generateServiceInstantiationRequest(null, serviceInstantiationPayload, "az2016");
448
449         String expected = IOUtils.toString(resource, "UTF-8");
450         MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
451     }
452
453     @Test
454     public void checkIfNullProjectNameSentToMso(){
455         ServiceInstantiation serviceInstantiationPayload = generateMockServiceInstantiationPayload(true,
456                 createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, Collections.EMPTY_LIST, false),
457                 1,
458                 false,null,false);
459         RequestDetailsWrapper<ServiceInstantiationRequestDetails> result =
460                 asyncInstantiationBL.generateServiceInstantiationRequest(null, serviceInstantiationPayload, "az2016");
461         JsonNode jsonNode = new ObjectMapper().valueToTree(result.requestDetails);
462         Assert.assertTrue(jsonNode.get("project").isNull());
463         serviceInstantiationPayload = generateMockServiceInstantiationPayload(true,
464                 createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, Collections.EMPTY_LIST, false),
465                 1,
466                 false,"not null",false);
467         result = asyncInstantiationBL.generateServiceInstantiationRequest(null, serviceInstantiationPayload, "az2016");
468         jsonNode = new ObjectMapper().valueToTree(result.requestDetails);
469         Assert.assertTrue(jsonNode.get("project").get("projectName").asText().equalsIgnoreCase("not null"));
470
471
472
473     }
474
475     @Test
476     public void pushBulkJob_verifyCreatedDateBehavior_createdDateIsTheSameForAllServicesInSameBulk() {
477         LocalDateTime startTestDate = LocalDateTime.now().withNano(0);
478         final ServiceInstantiation request = generateMockServiceInstantiationPayload(
479                 false,
480                 createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true),
481                 100, true,PROJECT_NAME, true
482         );
483
484         // in "createJob()" we will probe the service, with the generated names
485         final Job job = mock(Job.class);
486         when(job.getStatus()).thenReturn(PENDING);
487         when(jobAdapter.createJob(any(), any(), any(), any(), any())).thenReturn(job);
488
489         asyncInstantiationBL.pushBulkJob(request, "myUserId");
490         List<ServiceInfo> serviceInfoList = dataAccessService.getList(ServiceInfo.class, getPropsMap());
491
492         List<Date> creationDates = new ArrayList<>();
493         for (ServiceInfo serviceInfo : serviceInfoList) {
494             creationDates.add(serviceInfo.getCreatedBulkDate());
495         }
496         LocalDateTime endTestDate = LocalDateTime.now();
497
498         //creation date of all services is the same
499         Assert.assertTrue(creationDates.stream().distinct().count() <= 1);
500         LocalDateTime creationDate = fromDate(creationDates.get(0));
501         assertFalse(creationDate.isBefore(startTestDate));
502         assertFalse(creationDate.isAfter(endTestDate));
503     }
504
505     @DataProvider
506     public static Object[][] msoToJobStatusDataProvider() {
507         return new Object[][]{
508                 {"IN_PROGRESS", JobStatus.IN_PROGRESS},
509                 {"INPROGRESS", JobStatus.IN_PROGRESS},
510                 {"IN ProGREsS", JobStatus.IN_PROGRESS},
511                 {"JAMES_HARDEN", JobStatus.IN_PROGRESS},
512                 {"FAILED", JobStatus.FAILED},
513                 {"COMpleTE", JobStatus.COMPLETED},
514                 {"PENDING", JobStatus.IN_PROGRESS},
515                 {"Paused", JobStatus.PAUSE},
516                 {"Pause", JobStatus.PAUSE},
517                 {"PENDING_MANUAL_TASK", JobStatus.PAUSE},
518                 {"UNLOCKED", JobStatus.IN_PROGRESS}
519         };
520     }
521
522     @Test(dataProvider = "msoToJobStatusDataProvider")
523     void whenGetStatusFromMso_calcRightJobStatus(String msoStatus, Job.JobStatus expectedJobStatus) {
524         AsyncRequestStatus asyncRequestStatus = asyncRequestStatusResponse(msoStatus);
525         assertThat(asyncInstantiationBL.calcStatus(asyncRequestStatus), equalTo(expectedJobStatus));
526     }
527
528     private void createNewAuditStatus(JobAuditStatus auditStatus)
529     {
530         Date createdDate= auditStatus.getCreated();
531         dataAccessService.saveDomainObject(auditStatus, getPropsMap());
532         setDateToStatus(auditStatus.getSource(), auditStatus.getJobStatus(), createdDate);
533     }
534
535
536
537     private static final String MSO_ARBITRARY_STATUS = "completed mso status";
538
539     @DataProvider
540     public static Object[][] auditStatuses(Method test) {
541         return new Object[][]{
542                 {
543                         SourceStatus.VID,
544                         new String[]{ JobStatus.PENDING.toString(), JobStatus.IN_PROGRESS.toString()}
545                 },
546                 {       SourceStatus.MSO,
547                         new String[]{ JobStatus.IN_PROGRESS.toString(), MSO_ARBITRARY_STATUS }
548                 }
549         };
550
551     }
552
553     private void setDateToStatus(SourceStatus source, String status, Date date) {
554         List<JobAuditStatus> jobAuditStatusList = dataAccessService.getList(JobAuditStatus.class, getPropsMap());
555         DaoUtils.tryWithSessionAndTransaction(sessionFactory, session -> {
556             jobAuditStatusList.stream()
557                     .filter(auditStatus -> source.equals(auditStatus.getSource()) && status.equals(auditStatus.getJobStatus()))
558                     .forEach(auditStatus -> {
559                         auditStatus.setCreated(date);
560                         session.saveOrUpdate(auditStatus);
561                     });
562             return 1;
563         });
564     }
565
566
567     @Test(dataProvider = "auditStatuses")
568     public void givenSomeAuditStatuses_getStatusesOfSpecificSourceAndJobId_getSortedResultsMatchingToParameters(SourceStatus expectedSource, String [] expectedSortedStatuses){
569         UUID jobUuid = UUID.randomUUID();
570         List<JobAuditStatus> auditStatusList = com.google.common.collect.ImmutableList.of(
571                 new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.VID, toDate(LocalDateTime.now().minusHours(2))),
572                 new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, UUID.randomUUID(),"",toDate(LocalDateTime.now().minusHours(30))),
573                 new JobAuditStatus(jobUuid, MSO_ARBITRARY_STATUS, SourceStatus.MSO, UUID.randomUUID(),"",toDate(LocalDateTime.now().minusHours(3))),
574                 new JobAuditStatus(jobUuid, PENDING.toString(), SourceStatus.VID, toDate(LocalDateTime.now().minusHours(3))),
575                 new JobAuditStatus(UUID.randomUUID(), PENDING.toString(), SourceStatus.VID, toDate(LocalDateTime.now().minusHours(3))));
576         auditStatusList.forEach((auditStatus) -> createNewAuditStatus(auditStatus));
577         List<JobAuditStatus> statuses = asyncInstantiationBL.getAuditStatuses(jobUuid, expectedSource);
578         List<String> statusesList = statuses.stream().map(status -> status.getJobStatus()).collect(Collectors.toList());
579         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 ));
580         assertThat(statusesList, contains(expectedSortedStatuses));
581     }
582
583
584
585     @Test
586     public void addSomeVidStatuses_getThem_verifyGetInsertedWithoutDuplicates(){
587         ImmutableList<JobStatus> statusesToBeInserted = ImmutableList.of(PENDING, IN_PROGRESS, IN_PROGRESS, COMPLETED);
588         UUID jobUuid = UUID.randomUUID();
589         statusesToBeInserted.forEach(status->
590             {
591                 asyncInstantiationBL.auditVidStatus(jobUuid, status);
592             });
593         List<String> statusesFromDB = asyncInstantiationBL.getAuditStatuses(jobUuid, SourceStatus.VID).stream().map(auditStatus -> auditStatus.getJobStatus()).collect(Collectors.toList());
594         List<String> statusesWithoutDuplicates = statusesToBeInserted.stream().distinct().map(x -> x.toString()).collect(Collectors.toList());
595         assertThat(statusesFromDB, is(statusesWithoutDuplicates));
596     }
597
598     @DataProvider
599     public static Object[][] msoAuditStatuses(Method test) {
600         UUID jobUuid = UUID.randomUUID();
601         UUID requestId = UUID.randomUUID();
602         return new Object[][]{
603                 {
604                         jobUuid,
605                         ImmutableList.of(
606                                 new JobAuditStatus(jobUuid, PENDING.toString(), SourceStatus.MSO, null, null),
607                                 new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, requestId, null),
608                                 new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, requestId, null),
609                                 new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, requestId, null),
610                                 new JobAuditStatus(jobUuid, COMPLETED.toString(), SourceStatus.MSO, requestId, null)),
611                         ImmutableList.of(PENDING.toString(), IN_PROGRESS.toString(), COMPLETED.toString()),
612                         "All distinct statuses should be without duplicates"
613                 },
614                 {
615                         jobUuid,
616                         ImmutableList.of(
617                                 new JobAuditStatus(jobUuid, PENDING.toString(), SourceStatus.MSO, null, null),
618                                 new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, requestId, null),
619                                 new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, requestId, "aa"),
620                                 new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, requestId, "aa"),
621                                 new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, UUID.randomUUID(), "aa"),
622                                 new JobAuditStatus(jobUuid, COMPLETED.toString(), SourceStatus.MSO, requestId, null)),
623                         ImmutableList.of(PENDING.toString(), IN_PROGRESS.toString(), IN_PROGRESS.toString(),IN_PROGRESS.toString(), COMPLETED.toString()),
624                         "Statuses should be without duplicates only with same requestId and additionalInfo"
625
626                 }
627         };
628     }
629
630     @Test(dataProvider = "msoAuditStatuses")
631     public void addSomeMsoStatuses_getThem_verifyGetInsertedWithoutDuplicates(UUID jobUuid, ImmutableList<JobAuditStatus> msoStatuses, ImmutableList<String> expectedStatuses, String assertionReason) {
632         msoStatuses.forEach(status -> {
633             asyncInstantiationBL.auditMsoStatus(status.getJobId(), status.getJobStatus(), status.getRequestId() != null ? status.getRequestId().toString() : null, status.getAdditionalInfo());
634         });
635         List<String> statusesFromDB = asyncInstantiationBL.getAuditStatuses(jobUuid, SourceStatus.MSO).stream().map(auditStatus -> auditStatus.getJobStatus()).collect(Collectors.toList());
636         assertThat( assertionReason, statusesFromDB, is(expectedStatuses));
637     }
638
639     @Test
640     public void addSameStatusOfVidAndMso_verifyThatBothWereAdded(){
641         UUID jobUuid = UUID.randomUUID();
642         JobStatus sameStatus = IN_PROGRESS;
643         asyncInstantiationBL.auditMsoStatus(jobUuid, sameStatus.toString(),null,null);
644         asyncInstantiationBL.auditVidStatus(jobUuid, sameStatus);
645         List<JobAuditStatus> list = dataAccessService.getList(
646                 JobAuditStatus.class,
647                 String.format(" where JOB_ID = '%s'", jobUuid),
648                 null, null);
649         Assert.assertEquals(list.size(),2);
650         assertThat(list,everyItem(hasProperty("jobStatus", is(sameStatus.toString()))));
651     }
652
653     @Test
654     public void verifyAsyncRequestStatus_canBeReadFromSample() throws IOException {
655         String body = "{" +
656                 "  \"request\": {" +
657                 "    \"requestId\": \"c0011670-0e1a-4b74-945d-8bf5aede1d9c\"," +
658                 "    \"startTime\": \"Mon, 11 Dec 2017 07:27:49 GMT\"," +
659                 "    \"requestScope\": \"service\"," +
660                 "    \"requestType\": \"createInstance\"," +
661                 "    \"instanceReferences\": {" +
662                 "      \"serviceInstanceId\": \"f8791436-8d55-4fde-b4d5-72dd2cf13cfb\"," +
663                 "      \"serviceInstanceName\": \"asdfasdf234234asdf\"," +
664                 "      \"requestorId\": \"il883e\"" +
665                 "    }," +
666                 "    \"requestStatus\": {" +
667                 "      \"requestState\": \"COMPLETE\"," +
668                 "      \"statusMessage\": \"Service Instance was created successfully.\"," +
669                 "      \"percentProgress\": 100," +
670                 "      \"finishTime\": \"Mon, 11 Dec 2017 07:27:53 GMT\"" +
671                 "    }" +
672                 "  }" +
673                 "}";
674         ObjectMapper objectMapper = new ObjectMapper();
675         AsyncRequestStatus asyncRequestStatus = objectMapper.readValue(body, AsyncRequestStatus.class);
676         assertThat(asyncRequestStatus.request.requestStatus.getRequestState(), equalTo("COMPLETE"));
677
678     }
679
680     @Test
681     public void deleteJobInfo_pending_deleted() {
682         doNothing().when(jobsBrokerService).delete(any());
683         UUID uuid = createServicesInfoWithDefaultValues(PENDING);
684         asyncInstantiationBL.deleteJob(uuid);
685         assertNotNull(asyncInstantiationBL.getServiceInfoByJobId(uuid).getDeletedAt(), "service info wasn't deleted");
686     }
687
688     @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE)
689     public void deleteJobInfo_notAllowdStatus_shouldSendError() {
690         UUID uuid = createServicesInfoWithDefaultValues(COMPLETED);
691         doThrow(new IllegalStateException(DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE)).when(jobsBrokerService).delete(any());
692         try {
693             asyncInstantiationBL.deleteJob(uuid);
694         } catch (Exception e) {
695             assertNull(asyncInstantiationBL.getServiceInfoByJobId(uuid).getDeletedAt(), "service info shouldn't deleted");
696             throw e;
697         }
698     }
699
700     @DataProvider
701     public Object[][] jobStatusesFinal() {
702         return Arrays.stream(Job.JobStatus.values())
703                 .filter(t -> ImmutableList.of(COMPLETED, FAILED, STOPPED).contains(t))
704                 .map(v -> new Object[]{v}).collect(Collectors.toList()).toArray(new Object[][]{});
705     }
706
707     @Test(dataProvider = "jobStatusesFinal")
708     public void whenHideService_theServiceNotReturnedInServiceList(JobStatus jobStatus) {
709         UUID uuidToHide = createServicesInfoWithDefaultValues(jobStatus);
710         UUID uuidToShown = createServicesInfoWithDefaultValues(jobStatus);
711         List<UUID> serviceInfoList = listServicesUUID();
712         assertThat(serviceInfoList, hasItems(uuidToHide, uuidToShown));
713
714         asyncInstantiationBL.hideServiceInfo(uuidToHide);
715         serviceInfoList = listServicesUUID();
716         assertThat(serviceInfoList, hasItem(uuidToShown));
717         assertThat(serviceInfoList, not(hasItem(uuidToHide)));
718
719     }
720
721     protected List<UUID> listServicesUUID() {
722         return asyncInstantiationBL.getAllServicesInfo().stream().map(ServiceInfo::getJobId).collect(Collectors.toList());
723     }
724
725     @DataProvider
726     public Object[][] jobStatusesNotFinal() {
727         return Arrays.stream(Job.JobStatus.values())
728                 .filter(t -> ImmutableList.of(PENDING, IN_PROGRESS, PAUSE).contains(t))
729                 .map(v -> new Object[]{v}).collect(Collectors.toList()).toArray(new Object[][]{});
730     }
731
732     @Test(  dataProvider = "jobStatusesNotFinal",
733             expectedExceptions = OperationNotAllowedException.class,
734             expectedExceptionsMessageRegExp = "jobId.*Service status does not allow hide service, status = .*")
735     public void hideServiceInfo_notAllowedStatus_shouldSendError(JobStatus jobStatus) {
736         UUID uuid = createServicesInfoWithDefaultValues(jobStatus);
737         try {
738             asyncInstantiationBL.hideServiceInfo(uuid);
739         } catch (Exception e) {
740             assertFalse(asyncInstantiationBL.getServiceInfoByJobId(uuid).isHidden(), "service info shouldn't be hidden");
741             throw e;
742         }
743     }
744
745     @Test
746     public void whenUseGetCounterInMultiThreads_EachThreadGetDifferentCounter() throws InterruptedException {
747         int SIZE = 200;
748         ExecutorService executor = Executors.newFixedThreadPool(SIZE);
749         List<Callable<Integer>> tasks = IntStream.rangeClosed(1, SIZE)
750                 .mapToObj(x-> ((Callable<Integer>)() -> asyncInstantiationBL.getCounterForName("a")))
751                 .collect(Collectors.toList());
752         Set<Integer> expectedResults = IntStream.rangeClosed(1, SIZE).boxed().collect(Collectors.toSet());
753         executor.invokeAll(tasks)
754                 .forEach(future -> {
755                     try {
756                         assertTrue( expectedResults.remove(future.get()), "got unexpected counter");
757                     }
758                     catch (Exception e) {
759                         throw new RuntimeException(e);
760                     }
761                 });
762
763         assertThat(expectedResults.size(), is(0));
764     }
765
766     @Test
767     public void whenUseGetCounterForSameName_numbersReturnedByOrder() {
768
769         String name = UUID.randomUUID().toString();
770         int SIZE=10;
771         for (int i=1; i<=SIZE; i++) {
772             assertThat(asyncInstantiationBL.getCounterForName(name), is(i));
773         }
774     }
775
776     @Test
777     public void whenNamedInUsedInAai_getNextNumber() {
778         String name = someCommonStepsAndGetName();
779         ResourceType type = ResourceType.GENERIC_VNF;
780         when(aaiClient.searchNodeTypeByName(name+"_001", type)).thenReturn(aaiNodeQueryResponseNameUsed(type));
781         when(aaiClient.searchNodeTypeByName(name+"_002", type)).thenReturn(aaiNodeQueryResponseNameFree());
782         assertThat(asyncInstantiationBL.getUniqueName(name, type), equalTo(name+"_002"));
783     }
784
785     private String someCommonStepsAndGetName() {
786         mockAaiClientAaiStatusOK();
787         return UUID.randomUUID().toString();
788     }
789
790     private void mockAaiClientAaiStatusOK() {
791         when(aaiClient.searchNodeTypeByName(eq(AsyncInstantiationBusinessLogicImpl.NAME_FOR_CHECK_AAI_STATUS), any())).thenReturn(aaiNodeQueryResponseNameFree());
792     }
793
794     @Test(expectedExceptions=InvalidAAIResponseException.class)
795     public void whenAaiBadResponseCode_throwInvalidAAIResponseException() {
796         String name = someCommonStepsAndGetName();
797         ResourceType type = ResourceType.SERVICE_INSTANCE;
798         when(aaiClient.searchNodeTypeByName(name+"_001", type)).thenReturn(aaiNodeQueryBadResponse());
799         asyncInstantiationBL.getUniqueName(name, type);
800     }
801
802     @Test(expectedExceptions=MaxRetriesException.class)
803     public void whenAaiAlwaysReturnNameUsed_throwInvalidAAIResponseException() {
804         String name = someCommonStepsAndGetName();
805         ResourceType type = ResourceType.VF_MODULE;
806         when(aaiClient.searchNodeTypeByName(any(), eq(type))).thenReturn(aaiNodeQueryResponseNameUsed(type));
807         asyncInstantiationBL.setMaxRetriesGettingFreeNameFromAai(10);
808         asyncInstantiationBL.getUniqueName(name, type);
809     }
810
811     @Test
812     public void testFormattingOfNameAndCounter() {
813         AsyncInstantiationBusinessLogicImpl bl = (AsyncInstantiationBusinessLogicImpl) asyncInstantiationBL;
814         assertThat(bl.formatNameAndCounter("x", 3), equalTo("x_003"));
815         assertThat(bl.formatNameAndCounter("x", 99), equalTo("x_099"));
816         assertThat(bl.formatNameAndCounter("x", 100), equalTo("x_100"));
817         assertThat(bl.formatNameAndCounter("x", 1234), equalTo("x_1234"));
818     }*/
819 }