1 package org.onap.vid.services;
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.*;
51 import javax.inject.Inject;
52 import java.io.IOException;
53 import java.lang.reflect.Method;
55 import java.time.Instant;
56 import java.time.LocalDateTime;
57 import java.time.ZoneId;
58 import java.util.Optional;
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;
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.*;
77 @ContextConfiguration(classes = {DataSourceConfig.class, SystemProperties.class, MockedAaiClientAndFeatureManagerConfig.class})
78 public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseTest {
81 private DataAccessService dataAccessService;
84 private JobAdapter jobAdapterMock;
87 private JobsBrokerService jobsBrokerServiceMock;
91 private SessionFactory sessionFactory;
93 private AsyncInstantiationBusinessLogicImpl asyncInstantiationBL;
95 private int serviceCount = 0;
97 private static final String UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE =
98 "Failed to retrieve job with uuid .* from ServiceInfo table. Instances found: .*";
100 private static final String DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE =
101 "Service status does not allow deletion from the queue";
104 void initServicesInfoService() {
105 MockitoAnnotations.initMocks(this);
106 asyncInstantiationBL = new AsyncInstantiationBusinessLogicImpl(dataAccessService, jobAdapterMock, jobsBrokerServiceMock, sessionFactory, aaiClient, featureManager, cloudOwnerService);
107 createInstanceParamsMaps();
112 Mockito.reset(aaiClient);
113 Mockito.reset(jobAdapterMock);
114 Mockito.reset(jobsBrokerServiceMock);
115 mockAaiClientAnyNameFree();
116 enableAddCloudOwnerOnMsoRequest();
119 private void enableAddCloudOwnerOnMsoRequest() {
120 enableAddCloudOwnerOnMsoRequest(true);
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");
130 void resetServiceCount() {
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());
143 private void createNewTestServicesInfoForFilter(String userId) {
144 LocalDateTime createdDate, modifiedDate;
145 LocalDateTime NOW = LocalDateTime.now();
149 uuid = UUID.randomUUID();
151 createdDate = NOW.minusYears(1);
152 addNewServiceInfo(uuid, userId, "Old", createdDate, createdDate, COMPLETED, false);
154 uuid = UUID.randomUUID();
156 createdDate = NOW.minusDays(20);
157 modifiedDate = NOW.minusDays(19);
158 addNewServiceInfo(uuid, userId, "Hidden", createdDate, modifiedDate, PAUSE, true);
160 createNewTestServicesInfo(String.valueOf(userId));
163 private void createNewTestServicesInfo(String userId) {
165 LocalDateTime createdDate, modifiedDate;
166 LocalDateTime NOW = LocalDateTime.now();
169 uuid = UUID.randomUUID();
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);
176 uuid = UUID.randomUUID();
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);
185 modifiedDate = NOW.minusDays(19);
186 addNewServiceInfo(uuid, userId, "service instance 1", createdDate, modifiedDate, FAILED, false);
189 // Job to a different user
190 uuid = UUID.randomUUID();
193 createdDate = NOW.minusMonths(2);
194 addNewServiceInfo(uuid, "2221", "service instance 7", createdDate, createdDate, COMPLETED, false);
198 private UUID createServicesInfoWithDefaultValues(Job.JobStatus status) {
200 LocalDateTime NOW = LocalDateTime.now();
203 uuid = UUID.randomUUID();
204 addNewJob(uuid, status);
206 addNewServiceInfo(uuid, null, "service instance 1", NOW, NOW, status, false);
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;
219 private static Date toDate(LocalDateTime localDateTime) {
220 return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
223 private LocalDateTime fromDate(Date date) {
224 return Instant.ofEpochMilli(date.getTime())
225 .atZone(ZoneId.systemDefault())
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));
240 serviceInfo.setHidden(isHidden);
241 dataAccessService.saveDomainObject(serviceInfo, getPropsMap());
242 setCreateDateToServiceInfo(uuid, createDate);
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);
260 private void addNewJob(UUID uuid) {
261 addNewJob(uuid, null);
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());
271 @Test(enabled = false)
272 public void testServiceInfoAreOrderedAsExpected() {
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));
280 @Test(enabled = false)
281 public void testServiceInfoAreFilteredAsExpected() {
283 createNewTestServicesInfoForFilter(String.valueOf(userId));
284 List<ServiceInfo> expectedOrderServiceInfo = getFullList();
286 List<ServiceInfo> expectedFilterByUser = expectedOrderServiceInfo.stream().filter(x ->
287 !x.getServiceInstanceName().equals("Old") && !x.getServiceInstanceName().equals("Hidden")
289 ).collect(Collectors.toList());
292 List<ServiceInfo> serviceInfoFilteredByUser = asyncInstantiationBL.getAllServicesInfo();
293 assertThat("Services aren't ordered filtered as expected", serviceInfoFilteredByUser, equalTo(expectedFilterByUser));
296 @Test(enabled = false, dataProvider = "pauseAndInstanceParams")
297 public void createMacroServiceInstantiationMsoRequestUniqueName(Boolean isPause, HashMap<String, String> vfModuleInstanceParamsMap, List vnfInstanceParams) throws Exception {
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]);
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();
313 when(featureManager.isActive(Features.FLAG_SHIFT_VFMODULE_PARAMS_TO_VNF)).thenReturn(true);
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);
339 protected void verifySearchNodeTypeByName(String unique, String resourceName, ResourceType serviceInstance) {
340 verify(aaiClient, times(1)).isNodeTypeExistsByName(resourceName + unique, serviceInstance);
343 private HashMap<String, Object> getPropsMap() {
344 HashMap<String, Object> props = new HashMap<>();
345 props.put(FusionObject.Parameters.PARAM_USERID, 0);
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("", "", "")},
358 @Test(enabled = false, dataProvider="dataProviderForInstanceNames")
359 public void pushBulkJob_bulkWithSize3_instancesNamesAreExactlyAsExpected(boolean isUserProvidedNaming, List<String> expectedNames) {
362 final ServiceInstantiation request = generateMockMacroServiceInstantiationPayload(
364 createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true),
365 bulkSize, isUserProvidedNaming, PROJECT_NAME, true
368 // in "createServiceInstantiationJob()" we will probe the service, with the generated names
369 configureMockitoWithMockedJob();
372 asyncInstantiationBL.pushBulkJob(request, "myUserId");
374 List<ServiceInfo> serviceInfoList = dataAccessService.getList(ServiceInfo.class, getPropsMap());
375 assertEquals(serviceInfoList.stream().map(ServiceInfo::getServiceInstanceName).collect(Collectors.toList()), expectedNames);
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);
383 final ServiceInstantiation asObject = mapper.readValue(asString, ServiceInstantiation.class);
384 final String asString2 = mapper.writeValueAsString(asObject);
386 JsonAssert.assertJsonEquals(asString, asString2);
390 public Object[][] aLaCarteAndMacroPayload() {
391 ServiceInstantiation macroPayload = generateMockMacroServiceInstantiationPayload(
393 createVnfList(instanceParamsMapWithoutParams, ImmutableList.of(vnfInstanceParamsMapWithParamsToRemove, vnfInstanceParamsMapWithParamsToRemove), true),
394 2, false,PROJECT_NAME, false);
395 ServiceInstantiation aLaCartePayload = generateALaCarteServiceInstantiationPayload();
397 return new Object[][]{
403 public static class ServiceInfoComparator implements Comparator<ServiceInfo> {
406 public int compare(ServiceInfo o1, ServiceInfo o2) {
409 compare = o1.getCreatedBulkDate().compareTo(o2.getCreatedBulkDate());
414 // check jobStatus priority
415 int o1Priority = getPriority(o1);
416 int o2Priority = getPriority(o2);
417 compare = o1Priority - o2Priority;
422 // check statusModifiedDate
423 return o1.getStatusModifiedDate().compareTo(o2.getStatusModifiedDate());
426 private int getPriority(ServiceInfo o) throws JSONException {
427 Job.JobStatus status = o.getJobStatus();
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)}
454 private ServiceInstantiation generateMacroMockServiceInstantiationPayload(boolean isPause, Map<String, Vnf> vnfs) {
455 return generateMockMacroServiceInstantiationPayload(isPause, vnfs, 1, true, PROJECT_NAME, false);
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);
466 Optional<ServiceInfo> optionalServiceInfo = getJobById(uuid);
467 assertThat(optionalServiceInfo.get().getServiceInstanceName(), equalTo(STEPH_CURRY));
468 assertThat(optionalServiceInfo.get().getJobStatus(), equalTo(Job.JobStatus.IN_PROGRESS));
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();
476 private UUID createFakedJobAndServiceInfo() {
477 UUID uuid = UUID.randomUUID();
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());
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"));
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"));
503 public static Object[][] isPauseAndPropertyDataProvider() {
504 return new Object[][]{
505 {true, "mso.restapi.serviceInstanceAssign"},
506 {false, "mso.restapi.serviceInstanceCreate"},
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));
518 @Test(enabled = false)
519 public void testCreateVnfEndpoint_useProvidedInstanceId() {
520 String path = asyncInstantiationBL.getVnfInstantiationPath("myGreatId");
521 assertThat(path, equalTo("/serviceInstances/v7/myGreatId/vnfs"));
524 @Test(enabled = false)
525 public void createServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected() throws IOException {
526 createMacroServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(true);
529 @Test(enabled = false)
530 public void createServiceInfo_WithUserProvidedNamingFalseAndNoVfmodules_ServiceInfoIsAsExpected() throws IOException {
531 createMacroServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(false);
534 private void createMacroServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(boolean withVfmodules) throws IOException {
535 when(featureManager.isActive(Features.FLAG_SHIFT_VFMODULE_PARAMS_TO_VNF)).thenReturn(true);
537 ServiceInstantiation serviceInstantiationPayload = generateMockMacroServiceInstantiationPayload(true,
538 createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, Collections.EMPTY_LIST, false),
540 false, PROJECT_NAME, true);
543 resource = this.getClass().getResource("/payload_jsons/bulk_service_request_ecomp_naming.json");
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");
550 RequestDetailsWrapper<ServiceInstantiationRequestDetails> result =
551 asyncInstantiationBL.generateMacroServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016");
553 String expected = IOUtils.toString(resource, "UTF-8");
554 MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
557 @Test(enabled = false)
558 public void createALaCarteService_WithUserProvidedNamingFalse_RequestDetailsIsAsExpected() throws IOException {
559 ServiceInstantiation serviceInstantiationPayload = generateMockALaCarteServiceInstantiationPayload(false,
564 false, PROJECT_NAME, true, null);
566 RequestDetailsWrapper<ServiceInstantiationRequestDetails> result =
567 asyncInstantiationBL.generateALaCarteServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016");
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);
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");
580 String serviceExpected = IOUtils.toString(this.getClass().getResource("/payload_jsons/bulk_alacarte_service_request.json"), "UTF-8");
581 MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(serviceExpected, result);
584 @Test(enabled = false, dataProvider = "createVnfParameters")
585 public void createVnfRequestDetails_detailsAreAsExpected(boolean isFlagAddCloudOwnerActive, boolean isUserProvidedNaming, String file) throws IOException {
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";
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);
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);
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"},
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"}
622 @Test(enabled = false, dataProvider = "vfModuleRequestDetails")
623 public void createVfModuleRequestDetails_detailsAreAsExpected(String volumeGroupInstanceId, boolean isUserProvidedNaming, String fileName) throws IOException {
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);
635 String serviceInstanceId = "aa3514e3-5a33-55df-13ab-12abad84e7aa";
636 String vnfInstanceId = "bb3514e3-5a33-55df-13ab-12abad84e7bb";
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);
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);
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()},
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));
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"}
677 @Test(enabled = false, dataProvider = "expectedNetworkRequestDetailsParameters")
678 public void createNetworkRequestDetails_detailsAreAsExpected(boolean isUserProvidedNaming, String filePath) throws IOException {
680 final List<Network> networksList = new ArrayList<>(createNetworkList(null, isUserProvidedNaming, true).values());
681 ModelInfo siModelInfo = createServiceModelInfo();
682 String serviceInstanceId = "aa3514e3-5a33-55df-13ab-12abad84e7aa";
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);
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);
695 @Test(enabled = false)
696 public void createInstanceGroupRequestDetails_detailsAreAsExpected() throws IOException {
698 final InstanceGroup instanceGroup = createInstanceGroup(true, Action.Create);
699 ModelInfo siModelInfo = createServiceModelInfo();
700 String serviceInstanceId = "aa3514e3-5a33-55df-13ab-12abad84e7aa";
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);
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);
713 @Test(enabled = false)
714 public void checkIfNullProjectNameSentToMso(){
715 ServiceInstantiation serviceInstantiationPayload = generateMockMacroServiceInstantiationPayload(true,
716 createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, Collections.EMPTY_LIST, 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),
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"));
735 @Test(enabled = false)
736 public void pushBulkJob_macroServiceverifyCreatedDateBehavior_createdDateIsTheSameForAllServicesInSameBulk() {
737 LocalDateTime startTestDate = LocalDateTime.now().withNano(0);
738 final ServiceInstantiation request = generateMockMacroServiceInstantiationPayload(
740 createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true),
741 100, true,PROJECT_NAME, true
744 pushJobAndAssertDates(startTestDate, request);
747 @Test(enabled = false)
748 public void whenCreateServiceInfo_thenModelId_isModelVersionId() {
749 ServiceInfo serviceInfo = asyncInstantiationBL.createServiceInfo("userID",
750 generateALaCarteWithVnfsServiceInstantiationPayload(),
754 "myName", ServiceInfo.ServiceAction.INSTANTIATE);
755 assertEquals(SERVICE_MODEL_VERSION_ID, serviceInfo.getServiceModelId());
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);
766 protected void pushJobAndAssertDates(LocalDateTime startTestDate, ServiceInstantiation request) {
767 // in "createServiceInstantiationJob()" we will probe the service, with the generated names
768 configureMockitoWithMockedJob();
770 asyncInstantiationBL.pushBulkJob(request, "myUserId");
771 List<ServiceInfo> serviceInfoList = dataAccessService.getList(ServiceInfo.class, getPropsMap());
773 List<Date> creationDates = new ArrayList<>();
774 for (ServiceInfo serviceInfo : serviceInfoList) {
775 creationDates.add(serviceInfo.getCreatedBulkDate());
777 LocalDateTime endTestDate = LocalDateTime.now();
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));
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);
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}
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));
816 private void createNewAuditStatus(JobAuditStatus auditStatus)
818 Date createdDate= auditStatus.getCreated();
819 dataAccessService.saveDomainObject(auditStatus, getPropsMap());
820 setDateToStatus(auditStatus.getSource(), auditStatus.getJobStatus(), createdDate);
825 private static final String MSO_ARBITRARY_STATUS = "completed mso status";
828 public static Object[][] auditStatuses(Method test) {
829 return new Object[][]{
832 new String[]{ JobStatus.PENDING.toString(), JobStatus.IN_PROGRESS.toString()}
835 new String[]{ JobStatus.IN_PROGRESS.toString(), MSO_ARBITRARY_STATUS }
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);
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));
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->
879 asyncInstantiationBL.auditVidStatus(jobUuid, status);
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));
887 public static Object[][] msoAuditStatuses(Method test) {
888 UUID jobUuid = UUID.randomUUID();
889 UUID requestId = UUID.randomUUID();
890 return new Object[][]{
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"
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"
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());
923 List<String> statusesFromDB = asyncInstantiationBL.getAuditStatuses(jobUuid, SourceStatus.MSO).stream().map(auditStatus -> auditStatus.getJobStatus()).collect(Collectors.toList());
924 assertThat( assertionReason, statusesFromDB, is(expectedStatuses));
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),
937 Assert.assertEquals(list.size(),2);
938 assertThat(list,everyItem(hasProperty("jobStatus", is(sameStatus.toString()))));
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"}
950 @Test(enabled = false, dataProvider="msoRequestStatusFiles")
951 public void verifyAsyncRequestStatus_canBeReadFromSample(String msoResponseFile) throws IOException {
952 AsyncRequestStatus asyncRequestStatus = TestUtils.readJsonResourceFileAsObject(
954 AsyncRequestStatus.class);
955 assertThat(asyncRequestStatus.request.requestStatus.getRequestState(), equalTo("COMPLETE"));
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");
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());
971 asyncInstantiationBL.deleteJob(uuid);
972 } catch (Exception e) {
973 assertNull(asyncInstantiationBL.getServiceInfoByJobId(uuid).getDeletedAt(), "service info shouldn't deleted");
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[][]{});
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));
992 asyncInstantiationBL.hideServiceInfo(uuidToHide);
993 serviceInfoList = listServicesUUID();
994 assertThat(serviceInfoList, hasItem(uuidToShown));
995 assertThat(serviceInfoList, not(hasItem(uuidToHide)));
999 protected List<UUID> listServicesUUID() {
1000 return asyncInstantiationBL.getAllServicesInfo().stream().map(ServiceInfo::getJobId).collect(Collectors.toList());
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[][]{});
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);
1016 asyncInstantiationBL.hideServiceInfo(uuid);
1017 } catch (Exception e) {
1018 assertFalse(asyncInstantiationBL.getServiceInfoByJobId(uuid).isHidden(), "service info shouldn't be hidden");
1023 @Test(enabled = false)
1024 public void whenUseGetCounterInMultiThreads_EachThreadGetDifferentCounter() throws InterruptedException {
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 -> {
1034 assertTrue( expectedResults.remove(future.get()), "got unexpected counter");
1036 catch (Exception e) {
1037 throw new RuntimeException(e);
1041 assertThat(expectedResults.size(), is(0));
1044 @Test(enabled = false)
1045 public void whenUseGetCounterForSameName_numbersReturnedByOrder() {
1047 String name = UUID.randomUUID().toString();
1049 for (int i=0; i<SIZE; i++) {
1050 assertThat(asyncInstantiationBL.getCounterForName(name), is(i));
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"));
1063 private String someCommonStepsAndGetName() {
1064 mockAaiClientAaiStatusOK();
1065 return UUID.randomUUID().toString();
1068 private void mockAaiClientAaiStatusOK() {
1069 when(aaiClient.isNodeTypeExistsByName(eq(AsyncInstantiationBusinessLogicImpl.NAME_FOR_CHECK_AAI_STATUS), any())).thenReturn(false);
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);
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);
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"));
1099 @Test(enabled = false)
1100 public void pushBulkJob_verifyAlacarteFlow_useALaCartServiceInstantiationJobType(){
1101 final ServiceInstantiation request = generateALaCarteServiceInstantiationPayload();
1103 // in "createServiceInstantiationJob()" we will probe the service, with the generated names
1104 configureMockitoWithMockedJob();
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));
1112 @Test(enabled = false)
1113 public void pushBulkJob_verifyMacroFlow_useMacroServiceInstantiationJobType(){
1114 final ServiceInstantiation request = generateMacroMockServiceInstantiationPayload(false, Collections.emptyMap());
1116 // in "createServiceInstantiationJob()" we will probe the service, with the generated names
1117 configureMockitoWithMockedJob();
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));
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);
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");
1140 ServiceInstantiation serviceDeletionPayload = generateALaCarteServiceDeletionPayload();
1141 RequestDetailsWrapper<ServiceDeletionRequestDetails> result =
1142 asyncInstantiationBL.generateALaCarteServiceDeletionRequest(null, serviceDeletionPayload, "az2016");
1144 MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
1147 @Test(enabled = false)
1148 public void getALaCarteServiceDeletionPath_verifyPathIsAsExpected() throws IOException {
1150 String expected = "/serviceInstantiation/v7/serviceInstances/f36f5734-e9df-4fbf-9f35-61be13f028a1";
1152 String result = asyncInstantiationBL.getServiceDeletionPath("f36f5734-e9df-4fbf-9f35-61be13f028a1");
1154 assertThat(expected,equalTo(result));
1157 @Test(enabled = false)
1158 public void getInstanceGroupsDeletionPath_verifyPathIsAsExpected() {
1160 assertEquals(asyncInstantiationBL.getInstanceGroupDeletePath("9aada4af-0f9b-424f-ae21-e693bd3e005b"),
1161 "/serviceInstantiation/v7/instanceGroups/9aada4af-0f9b-424f-ae21-e693bd3e005b");
1165 public static Object[][] testBuildVnfInstanceParamsDataProvider(Method test) {
1166 return new Object[][]{
1168 Collections.EMPTY_LIST,
1170 ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2")),
1171 ImmutableList.of(ImmutableMap.of("k3","v3","k2","v2"))
1174 ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2","k3","v3"))
1177 ImmutableList.of(ImmutableMap.of("j1", "w1", "k1","v1", "vnf_name","w2", "vf_module_name","w3")), //vnf_name, vf_module_name are excluded
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)
1185 ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2","k3","v3","j1", "w1"))
1188 Collections.EMPTY_LIST,
1189 Arrays.asList(null, null),
1191 Collections.EMPTY_LIST //mso is expect to empty list and not list with empty map
1194 ImmutableList.of(Collections.EMPTY_MAP),
1196 ImmutableList.of(Collections.EMPTY_MAP),
1197 ImmutableList.of(Collections.EMPTY_MAP)
1200 Collections.EMPTY_LIST //mso is expect to empty list and not list with empty map
1203 Collections.EMPTY_LIST,
1205 ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2")),
1206 ImmutableList.of(ImmutableMap.of("k3","v3","k2","v2"))
1209 Collections.EMPTY_LIST //mso is expect to empty list and not list with empty map
1212 ImmutableList.of(ImmutableMap.of("j1", "w1", "k1","v1", "vnf_name","w2", "vf_module_name","w3")),
1214 ImmutableList.of(Collections.EMPTY_MAP)
1217 ImmutableList.of(ImmutableMap.of("j1", "w1", "k1","v1"))
1220 ImmutableList.of(ImmutableMap.of("vnf_name","w2", "vf_module_name", "w3", "j2", "w2", "j4","w4")),
1222 ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2")),
1223 ImmutableList.of(ImmutableMap.of("k3","v3","k2","v2"))
1226 ImmutableList.of(ImmutableMap.of("j2", "w2", "j4","w4"))
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));
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));
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));
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",
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",
1284 String expected = IOUtils.toString(resource, "UTF-8");
1285 MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
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));
1307 protected ServiceInstantiation generateALaCarteServiceInstantiationPayload() {
1308 return generateMockALaCarteServiceInstantiationPayload(false, Collections.EMPTY_MAP, Collections.EMPTY_MAP, Collections.EMPTY_MAP, 1, true, PROJECT_NAME, false, "VNF_API");
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");
1315 static class MockedJob implements Job {
1317 private static Map<UUID, MockedJob> uuidToJob = new HashMap<>();
1319 public static void putJob(UUID uuid, MockedJob job) {
1320 uuidToJob.put(uuid, job);
1323 public static MockedJob getJob(UUID uuid) {
1324 return uuidToJob.get(uuid);
1328 private String optimisticUniqueServiceInstanceName;
1330 public MockedJob(String optimisticUniqueServiceInstanceName) {
1331 this.optimisticUniqueServiceInstanceName = optimisticUniqueServiceInstanceName;
1334 private UUID uuid = UUID.randomUUID();
1337 public UUID getUuid() {
1342 public void setUuid(UUID uuid) {
1347 public JobStatus getStatus() {
1348 return JobStatus.PENDING;
1352 public void setStatus(JobStatus status) {
1357 public Map<String, Object> getData() {
1362 public JobSharedData getSharedData() {
1363 return new JobSharedData(uuid, "", null);
1367 public void setTypeAndData(JobType jobType, Map<String, Object> commandData) {
1372 public UUID getTemplateId() {
1377 public void setTemplateId(UUID templateId) {
1382 public Integer getIndexInBulk() {
1387 public void setIndexInBulk(Integer indexInBulk) {
1392 public JobType getType() {
1396 public String getOptimisticUniqueServiceInstanceName() {
1397 return optimisticUniqueServiceInstanceName;