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