2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.vid.services;
23 import static net.javacrumbs.jsonunit.JsonAssert.assertJsonEquals;
24 import static net.javacrumbs.jsonunit.JsonAssert.whenIgnoringPaths;
25 import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals;
26 import static net.javacrumbs.jsonunit.JsonMatchers.jsonPartEquals;
27 import static net.javacrumbs.jsonunit.core.Option.IGNORING_ARRAY_ORDER;
28 import static org.hamcrest.MatcherAssert.assertThat;
29 import static org.hamcrest.Matchers.allOf;
30 import static org.hamcrest.Matchers.containsInAnyOrder;
31 import static org.hamcrest.Matchers.containsString;
32 import static org.hamcrest.Matchers.hasItem;
33 import static org.hamcrest.Matchers.hasItems;
34 import static org.hamcrest.Matchers.hasProperty;
35 import static org.hamcrest.Matchers.hasSize;
36 import static org.hamcrest.Matchers.is;
37 import static org.hamcrest.Matchers.matchesPattern;
38 import static org.hamcrest.Matchers.not;
39 import static org.hamcrest.Matchers.nullValue;
40 import static org.hamcrest.core.Every.everyItem;
41 import static org.hamcrest.core.IsEqual.equalTo;
42 import static org.mockito.ArgumentMatchers.any;
43 import static org.mockito.ArgumentMatchers.anyInt;
44 import static org.mockito.ArgumentMatchers.anyString;
45 import static org.mockito.ArgumentMatchers.eq;
46 import static org.mockito.Mockito.doNothing;
47 import static org.mockito.Mockito.doReturn;
48 import static org.mockito.Mockito.doThrow;
49 import static org.mockito.Mockito.mock;
50 import static org.mockito.Mockito.reset;
51 import static org.mockito.Mockito.spy;
52 import static org.mockito.Mockito.times;
53 import static org.mockito.Mockito.verify;
54 import static org.mockito.Mockito.when;
55 import static org.onap.vid.job.Job.JobStatus.COMPLETED;
56 import static org.onap.vid.job.Job.JobStatus.COMPLETED_WITH_ERRORS;
57 import static org.onap.vid.job.Job.JobStatus.COMPLETED_WITH_NO_ACTION;
58 import static org.onap.vid.job.Job.JobStatus.FAILED;
59 import static org.onap.vid.job.Job.JobStatus.IN_PROGRESS;
60 import static org.onap.vid.job.Job.JobStatus.PAUSE;
61 import static org.onap.vid.job.Job.JobStatus.PENDING;
62 import static org.onap.vid.job.Job.JobStatus.STOPPED;
63 import static org.onap.vid.testUtils.TestUtils.generateRandomAlphaNumeric;
64 import static org.onap.vid.utils.KotlinUtilsKt.JACKSON_OBJECT_MAPPER;
65 import static org.testng.Assert.assertEquals;
66 import static org.testng.Assert.assertFalse;
67 import static org.testng.Assert.assertNotNull;
68 import static org.testng.Assert.assertNull;
69 import static org.testng.Assert.assertTrue;
71 import com.fasterxml.jackson.core.JsonProcessingException;
72 import com.fasterxml.jackson.databind.ObjectMapper;
73 import com.google.common.collect.ImmutableList;
74 import com.google.common.collect.ImmutableMap;
75 import java.io.IOException;
76 import java.lang.reflect.Method;
78 import java.time.Instant;
79 import java.time.LocalDate;
80 import java.time.LocalDateTime;
81 import java.time.ZoneId;
82 import java.time.ZonedDateTime;
83 import java.util.ArrayList;
84 import java.util.Arrays;
85 import java.util.Collections;
86 import java.util.Comparator;
87 import java.util.Date;
88 import java.util.HashMap;
89 import java.util.HashSet;
90 import java.util.List;
92 import java.util.Optional;
94 import java.util.UUID;
95 import java.util.concurrent.Callable;
96 import java.util.concurrent.ExecutorService;
97 import java.util.concurrent.Executors;
98 import java.util.stream.Collectors;
99 import java.util.stream.IntStream;
100 import org.apache.commons.io.IOUtils;
101 import org.apache.commons.lang3.time.DateUtils;
102 import org.jetbrains.annotations.NotNull;
103 import org.json.JSONException;
104 import org.mockito.ArgumentCaptor;
105 import org.mockito.Mock;
106 import org.mockito.Mockito;
107 import org.mockito.MockitoAnnotations;
108 import org.mockito.stubbing.Answer;
109 import org.onap.portalsdk.core.util.SystemProperties;
110 import org.onap.vid.aai.ExceptionWithRequestInfo;
111 import org.onap.vid.aai.model.ResourceType;
112 import org.onap.vid.changeManagement.RequestDetailsWrapper;
113 import org.onap.vid.config.DataSourceConfig;
114 import org.onap.vid.config.MockedAaiClientAndFeatureManagerConfig;
115 import org.onap.vid.dal.AsyncInstantiationRepository;
116 import org.onap.vid.exceptions.MaxRetriesException;
117 import org.onap.vid.exceptions.NotFoundException;
118 import org.onap.vid.exceptions.OperationNotAllowedException;
119 import org.onap.vid.job.Job;
120 import org.onap.vid.job.Job.JobStatus;
121 import org.onap.vid.job.JobAdapter;
122 import org.onap.vid.job.JobType;
123 import org.onap.vid.job.JobsBrokerService;
124 import org.onap.vid.job.command.MsoRequestBuilder;
125 import org.onap.vid.job.command.ResourceCommandTest.FakeResourceCreator;
126 import org.onap.vid.job.impl.JobDaoImpl;
127 import org.onap.vid.job.impl.JobSharedData;
128 import org.onap.vid.model.Action;
129 import org.onap.vid.model.JobAuditStatus;
130 import org.onap.vid.model.NameCounter;
131 import org.onap.vid.model.ResourceInfo;
132 import org.onap.vid.model.ServiceInfo;
133 import org.onap.vid.model.serviceInstantiation.BaseResource;
134 import org.onap.vid.model.serviceInstantiation.ServiceInstantiation;
135 import org.onap.vid.model.serviceInstantiation.Vnf;
136 import org.onap.vid.mso.MsoOperationalEnvironmentTest;
137 import org.onap.vid.mso.RestObject;
138 import org.onap.vid.mso.model.ModelInfo;
139 import org.onap.vid.mso.model.ServiceInstantiationRequestDetails;
140 import org.onap.vid.mso.rest.AsyncRequestStatus;
141 import org.onap.vid.mso.rest.RequestStatus;
142 import org.onap.vid.properties.Features;
143 import org.onap.vid.testUtils.TestUtils;
144 import org.onap.vid.utils.DaoUtils;
145 import org.onap.vid.utils.TimeUtils;
146 import org.springframework.test.context.ContextConfiguration;
147 import org.testng.Assert;
148 import org.testng.annotations.AfterMethod;
149 import org.testng.annotations.BeforeClass;
150 import org.testng.annotations.BeforeMethod;
151 import org.testng.annotations.DataProvider;
152 import org.testng.annotations.Test;
154 @ContextConfiguration(classes = {DataSourceConfig.class, SystemProperties.class, MockedAaiClientAndFeatureManagerConfig.class})
155 public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseTest {
158 private JobAdapter jobAdapterMock;
161 private JobsBrokerService jobsBrokerServiceMock;
163 private AsyncInstantiationRepository asyncInstantiationRepository;
165 private AuditService auditService;
168 private AsyncInstantiationBusinessLogicImpl asyncInstantiationBL;
170 protected MsoRequestBuilder msoRequestBuilder;
172 private static final String UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE =
173 "Failed to retrieve class .*ServiceInfo with jobId .* from table. no resource found";
175 private static final String DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE =
176 "Service status does not allow deletion from the queue";
178 private String uuidRegex = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
179 private org.hamcrest.Matcher uuidRegexMatcher = is(matchesPattern(uuidRegex));
183 void initServicesInfoService() {
184 MockitoAnnotations.initMocks(this);
185 doReturn(false).when(featureManager).isActive(Features.FLAG_DISABLE_HOMING);
186 AsyncInstantiationRepository realAsyncInstantiationRepository = new AsyncInstantiationRepository(dataAccessService);
187 asyncInstantiationRepository = spy(realAsyncInstantiationRepository);
189 auditService = new AuditServiceImpl(null, asyncInstantiationRepository);
191 AsyncInstantiationBusinessLogicImpl realAsyncInstantiationBL = new AsyncInstantiationBusinessLogicImpl(jobAdapterMock, jobsBrokerServiceMock, sessionFactory, aaiClient, featureManager, cloudOwnerService, asyncInstantiationRepository, auditService);
192 asyncInstantiationBL = Mockito.spy(realAsyncInstantiationBL);
194 msoRequestBuilder = new MsoRequestBuilder(asyncInstantiationBL, cloudOwnerService, aaiClient, featureManager);
196 createInstanceParamsMaps();
201 Mockito.reset(aaiClient);
202 Mockito.reset(jobAdapterMock);
203 Mockito.reset(jobsBrokerServiceMock);
204 Mockito.reset(asyncInstantiationRepository);
205 mockAaiClientAnyNameFree();
206 enableAddCloudOwnerOnMsoRequest();
210 void resetServiceCount() {
216 dataAccessService.deleteDomainObjects(JobDaoImpl.class, "1=1", getPropsMap());
217 dataAccessService.deleteDomainObjects(ServiceInfo.class, "1=1", getPropsMap());
218 dataAccessService.deleteDomainObjects(JobAuditStatus.class, "1=1", getPropsMap());
219 dataAccessService.deleteDomainObjects(NameCounter.class, "1=1", getPropsMap());
223 private void createNewTestServicesInfoForFilter(String userId) {
224 LocalDateTime createdDate, modifiedDate;
225 LocalDateTime NOW = LocalDateTime.now();
229 uuid = UUID.randomUUID();
231 createdDate = NOW.minusYears(1);
232 addNewServiceInfo(uuid, userId, "Old", createdDate, createdDate, COMPLETED, false, false,
235 uuid = UUID.randomUUID();
237 createdDate = NOW.minusDays(20);
238 modifiedDate = NOW.minusDays(19);
239 addNewServiceInfo(uuid, userId, "Hidden", createdDate, modifiedDate, PAUSE, true, false,
242 createNewTestServicesInfo(String.valueOf(userId));
245 private void createNewTestServicesInfo(String userId) {
247 LocalDateTime createdDate, modifiedDate;
248 LocalDateTime NOW = LocalDateTime.now();
251 uuid = UUID.randomUUID();
254 createdDate = NOW.minusDays(40);
255 addNewServiceInfo(uuid, userId, "service instance 5", createdDate, createdDate, COMPLETED, false, false,
257 addNewServiceInfo(uuid, userId, "service instance 6", createdDate, createdDate, STOPPED, false, false,
260 uuid = UUID.randomUUID();
263 createdDate = NOW.minusDays(20);
264 modifiedDate = NOW.minusDays(10);
265 addNewServiceInfo(uuid, userId, "service instance 4", createdDate, modifiedDate, STOPPED, false, false,
267 addNewServiceInfo(uuid, userId, "service instance 2", createdDate, modifiedDate, COMPLETED, false, false,
269 addNewServiceInfo(uuid, userId, "service instance 3", createdDate, modifiedDate, PAUSE, false, false,
272 modifiedDate = NOW.minusDays(19);
273 addNewServiceInfo(uuid, userId, "service instance 1", createdDate, modifiedDate, FAILED, false, false,
277 // Job to a different user
278 uuid = UUID.randomUUID();
281 createdDate = NOW.minusMonths(2);
282 addNewServiceInfo(uuid, "2221", "service instance 7", createdDate, createdDate, COMPLETED, false, false,
289 private UUID createServicesInfoWithDefaultValues(Job.JobStatus status) {
291 LocalDateTime NOW = LocalDateTime.now();
294 uuid = UUID.randomUUID();
295 addNewJob(uuid, status);
297 addNewServiceInfo(uuid, null, "service instance 1", NOW, NOW, status, false, false,
304 private List<ServiceInfo> getFullList() {
305 List<ServiceInfo> expectedOrderServiceInfo = dataAccessService.getList(ServiceInfo.class, getPropsMap());
306 assertThat("Failed to retrieve all predefined services", expectedOrderServiceInfo.size(), equalTo(serviceCount));
307 expectedOrderServiceInfo.sort(new ServiceInfoComparator());
308 return expectedOrderServiceInfo;
313 private LocalDateTime fromDate(Date date) {
314 return Instant.ofEpochMilli(date.getTime())
315 .atZone(ZoneId.systemDefault())
319 private void setCreateDateToServiceInfo(UUID jobUuid, LocalDateTime createDate) {
320 List<ServiceInfo> serviceInfoList = dataAccessService.getList(ServiceInfo.class, getPropsMap());
321 DaoUtils.tryWithSessionAndTransaction(sessionFactory, session -> {
322 serviceInfoList.stream()
323 .filter(serviceInfo -> jobUuid.equals(serviceInfo.getJobId()))
324 .forEach(serviceInfo -> {
325 serviceInfo.setCreated(toDate(createDate));
326 session.saveOrUpdate(serviceInfo);
332 private void addNewJob(UUID uuid) {
333 addNewJob(uuid, null);
336 private void addNewJob(UUID uuid, Job.JobStatus status) {
337 JobDaoImpl jobDao = new JobDaoImpl();
338 jobDao.setUuid(uuid);
339 jobDao.setStatus(status);
340 dataAccessService.saveDomainObject(jobDao, getPropsMap());
343 private ServiceInstantiation addOriginalService(UUID jobId, String userID){
344 addNewServiceInfo(jobId, userID, "name", LocalDateTime.now(), LocalDateTime.now(), COMPLETED_WITH_ERRORS, false,
347 assertThat(asyncInstantiationRepository.getServiceInfoByJobId(jobId).isRetryEnabled(), is(true));
348 ServiceInstantiation originalServiceInstantiation = prepareServiceInstantiation(true, 1);
349 doReturn(originalServiceInstantiation).when(asyncInstantiationRepository).getJobRequest(jobId);
350 return originalServiceInstantiation;
353 private void assertRetryDisabled(UUID jobId){
354 assertThat(asyncInstantiationRepository.getServiceInfoByJobId(jobId).isRetryEnabled(), is(false));
357 private void assertNewJobExistsAsExpectedAfterRetry(List<UUID> newJobIds, ServiceInstantiation expectedServiceInstantiation, UUID jobId, String userId){
358 assertThat(newJobIds, hasSize(1));
359 assertThat(newJobIds.get(0), not(equalTo(jobId)));
361 ArgumentCaptor<ServiceInstantiation> requestsCaptor = ArgumentCaptor.forClass(ServiceInstantiation.class);
362 ArgumentCaptor<UUID> uuidsCaptor = ArgumentCaptor.forClass(UUID.class);
363 ArgumentCaptor<JobType> jobTypeCaptor = ArgumentCaptor.forClass(JobType.class);
365 verify(asyncInstantiationRepository).addJobRequest(uuidsCaptor.capture(), requestsCaptor.capture());
366 verify(jobAdapterMock).createServiceInstantiationJob(jobTypeCaptor.capture(), requestsCaptor.capture(), uuidsCaptor.capture(), eq(userId), any(), anyString(), anyInt());
367 verify(jobsBrokerServiceMock).add(any());
369 requestsCaptor.getAllValues().forEach(x->assertJsonEquals(expectedServiceInstantiation, x, whenIgnoringPaths(
371 "vnfs.2016-73_MOW-AVPN-vPE-BV-L.trackById",
372 "vnfs.2016-73_MOW-AVPN-vPE-BV-L.vfModules.201673MowAvpnVpeBvL..AVPN_base_vPE_BV..module-0.201673MowAvpnVpeBvL..AVPN_base_vPE_BV..module-0:001.trackById",
373 "vnfs.2016-73_MOW-AVPN-vPE-BV-L.vfModules.201673MowAvpnVpeBvL..AVPN_base_vPE_BV..module-0.201673MowAvpnVpeBvL..AVPN_base_vPE_BV..module-0:002.trackById"
379 public void testServiceInfoAreOrderedAsExpected() {
381 createNewTestServicesInfo(String.valueOf(userId));
382 List<ServiceInfo> expectedOrderServiceInfo = getFullList();
383 List<ServiceInfo> serviceInfoListResult = asyncInstantiationBL.getAllServicesInfo();
384 assertThat("Services aren't ordered as expected", serviceInfoListResult, equalTo(expectedOrderServiceInfo));
388 public void whenNewServiceInfoCreated_isRetryEnablesIsFalse() {
389 UUID uuid = createServicesInfoWithDefaultValues(PENDING);
390 assertFalse(asyncInstantiationRepository.getServiceInfoByJobId(uuid).isRetryEnabled());
394 public void testServiceInfoAreFilteredAsExpected() {
396 createNewTestServicesInfoForFilter(String.valueOf(userId));
397 List<ServiceInfo> expectedOrderServiceInfo = getFullList();
399 List<ServiceInfo> expectedFilterByUser = expectedOrderServiceInfo.stream().filter(x ->
400 !x.getServiceInstanceName().equals("Old") && !x.getServiceInstanceName().equals("Hidden")
402 ).collect(Collectors.toList());
405 List<ServiceInfo> serviceInfoFilteredByUser = asyncInstantiationBL.getAllServicesInfo();
406 assertThat("Services aren't ordered filtered as expected", serviceInfoFilteredByUser, equalTo(expectedFilterByUser));
409 @Test(dataProvider = "pauseAndInstanceParams")
410 public void createMacroServiceInstantiationMsoRequestUniqueName(Boolean isPause, HashMap<String, String> vfModuleInstanceParamsMap, List vnfInstanceParams) throws Exception {
412 ServiceInstantiation serviceInstantiationPayload = generateMockMacroServiceInstantiationPayload(isPause, createVnfList(vfModuleInstanceParamsMap, vnfInstanceParams, true), 2, true, PROJECT_NAME, false);
413 final URL resource = this.getClass().getResource("/payload_jsons/bulk_service_request_unique_names.json");
414 when(jobAdapterMock.createServiceInstantiationJob(any(), any(), any(), any(), any(), anyString(), any())).thenAnswer(invocation -> {
415 Object[] args = invocation.getArguments();
416 return new MockedJob((String)args[5]);
419 when(jobsBrokerServiceMock.add(any(MockedJob.class))).thenAnswer((Answer<UUID>) invocation -> {
420 Object[] args = invocation.getArguments();
421 MockedJob job = (MockedJob) args[0];
422 MockedJob.putJob(job.uuid, job);
423 return job.getUuid();
426 when(asyncInstantiationBL.isPartOfBulk(any())).thenReturn(true);
428 List<UUID> uuids = asyncInstantiationBL.pushBulkJob(serviceInstantiationPayload, "az2016");
429 for (int i = 0; i < 2; i++) {
430 UUID currentUuid = uuids.get(i);
431 RequestDetailsWrapper<ServiceInstantiationRequestDetails> result =
432 msoRequestBuilder.generateMacroServiceInstantiationRequest(currentUuid, serviceInstantiationPayload,
433 MockedJob.getJob(currentUuid).getOptimisticUniqueServiceInstanceName(), "az2016");
434 String unique = i==0 ? "" : String.format("_00%s", i);
435 String expected = IOUtils.toString(resource, "UTF-8")
436 .replace("{SERVICE_UNIQENESS}", unique)
437 .replace("{VNF_UNIQENESS}", unique)
438 .replace("{VF_MODULE_UNIQENESS}", unique)
439 .replace("{VF_MODULE_2_UNIQENESS}", unique)
440 .replace("{VG_UNIQUENESS}", unique);
441 MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
442 Optional<ServiceInfo> optionalServiceInfo = getJobById(currentUuid);
443 assertThat(optionalServiceInfo.get().getServiceInstanceName(), equalTo("vPE_Service" + unique));
444 verifySearchNodeTypeByName(unique, "vPE_Service", ResourceType.SERVICE_INSTANCE);
445 verifySearchNodeTypeByName(unique, VNF_NAME, ResourceType.GENERIC_VNF);
446 verifySearchNodeTypeByName(unique, "vmxnjr001_AVPN_base_vPE_BV_base", ResourceType.VF_MODULE);
447 verifySearchNodeTypeByName(unique, "vmxnjr001_AVPN_base_vRE_BV_expansion", ResourceType.VF_MODULE);
448 verifySearchNodeTypeByName(unique, "myVgName", ResourceType.VOLUME_GROUP);
452 protected void verifySearchNodeTypeByName(String unique, String resourceName, ResourceType serviceInstance) {
453 String uniqueName = resourceName + unique;
454 verify(aaiClient, times(1)).isNodeTypeExistsByName(uniqueName, serviceInstance);
455 when(aaiClient.isNodeTypeExistsByName(uniqueName, serviceInstance)).thenReturn(true);
462 public static Object[][] dataProviderForInstanceNames() {
463 return new Object[][]{
464 {true, ImmutableList.of("vPE_Service", "vPE_Service_001", "vPE_Service_002")},
465 {false, ImmutableList.of("", "", "")},
469 @Test(dataProvider="dataProviderForInstanceNames")
470 public void pushBulkJob_bulkWithSize3_instancesNamesAreExactlyAsExpected(boolean isUserProvidedNaming, List<String> expectedNames) {
471 final ServiceInstantiation request = prepareServiceInstantiation(isUserProvidedNaming, 3);
474 asyncInstantiationBL.pushBulkJob(request, "myUserId");
476 List<ServiceInfo> serviceInfoList = dataAccessService.getList(ServiceInfo.class, getPropsMap());
477 assertEquals(serviceInfoList.stream().map(ServiceInfo::getServiceInstanceName).collect(Collectors.toList()), expectedNames);
480 protected ServiceInstantiation prepareServiceInstantiation(String projectName, boolean isUserProvidedNaming, int bulkSize) {
481 final ServiceInstantiation request = generateMockMacroServiceInstantiationPayload(
483 createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true),
484 bulkSize, isUserProvidedNaming, projectName, true
487 // in "createServiceInstantiationJob()" we will probe the service, with the generated names
488 configureMockitoWithMockedJob();
492 protected ServiceInstantiation prepareServiceInstantiation(boolean isUserProvidedNaming, int bulkSize) {
493 return prepareServiceInstantiation(PROJECT_NAME, isUserProvidedNaming, bulkSize);
497 public static Object[][] dataProviderSummarizedMap() {
498 return new Object[][]{
499 {"/payload_jsons/templateSummarize4vnfs6vfmodules.json", ImmutableMap.of("vnf", 4L, "vfModule", 6L, "volumeGroup", 1L, "network", 2L)},
500 {"/payload_jsons/templateSummarize3Vnfs8Vfmodule2VolumeGroups.json", ImmutableMap.of("vnf", 3L, "vfModule", 8L, "volumeGroup", 2L)},
501 {"/payload_jsons/templateSummarize3Networks.json", ImmutableMap.of("network", 3L)},
506 @Test(dataProvider = "dataProviderSummarizedMap")
507 public void summarizedChildrenMap_givenServiceInstantiation_yieldCorrectMap(String pathInResource, Map<String, Long> expectedMap){
508 ServiceInstantiation serviceInstantiation = TestUtils.readJsonResourceFileAsObject(
509 pathInResource, ServiceInstantiation.class);
510 Map<String, Long> childrenMap = asyncInstantiationBL.summarizedChildrenMap(serviceInstantiation);
511 assertEquals(childrenMap,expectedMap);
515 public void requestSummaryOrNull_givenActionWhichIsNotCreate_yieldNullRegardlessOfPayload(){
516 ServiceInstantiation serviceInstantiation = mock(ServiceInstantiation.class);
518 when(serviceInstantiation.getAction()).thenReturn(Action.Upgrade);
519 when(featureManager.isActive(Features.FLAG_2004_CREATE_ANOTHER_INSTANCE_FROM_TEMPLATE)).thenReturn(true);
521 assertThat(asyncInstantiationBL.requestSummaryOrNull(serviceInstantiation), is(nullValue()));
525 public void whenPushBulkJob_thenJobRequestIsSaveInJobRequestDb() {
526 Mockito.reset(asyncInstantiationRepository);
528 final ServiceInstantiation request = prepareServiceInstantiation(true, bulkSize);
529 when(jobsBrokerServiceMock.add(any())).thenReturn(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID());
530 List<UUID> jobIds = asyncInstantiationBL.pushBulkJob(request, "abc");
532 ArgumentCaptor<JobAdapter.AsyncJobRequest> asyncJobRequestCaptor = ArgumentCaptor.forClass(JobAdapter.AsyncJobRequest.class);
533 ArgumentCaptor<ServiceInstantiation> requestsCaptor = ArgumentCaptor.forClass(ServiceInstantiation.class);
534 ArgumentCaptor<UUID> uuidsCaptor = ArgumentCaptor.forClass(UUID.class);
535 verify(asyncInstantiationRepository, times(bulkSize)).addJobRequest(uuidsCaptor.capture(), requestsCaptor.capture());
536 verify(jobsBrokerServiceMock, times(bulkSize)).add(any());
537 verify(jobAdapterMock, times(bulkSize)).createServiceInstantiationJob(any(), asyncJobRequestCaptor.capture(), any(), any(), any(), any(), any());
539 //verify that all for each job we saved an row in jobRequest table
540 assertThat(uuidsCaptor.getAllValues(), containsInAnyOrder(jobIds.toArray()));
542 //assert that each real job we created with the adaptor, request is save in jobRequest table
543 assertThat(requestsCaptor.getAllValues(), containsInAnyOrder(asyncJobRequestCaptor.getAllValues().toArray()));
545 assertThat(requestsCaptor.getAllValues(),everyItem(hasProperty("bulkSize", is(1))));
547 //assert that the requests that save in DB are the same as original request expect of the trackById
548 requestsCaptor.getAllValues().forEach(x->assertJsonEquals(request, x, whenIgnoringPaths(
551 "vnfs.2016-73_MOW-AVPN-vPE-BV-L.trackById",
552 "vnfs.2016-73_MOW-AVPN-vPE-BV-L.vfModules.201673MowAvpnVpeBvL..AVPN_base_vPE_BV..module-0.201673MowAvpnVpeBvL..AVPN_base_vPE_BV..module-0:001.trackById",
553 "vnfs.2016-73_MOW-AVPN-vPE-BV-L.vfModules.201673MowAvpnVpeBvL..AVPN_base_vPE_BV..module-0.201673MowAvpnVpeBvL..AVPN_base_vPE_BV..module-0:002.trackById"
556 //assert that each trackById on all bulk jobs is unique
557 Set<String> usedUUID = new HashSet<>();
558 requestsCaptor.getAllValues().forEach(x->assertTrackByIdRecursively(x, uuidRegexMatcher, usedUUID));
562 public void whenRetryJob_prevJobRetryIsDisabled() {
563 reset(asyncInstantiationRepository);
564 UUID jobId = UUID.randomUUID();
565 String userID = generateRandomAlphaNumeric(8);
566 addOriginalService(jobId, userID);
567 doReturn(mock(Map.class)).when(asyncInstantiationRepository).getResourceInfoByRootJobId(jobId);
568 asyncInstantiationBL.retryJob(jobId, userID);
569 assertRetryDisabled(jobId);
573 public void whenRetryJobWithEditedData_prevJobRetryIsDisabled() {
574 reset(asyncInstantiationRepository);
575 UUID jobId = UUID.randomUUID();
576 String userID = generateRandomAlphaNumeric(8);
577 addOriginalService(jobId, userID);
578 ServiceInstantiation editedServiceInstantiation = prepareServiceInstantiation("editedProjectName", true, 1);
579 asyncInstantiationBL.retryJob(editedServiceInstantiation, jobId, userID);
580 assertRetryDisabled(jobId);
584 public void retryJobWithEditedData_expectedNewJobDifferentData() {
585 reset(asyncInstantiationRepository);
586 UUID jobId = UUID.randomUUID();
587 String userID = generateRandomAlphaNumeric(8);
588 addOriginalService(jobId, userID);
589 ServiceInstantiation editedServiceInstantiation = prepareServiceInstantiation("editedProjectName", true, 1);
590 List<UUID> newJobIds = asyncInstantiationBL.retryJob(editedServiceInstantiation, jobId, userID);
591 assertNewJobExistsAsExpectedAfterRetry(newJobIds, editedServiceInstantiation, jobId, userID);
595 public void retryJob_expectedNewJob() {
596 reset(asyncInstantiationRepository);
597 UUID jobId = UUID.randomUUID();
598 String userID = "az2016";
599 ServiceInstantiation originalServiceInstantiation = addOriginalService(jobId, userID);
600 doReturn(mock(Map.class)).when(asyncInstantiationRepository).getResourceInfoByRootJobId(jobId);
601 List<UUID> newJobIds = asyncInstantiationBL.retryJob(jobId, userID);
602 assertNewJobExistsAsExpectedAfterRetry(newJobIds, originalServiceInstantiation, jobId, userID);
605 @Test (dataProvider = "aLaCarteAndMacroPayload")
606 public void generateMockServiceInstantiationPayload_serializeBackAndForth_sourceShouldBeTheSame(ServiceInstantiation serviceInstantiationPayload) throws IOException {
607 ObjectMapper mapper = new ObjectMapper();
608 final String asString = mapper.writeValueAsString(serviceInstantiationPayload);
610 final ServiceInstantiation asObject = mapper.readValue(asString, ServiceInstantiation.class);
611 final String asString2 = mapper.writeValueAsString(asObject);
613 assertJsonEquals(asString, asString2);
617 public Object[][] aLaCarteAndMacroPayload() {
618 ServiceInstantiation macroPayload = generateMockMacroServiceInstantiationPayload(
620 createVnfList(instanceParamsMapWithoutParams, ImmutableList.of(vnfInstanceParamsMapWithParamsToRemove, vnfInstanceParamsMapWithParamsToRemove), true),
621 2, false,PROJECT_NAME, false);
622 ServiceInstantiation aLaCartePayload = generateALaCarteServiceInstantiationPayload();
624 return new Object[][]{
630 public static class ServiceInfoComparator implements Comparator<ServiceInfo> {
633 public int compare(ServiceInfo o1, ServiceInfo o2) {
636 compare = o1.getCreatedBulkDate().compareTo(o2.getCreatedBulkDate());
641 // check jobStatus priority
642 int o1Priority = getPriority(o1);
643 int o2Priority = getPriority(o2);
644 compare = o1Priority - o2Priority;
649 // check statusModifiedDate
650 return o1.getStatusModifiedDate().compareTo(o2.getStatusModifiedDate());
653 private int getPriority(ServiceInfo o) throws JSONException {
654 Job.JobStatus status = o.getJobStatus();
673 public Object[][] pauseAndInstanceParams() {
674 return new Object[][]{
675 {Boolean.TRUE, instanceParamsMapWithoutParams, Collections.EMPTY_LIST},
676 {Boolean.FALSE, instanceParamsMapWithoutParams, Collections.EMPTY_LIST},
677 {Boolean.TRUE, vfModuleInstanceParamsMapWithParamsToRemove, Collections.singletonList(vnfInstanceParamsMapWithParamsToRemove)}
682 public void testUpdateServiceInfo_WithExistingServiceInfo_ServiceInfoIsUpdated() {
683 UUID uuid = createFakedJobAndServiceInfo();
684 final String STEPH_CURRY = "Steph Curry";
685 asyncInstantiationBL.updateServiceInfo(uuid, x -> {
686 x.setServiceInstanceName(STEPH_CURRY);
687 x.setJobStatus(Job.JobStatus.IN_PROGRESS);
689 Optional<ServiceInfo> optionalServiceInfo = getJobById(uuid);
690 assertThat(optionalServiceInfo.get().getServiceInstanceName(), equalTo(STEPH_CURRY));
691 assertThat(optionalServiceInfo.get().getJobStatus(), equalTo(Job.JobStatus.IN_PROGRESS));
694 private Optional<ServiceInfo> getJobById(UUID jobId) {
695 List<ServiceInfo> serviceInfoList = dataAccessService.getList(ServiceInfo.class, null);
696 return serviceInfoList.stream().filter(x -> jobId.equals(x.getJobId())).findFirst();
699 private UUID createFakedJobAndServiceInfo() {
700 UUID uuid = UUID.randomUUID();
702 ServiceInfo serviceInfo = new ServiceInfo();
703 serviceInfo.setServiceInstanceName("Lebron James");
704 serviceInfo.setJobId(uuid);
705 serviceInfo.setJobStatus(Job.JobStatus.PENDING);
706 dataAccessService.saveDomainObject(serviceInfo, getPropsMap());
710 @Test(expectedExceptions = NotFoundException.class, expectedExceptionsMessageRegExp = UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE)
711 public void testUpdateServiceInfo_WithNonExisting_ThrowException() {
712 asyncInstantiationBL.updateServiceInfo(UUID.randomUUID(), x -> x.setServiceInstanceName("not matter"));
715 @Test(expectedExceptions = NotFoundException.class, expectedExceptionsMessageRegExp = UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE)
716 public void testUpdateServiceInfo_WithDoubleServiceWithSameJobUuid_ThrowException() {
717 UUID uuid = createFakedJobAndServiceInfo();
718 ServiceInfo serviceInfo = new ServiceInfo();
719 serviceInfo.setJobId(uuid);
720 dataAccessService.saveDomainObject(serviceInfo, getPropsMap());
721 asyncInstantiationBL.updateServiceInfo(UUID.randomUUID(), x -> x.setServiceInstanceName("not matter"));
726 public static Object[][] isPauseAndPropertyDataProvider() {
727 return new Object[][]{
728 {true, "mso.restapi.serviceInstanceAssign"},
729 {false, "mso.restapi.service.instance"},
734 @Test(dataProvider = "isPauseAndPropertyDataProvider")
735 public void testServiceInstantiationPath_RequestPathIsAsExpected(boolean isPause, String expectedProperty) {
736 ServiceInstantiation serviceInstantiationPauseFlagTrue = generateMacroMockServiceInstantiationPayload(isPause, createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true));
737 String path = asyncInstantiationBL.getServiceInstantiationPath(serviceInstantiationPauseFlagTrue);
738 Assert.assertEquals(path, SystemProperties.getProperty(expectedProperty));
742 public void testCreateVnfEndpoint_useProvidedInstanceId() {
743 String path = asyncInstantiationBL.getVnfInstantiationPath("myGreatId");
744 assertThat(path, equalTo("/serviceInstantiation/v7/serviceInstances/myGreatId/vnfs"));
750 public void pushBulkJob_macroServiceverifyCreatedDateBehavior_createdDateIsTheSameForAllServicesInSameBulk() {
751 LocalDateTime startTestDate = LocalDateTime.now().withNano(0);
752 final ServiceInstantiation request = generateMockMacroServiceInstantiationPayload(
754 createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true),
755 100, true,PROJECT_NAME, true
758 pushJobAndAssertDates(startTestDate, request);
762 public void whenCreateServiceInfo_thenModelId_isModelVersionId() {
763 ServiceInfo serviceInfo = asyncInstantiationBL.createServiceInfo("userID",
764 generateALaCarteWithVnfsServiceInstantiationPayload(),
768 "myName", ServiceInfo.ServiceAction.INSTANTIATE, null);
769 assertEquals(SERVICE_MODEL_VERSION_ID, serviceInfo.getServiceModelId());
774 public void pushBulkJob_aLaCarteServiceverifyCreatedDateBehavior_createdDateIsTheSameForAllServicesInSameBulk() {
775 LocalDateTime startTestDate = LocalDateTime.now().withNano(0);
776 final ServiceInstantiation request = generateALaCarteServiceInstantiationPayload();
777 pushJobAndAssertDates(startTestDate, request);
780 protected void pushJobAndAssertDates(LocalDateTime startTestDate, ServiceInstantiation request) {
781 // in "createServiceInstantiationJob()" we will probe the service, with the generated names
782 configureMockitoWithMockedJob();
784 asyncInstantiationBL.pushBulkJob(request, "myUserId");
785 List<ServiceInfo> serviceInfoList = dataAccessService.getList(ServiceInfo.class, getPropsMap());
787 List<Date> creationDates = new ArrayList<>();
788 for (ServiceInfo serviceInfo : serviceInfoList) {
789 creationDates.add(serviceInfo.getCreatedBulkDate());
791 LocalDateTime endTestDate = LocalDateTime.now();
793 //creation date of all services is the same
794 Assert.assertTrue(creationDates.stream().distinct().count() <= 1);
795 LocalDateTime creationDate = fromDate(creationDates.get(0));
796 assertFalse(creationDate.isBefore(startTestDate));
797 assertFalse(creationDate.isAfter(endTestDate));
800 protected void configureMockitoWithMockedJob() {
801 Mockito.reset(jobAdapterMock);
802 final Job job = mock(Job.class);
803 when(job.getStatus()).thenReturn(PENDING);
804 when(job.getUuid()).thenReturn(UUID.fromString("db2c5ed9-1c19-41ce-9cb7-edf0d878cdeb"));
805 when(jobAdapterMock.createServiceInstantiationJob(any(), any(), any(), any(), any(), any(), any())).thenReturn(job);
806 when(jobsBrokerServiceMock.add(job)).thenReturn(UUID.randomUUID());
810 public static Object[][] msoToJobStatusDataProvider() {
811 return new Object[][]{
812 {"IN_PROGRESS", JobStatus.IN_PROGRESS},
813 {"INPROGRESS", JobStatus.IN_PROGRESS},
814 {"IN ProGREsS", JobStatus.IN_PROGRESS},
815 {"JAMES_HARDEN", JobStatus.IN_PROGRESS},
816 {"FAILED", JobStatus.FAILED},
817 {"COMpleTE", JobStatus.COMPLETED},
818 {"PENDING", JobStatus.IN_PROGRESS},
819 {"Paused", JobStatus.PAUSE},
820 {"Pause", JobStatus.PAUSE},
821 {"PENDING_MANUAL_TASK", JobStatus.PAUSE},
822 {"UNLOCKED", JobStatus.IN_PROGRESS},
823 {"AbORtEd", COMPLETED_WITH_ERRORS},
824 {"RoLlED_baCK", FAILED},
825 {"ROllED_BAcK_To_ASsIGnED", FAILED},
826 {"rOLLED_bACK_tO_CrEATeD", FAILED},
830 @Test(dataProvider = "msoToJobStatusDataProvider")
831 public void whenGetStatusFromMso_calcRightJobStatus(String msoStatus, Job.JobStatus expectedJobStatus) {
832 AsyncRequestStatus asyncRequestStatus = asyncRequestStatusResponse(msoStatus);
833 assertThat(asyncInstantiationBL.calcStatus(asyncRequestStatus), equalTo(expectedJobStatus));
837 public static Object[][] msoRequestStatusFiles(Method test) {
838 return new Object[][]{
839 {"/responses/mso/orchestrationRequestsServiceInstance.json"},
840 {"/responses/mso/orchestrationRequestsVnf.json"},
841 {"/responses/mso/orchestrationRequestsMockedMinimalResponse.json"}
845 @Test(dataProvider="msoRequestStatusFiles")
846 public void verifyAsyncRequestStatus_canBeReadFromSample(String msoResponseFile) throws IOException {
847 AsyncRequestStatus asyncRequestStatus = TestUtils.readJsonResourceFileAsObject(
849 AsyncRequestStatus.class);
850 assertThat(asyncRequestStatus.request.requestStatus.getRequestState(), equalTo("COMPLETE"));
854 public void deleteJobInfo_pending_deleted() {
855 doNothing().when(jobsBrokerServiceMock).delete(any());
856 UUID uuid = createServicesInfoWithDefaultValues(PENDING);
857 asyncInstantiationBL.deleteJob(uuid);
858 assertNotNull(asyncInstantiationRepository.getServiceInfoByJobId(uuid).getDeletedAt(), "service info wasn't deleted");
861 @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE)
862 public void deleteJobInfo_notAllowdStatus_shouldSendError() {
863 UUID uuid = createServicesInfoWithDefaultValues(COMPLETED);
864 doThrow(new IllegalStateException(DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE)).when(jobsBrokerServiceMock).delete(any());
866 asyncInstantiationBL.deleteJob(uuid);
867 } catch (Exception e) {
868 assertNull(asyncInstantiationRepository.getServiceInfoByJobId(uuid).getDeletedAt(), "service info shouldn't deleted");
874 public Object[][] jobStatusesFinal() {
875 return Arrays.stream(Job.JobStatus.values())
876 .filter(t -> ImmutableList.of(COMPLETED, FAILED, STOPPED).contains(t))
877 .map(v -> new Object[]{v}).collect(Collectors.toList()).toArray(new Object[][]{});
880 @Test(dataProvider = "jobStatusesFinal")
881 public void whenHideService_theServiceNotReturnedInServiceList(JobStatus jobStatus) {
882 UUID uuidToHide = createServicesInfoWithDefaultValues(jobStatus);
883 UUID uuidToShown = createServicesInfoWithDefaultValues(jobStatus);
884 List<UUID> serviceInfoList = listServicesUUID();
885 assertThat(serviceInfoList, hasItems(uuidToHide, uuidToShown));
887 asyncInstantiationBL.hideServiceInfo(uuidToHide);
888 serviceInfoList = listServicesUUID();
889 assertThat(serviceInfoList, hasItem(uuidToShown));
890 assertThat(serviceInfoList, not(hasItem(uuidToHide)));
894 protected List<UUID> listServicesUUID() {
895 return asyncInstantiationBL.getAllServicesInfo().stream().map(ServiceInfo::getJobId).collect(Collectors.toList());
899 public Object[][] jobStatusesNotFinal() {
900 return Arrays.stream(Job.JobStatus.values())
901 .filter(t -> ImmutableList.of(PENDING, IN_PROGRESS, PAUSE).contains(t))
902 .map(v -> new Object[]{v}).collect(Collectors.toList()).toArray(new Object[][]{});
905 @Test(dataProvider = "jobStatusesNotFinal",
906 expectedExceptions = OperationNotAllowedException.class,
907 expectedExceptionsMessageRegExp = "jobId.*Service status does not allow hide service, status = .*")
908 public void hideServiceInfo_notAllowedStatus_shouldSendError(JobStatus jobStatus) {
909 UUID uuid = createServicesInfoWithDefaultValues(jobStatus);
911 asyncInstantiationBL.hideServiceInfo(uuid);
912 } catch (Exception e) {
913 assertFalse(asyncInstantiationRepository.getServiceInfoByJobId(uuid).isHidden(), "service info shouldn't be hidden");
919 public void whenUseGetCounterInMultiThreads_EachThreadGetDifferentCounter() throws InterruptedException {
921 ExecutorService executor = Executors.newFixedThreadPool(SIZE);
922 List<Callable<Integer>> tasks = IntStream.rangeClosed(0, SIZE)
923 .mapToObj(x-> ((Callable<Integer>)() -> asyncInstantiationBL.getCounterForName("a")))
924 .collect(Collectors.toList());
925 Set<Integer> expectedResults = IntStream.rangeClosed(0, SIZE).boxed().collect(Collectors.toSet());
926 executor.invokeAll(tasks)
929 assertTrue( expectedResults.remove(future.get()), "got unexpected counter");
931 catch (Exception e) {
932 throw new RuntimeException(e);
936 assertThat(expectedResults.size(), is(0));
940 public void whenUseGetCounterForSameName_numbersReturnedByOrder() {
942 String name = UUID.randomUUID().toString();
944 for (int i=0; i<SIZE; i++) {
945 assertThat(asyncInstantiationBL.getCounterForName(name), is(i));
950 public void whenNamedInUsedInAai_getNextNumber() {
951 String name = someCommonStepsAndGetName();
952 ResourceType type = ResourceType.GENERIC_VNF;
953 when(aaiClient.isNodeTypeExistsByName(name, type)).thenReturn(true);
954 when(aaiClient.isNodeTypeExistsByName(name+"_001", type)).thenReturn(false);
955 assertThat(asyncInstantiationBL.getUniqueName(name, type), equalTo(name+"_001"));
958 @Test(enabled = false) //skip till we will handle macro bulk again...
959 public void whenNamedNotInUsedInAai_getSameNameTwice() {
960 String name = someCommonStepsAndGetName();
961 ResourceType type = ResourceType.GENERIC_VNF;
962 when(aaiClient.isNodeTypeExistsByName(name, type)).thenReturn(false);
963 assertThat(asyncInstantiationBL.getUniqueName(name, type), equalTo(name));
964 assertThat(asyncInstantiationBL.getUniqueName(name, type), equalTo(name));
965 when(aaiClient.isNodeTypeExistsByName(name, type)).thenReturn(true);
966 assertThat(asyncInstantiationBL.getUniqueName(name, type), equalTo(name+"_001"));
969 private String someCommonStepsAndGetName() {
970 mockAaiClientAaiStatusOK();
971 return UUID.randomUUID().toString();
974 @Test(expectedExceptions= ExceptionWithRequestInfo.class)
975 public void whenAaiBadResponseCode_throwInvalidAAIResponseException() {
976 String name = someCommonStepsAndGetName();
977 ResourceType type = ResourceType.SERVICE_INSTANCE;
978 when(aaiClient.isNodeTypeExistsByName(name, type)).thenThrow(aaiNodeQueryBadResponseException());
979 asyncInstantiationBL.getUniqueName(name, type);
982 @Test(expectedExceptions=MaxRetriesException.class)
983 public void whenAaiAlwaysReturnNameUsed_throwInvalidAAIResponseException() {
984 String name = someCommonStepsAndGetName();
985 ResourceType type = ResourceType.VF_MODULE;
986 when(aaiClient.isNodeTypeExistsByName(any(), eq(type))).thenReturn(true);
987 asyncInstantiationBL.setMaxRetriesGettingFreeNameFromAai(10);
988 asyncInstantiationBL.getUniqueName(name, type);
992 public void testFormattingOfNameAndCounter() {
993 AsyncInstantiationBusinessLogicImpl bl = (AsyncInstantiationBusinessLogicImpl) asyncInstantiationBL;
994 assertThat(bl.formatNameAndCounter("x", 0), equalTo("x"));
995 assertThat(bl.formatNameAndCounter("x", 3), equalTo("x_003"));
996 assertThat(bl.formatNameAndCounter("x", 99), equalTo("x_099"));
997 assertThat(bl.formatNameAndCounter("x", 100), equalTo("x_100"));
998 assertThat(bl.formatNameAndCounter("x", 1234), equalTo("x_1234"));
1002 public void pushBulkJob_verifyAlacarteFlow_useALaCartServiceInstantiationJobType(){
1003 final ServiceInstantiation request = generateALaCarteServiceInstantiationPayload();
1005 // in "createServiceInstantiationJob()" we will probe the service, with the generated names
1006 configureMockitoWithMockedJob();
1008 ArgumentCaptor<JobType> argumentCaptor = ArgumentCaptor.forClass(JobType.class);
1009 asyncInstantiationBL.pushBulkJob(request, "myUserId");
1010 verify(jobAdapterMock).createServiceInstantiationJob(argumentCaptor.capture(),any(),any(),anyString(), anyString(), anyString(), anyInt());
1011 assertTrue(argumentCaptor.getValue().equals(JobType.ALaCarteServiceInstantiation));
1015 public void pushBulkJob_verifyMacroFlow_useMacroServiceInstantiationJobType(){
1016 final ServiceInstantiation request = generateMacroMockServiceInstantiationPayload(false, Collections.emptyMap());
1018 // in "createServiceInstantiationJob()" we will probe the service, with the generated names
1019 configureMockitoWithMockedJob();
1021 ArgumentCaptor<JobType> argumentCaptor = ArgumentCaptor.forClass(JobType.class);
1022 asyncInstantiationBL.pushBulkJob(request, "myUserId");
1023 verify(jobAdapterMock).createServiceInstantiationJob(argumentCaptor.capture(),any(),any(),anyString(), any(), anyString(), anyInt());
1024 assertTrue(argumentCaptor.getValue().equals(JobType.MacroServiceInstantiation));
1030 public void getALaCarteServiceDeletionPath_verifyPathIsAsExpected() {
1032 String expected = "/serviceInstantiation/v7/serviceInstances/f36f5734-e9df-4fbf-9f35-61be13f028a1";
1034 String result = asyncInstantiationBL.getServiceDeletionPath("f36f5734-e9df-4fbf-9f35-61be13f028a1");
1036 assertThat(expected,equalTo(result));
1040 public void getResumeRequestPath_verifyPathIsAsExpected() {
1042 String expected = "/orchestrationRequests/v7/rq1234d1-5a33-55df-13ab-12abad84e333/resume";
1044 String result = asyncInstantiationBL.getResumeRequestPath("rq1234d1-5a33-55df-13ab-12abad84e333");
1046 assertThat(expected, equalTo(result));
1050 public void getInstanceGroupsDeletionPath_verifyPathIsAsExpected() {
1051 assertEquals(asyncInstantiationBL.getInstanceGroupDeletePath("9aada4af-0f9b-424f-ae21-e693bd3e005b"),
1052 "/serviceInstantiation/v7/instanceGroups/9aada4af-0f9b-424f-ae21-e693bd3e005b");
1056 public void whenLcpRegionNotEmpty_thenCloudRegionIdOfResourceIsLegacy() {
1057 String legacyCloudRegion = "legacyCloudRegion";
1058 Vnf vnf = new Vnf(new ModelInfo(), null, null, Action.Create.name(), null, "anyCloudRegion", legacyCloudRegion,
1059 null, null, null, false, null, null, UUID.randomUUID().toString(), null, null, null, "originalName");
1060 assertThat(vnf.getLcpCloudRegionId(), equalTo(legacyCloudRegion));
1064 public void whenLcpRegionNotEmpty_thenCloudRegionIdOfServiceIsLegacy() {
1065 String legacyCloudRegion = "legacyCloudRegion";
1066 ServiceInstantiation service = new ServiceInstantiation(new ModelInfo(), null, null, null, null, null, null,
1067 null, null, "anyCloudRegion", legacyCloudRegion, null, null, null, null, null, null, null, null, null,
1068 false, 1,false, false, null, null, Action.Create.name(), UUID.randomUUID().toString(), null, null, null, "originalName");
1069 assertThat(service.getLcpCloudRegionId(), equalTo(legacyCloudRegion));
1073 public static Object[][] getJobTypeByRequest_verifyResultAsExpectedDataProvider() {
1074 return new Object[][]{
1075 {false, Action.Create, JobType.MacroServiceInstantiation},
1076 {true, Action.Create, JobType.ALaCarteServiceInstantiation},
1077 {true, Action.Delete, JobType.ALaCarteService},
1081 @Test(dataProvider = "getJobTypeByRequest_verifyResultAsExpectedDataProvider")
1082 public void getJobTypeByRequest_verifyResultAsExpected(boolean isALaCarte, Action action, JobType expectedJobType) {
1083 ServiceInstantiation service = createServiceWithIsALaCarteAndAction(isALaCarte, action);
1084 assertThat(asyncInstantiationBL.getJobType(service), equalTo(expectedJobType));
1088 protected ServiceInstantiation createServiceWithIsALaCarteAndAction(boolean isALaCarte, Action action) {
1089 return new ServiceInstantiation(new ModelInfo(), null, null, null, null, null, null,
1090 null, null, null, null, null, null, null, null, null, null, null, null, null,
1091 false, 1, false, isALaCarte, null, null, action.name(),
1092 UUID.randomUUID().toString(), null, null, null, "originalName");
1096 public static Object[][] isRetryEnabledForStatusDataProvider(Method test) {
1097 return new Object[][]{
1098 {FAILED, true, true},
1099 {COMPLETED_WITH_ERRORS, true, true},
1100 {COMPLETED_WITH_NO_ACTION, true, false},
1101 {COMPLETED, true, false},
1102 {IN_PROGRESS, true, false},
1103 {FAILED, false, false},
1104 {COMPLETED_WITH_ERRORS, false, false},
1105 {COMPLETED, false, false},
1109 @Test(dataProvider = "isRetryEnabledForStatusDataProvider")
1110 public void whenUpdateServiceInfoAndAuditStatus_thenServiceInfoRowIsUpdatedAndIsRetryIsRight(
1111 JobStatus jobStatus, boolean isRetryfeatureEnabled, boolean expectedIsRetry) {
1112 when(featureManager.isActive(Features.FLAG_1902_RETRY_JOB)).thenReturn(isRetryfeatureEnabled);
1113 UUID uuid = createFakedJobAndServiceInfo();
1114 asyncInstantiationBL.updateServiceInfoAndAuditStatus(uuid, jobStatus);
1115 ServiceInfo serviceInfo = ((List<ServiceInfo>)dataAccessService.getList(ServiceInfo.class, getPropsMap())).
1116 stream().filter(x->x.getJobId().equals(uuid)).findFirst().get();
1117 assertEquals(jobStatus, serviceInfo.getJobStatus());
1119 //we don't test serviceInfo.getStatusModifiedDate() because it's too complicated
1121 assertEquals(expectedIsRetry, serviceInfo.isRetryEnabled());
1125 public void givenServiceWithNullTrackByIds_whenReplaceTrackByIds_thenAllLevelsHasTrackByIdWithUUID() {
1126 ServiceInstantiation serviceInstantiation = FakeResourceCreator.createServiceWith2InstancesInEachLevel(Action.Create);
1127 //assert for the given that all trackById are null
1128 assertTrackByIdRecursively(serviceInstantiation, is(nullValue()), new HashSet<>());
1129 ServiceInstantiation modifiedServiceInstantiation = asyncInstantiationBL.prepareServiceToBeUnique(serviceInstantiation);
1130 assertTrackByIdRecursively(modifiedServiceInstantiation, uuidRegexMatcher, new HashSet<>());
1133 private void assertTrackByIdRecursively(BaseResource baseResource, org.hamcrest.Matcher matcher, Set<String> usedUuids) {
1134 assertThat(baseResource.getTrackById(), matcher);
1135 if (baseResource.getTrackById()!=null) {
1136 assertThat(usedUuids, not(hasItem(baseResource.getTrackById())));
1137 usedUuids.add(baseResource.getTrackById());
1139 baseResource.getChildren().forEach(x->assertTrackByIdRecursively(x, matcher, usedUuids));
1143 public void givenServicefromDB_returnsTheBulkRequest() throws IOException {
1144 ServiceInstantiation serviceInstantiation = TestUtils.readJsonResourceFileAsObject("/payload_jsons/VnfGroupCreate3Delete1None1Request.json", ServiceInstantiation.class);
1145 UUID jobId = UUID.randomUUID();
1146 doReturn(serviceInstantiation).when(asyncInstantiationRepository).getJobRequest(jobId);
1147 doReturn(mock(Map.class)).when(asyncInstantiationRepository).getResourceInfoByRootJobId(jobId);
1148 ServiceInstantiation modifiedServiceInstantiation = asyncInstantiationBL.getBulkForRetry(jobId);
1149 assertThat(modifiedServiceInstantiation, jsonEquals(serviceInstantiation).when(IGNORING_ARRAY_ORDER));
1153 public void givenServiceFromDB_returnsResolvedData() throws IOException {
1154 ServiceInstantiation serviceInstantiation = TestUtils.readJsonResourceFileAsObject("/payload_jsons/VnfGroupCreate3Delete1None1Request.json", ServiceInstantiation.class);
1155 ServiceInstantiation expectedServiceInstantiation = TestUtils.readJsonResourceFileAsObject("/payload_jsons/VnfGroupCreate3Delete1None1RequestResolvedForRetry.json", ServiceInstantiation.class);
1156 UUID jobId = UUID.randomUUID();
1157 AsyncRequestStatus asyncRequestStatus = TestUtils.readJsonResourceFileAsObject(
1158 "/responses/mso/orchestrationRequestsVnf.json",
1159 AsyncRequestStatus.class);
1160 Map<String, ResourceInfo> mockedResourceInfoMap = ImmutableMap.of(
1161 "groupingservicefortest..ResourceInstanceGroup..0:001", new ResourceInfo("groupingservicefortest..ResourceInstanceGroup..0:001",jobId,"VNF_GROUP1_INSTANCE_ID", COMPLETED, asyncRequestStatus),// TODO case: delete completed
1162 "ag5aav86u4j", new ResourceInfo("ag5aav86u4j",jobId, null, FAILED, asyncRequestStatus),// case: failed
1163 "asedrftjko", new ResourceInfo("asedrftjko",jobId, "VNF_GROUP1_INSTANCE_ID_3", COMPLETED, asyncRequestStatus),//case: completed after retry failed
1164 "rgedfdged4", new ResourceInfo("rgedfdged4", jobId,"VNF_GROUP1_INSTANCE_ID_4", COMPLETED, asyncRequestStatus ));// case: create completed
1166 doReturn(mockedResourceInfoMap).when(asyncInstantiationRepository).getResourceInfoByRootJobId(jobId);
1167 ServiceInstantiation modifiedServiceInstantiation = asyncInstantiationBL.enrichBulkForRetry(serviceInstantiation,jobId);
1168 assertThat(modifiedServiceInstantiation, jsonEquals(expectedServiceInstantiation).when(IGNORING_ARRAY_ORDER));
1172 public static Object[][] readStatusMsgDataProvider(Method test) throws IOException {
1173 AsyncRequestStatus asyncRequestStatus = TestUtils.readJsonResourceFileAsObject(
1174 "/responses/mso/orchestrationRequestsVnf.json",
1175 AsyncRequestStatus.class);
1176 return new Object[][]{
1178 {new AsyncRequestStatus(), null},
1179 {new AsyncRequestStatus(new AsyncRequestStatus.Request()), null},
1180 {new AsyncRequestStatus(new AsyncRequestStatus.Request(new RequestStatus())), null},
1181 {asyncRequestStatus, "Vnf has been created successfully."}
1185 @Test(dataProvider = "readStatusMsgDataProvider")
1186 public void resourceInfoReadStatusMsg_returnsStatusMsgOrNull(AsyncRequestStatus asyncRequestStatus, String expected) {
1187 ResourceInfo resourceInfo = new ResourceInfo("groupingservicefortest..ResourceInstanceGroup..0:001",UUID.randomUUID(),"VNF_GROUP1_INSTANCE_ID", COMPLETED, asyncRequestStatus);
1188 String msg= asyncInstantiationBL.readStatusMsg(resourceInfo);
1189 assertThat(msg, equalTo( expected));
1193 public void testAddResourceInfoForOkResponse() {
1194 reset(asyncInstantiationRepository);
1195 String serviceInstanceId = "service-instance-id";
1196 UUID jobUuid = UUID.randomUUID();
1198 asyncInstantiationBL.addResourceInfo(prepareSharedDataForAddResourceInfo(jobUuid), JobStatus.IN_PROGRESS, serviceInstanceId);
1200 ArgumentCaptor<ResourceInfo> resourceInfoCaptor = ArgumentCaptor.forClass(ResourceInfo.class);
1201 verify(asyncInstantiationRepository).saveResourceInfo(resourceInfoCaptor.capture());
1203 ResourceInfo resourceInfo = resourceInfoCaptor.getValue();
1204 assertResourceInfoValues(resourceInfo, serviceInstanceId, jobUuid, JobStatus.IN_PROGRESS);
1205 assertThat(resourceInfo.getErrorMessage(), is(nullValue()));
1208 private JobSharedData prepareSharedDataForAddResourceInfo(UUID jobUuid) {
1209 ServiceInstantiation serviceInstantiation = mock(ServiceInstantiation.class);
1210 when(serviceInstantiation.getTrackById()).thenReturn("track-by-id");
1211 return new JobSharedData(jobUuid, "", serviceInstantiation, "");
1214 private void assertResourceInfoValues(ResourceInfo resourceInfo, String serviceInstanceId, UUID jobUuid, JobStatus jobStatus) {
1215 assertThat(resourceInfo.getInstanceId(), equalTo(serviceInstanceId));
1216 assertThat(resourceInfo.getJobStatus(), equalTo(jobStatus));
1217 assertThat(resourceInfo.getRootJobId(), equalTo(jobUuid));
1218 assertThat(resourceInfo.getTrackById(), equalTo("track-by-id"));
1222 public static Object[][] addResourceInfoWithError() {
1223 String message = "Failed to create service instance";
1224 return new Object[][]{
1226 {400, "{\"requestError\":{\"serviceException\":{\"messageId\":\"SVC0002\",\"text\":\"" + message + "\"}}}"},
1227 {199, "{\"serviceException\":{\"messageId\":\"SVC2000\",\"text\":\"Error: " + message + "\"}}"},
1231 @Test(dataProvider = "addResourceInfoWithError")
1232 public void testAddResourceInfoForErrorResponse(int errorCode, String errorMessage) {
1233 reset(asyncInstantiationRepository);
1234 UUID jobUuid = UUID.randomUUID();
1236 RestObject restObject = mock(RestObject.class);
1237 when(restObject.getStatusCode()).thenReturn(errorCode);
1238 when(restObject.getRaw()).thenReturn(errorMessage);
1239 asyncInstantiationBL.addFailedResourceInfo(prepareSharedDataForAddResourceInfo(jobUuid), restObject);
1241 ArgumentCaptor<ResourceInfo> resourceInfoCaptor = ArgumentCaptor.forClass(ResourceInfo.class);
1242 verify(asyncInstantiationRepository).saveResourceInfo(resourceInfoCaptor.capture());
1244 ResourceInfo resourceInfo = resourceInfoCaptor.getValue();
1245 assertResourceInfoValues(resourceInfo, null, jobUuid, JobStatus.FAILED);
1246 assertThat(resourceInfo.getErrorMessage().request.requestStatus.getStatusMessage(), containsString("Failed to create service instance"));
1247 assertThat(resourceInfo.getErrorMessage().request.requestStatus.getStatusMessage(), containsString(String.valueOf(errorCode)));
1248 ZonedDateTime parsedDate = TimeUtils.parseZonedDateTime(resourceInfo.getErrorMessage().request.requestStatus.getTimestamp());
1249 assertThat(parsedDate.toLocalDate(), is(LocalDate.now()));
1251 doReturn(resourceInfo).when(asyncInstantiationRepository).getResourceInfoByTrackId(any());
1252 JobAuditStatus jobAuditStatus = auditService.getResourceAuditStatus(resourceInfo.getTrackById());
1253 assertThat(jobAuditStatus.getJobStatus(), equalTo("FAILED"));
1254 assertThat(jobAuditStatus.getAdditionalInfo(), containsString("Failed to create service instance"));
1255 assertThat(jobAuditStatus.getAdditionalInfo(), containsString(String.valueOf(errorCode)));
1256 assertTrue(DateUtils.isSameDay(jobAuditStatus.getCreatedDate(), new Date()));
1260 public static Object[][] updateResourceInfoParameters() {
1261 return new Object[][] {
1262 {JobStatus.COMPLETED, "Instance was created successfully"},
1263 {JobStatus.FAILED, "Failed to create instance"}
1267 @Test(dataProvider = "updateResourceInfoParameters")
1268 public void testUpdateResourceInfo(JobStatus jobStatus, String message) {
1269 reset(asyncInstantiationRepository);
1270 UUID jobUuid = UUID.randomUUID();
1271 JobSharedData sharedData = new JobSharedData(jobUuid, "", mock(ServiceInstantiation.class),"");
1273 ResourceInfo resourceInfoMock = new ResourceInfo();
1274 resourceInfoMock.setTrackById(UUID.randomUUID().toString());
1275 doReturn(resourceInfoMock).when(asyncInstantiationRepository).getResourceInfoByTrackId(any());
1277 AsyncRequestStatus asyncRequestStatus = asyncInstantiationBL.convertMessageToAsyncRequestStatus(message);
1279 asyncInstantiationBL.updateResourceInfo(sharedData, jobStatus, asyncRequestStatus);
1281 ArgumentCaptor<ResourceInfo> resourceInfoCaptor = ArgumentCaptor.forClass(ResourceInfo.class);
1282 verify(asyncInstantiationRepository).saveResourceInfo(resourceInfoCaptor.capture());
1284 ResourceInfo resourceInfo = resourceInfoCaptor.getValue();
1285 assertThat(resourceInfo.getJobStatus(), equalTo(jobStatus));
1286 if (jobStatus == JobStatus.FAILED) {
1287 assertThat(resourceInfo.getErrorMessage(), is(not(nullValue())));
1288 assertThat(resourceInfo.getErrorMessage().request.requestStatus.getStatusMessage(), equalTo(message));
1289 ZonedDateTime parsedDate = TimeUtils.parseZonedDateTime(resourceInfo.getErrorMessage().request.requestStatus.getTimestamp());
1290 assertThat(parsedDate.toLocalDate(), is(LocalDate.now()));
1292 assertThat(resourceInfo.getErrorMessage(), is(nullValue()));
1295 JobAuditStatus jobAuditStatus = auditService.getResourceAuditStatus(resourceInfo.getTrackById());
1296 if (jobStatus == JobStatus.FAILED) {
1297 assertThat(jobAuditStatus.getJobStatus(), equalTo("FAILED"));
1298 assertThat(jobAuditStatus.getAdditionalInfo(), equalTo(message));
1300 assertThat(jobAuditStatus, is(nullValue()));
1305 static class MockedJob implements Job {
1307 private static Map<UUID, MockedJob> uuidToJob = new HashMap<>();
1309 public static void putJob(UUID uuid, MockedJob job) {
1310 uuidToJob.put(uuid, job);
1313 public static MockedJob getJob(UUID uuid) {
1314 return uuidToJob.get(uuid);
1318 private String optimisticUniqueServiceInstanceName;
1320 public MockedJob(String optimisticUniqueServiceInstanceName) {
1321 this.optimisticUniqueServiceInstanceName = optimisticUniqueServiceInstanceName;
1324 private UUID uuid = UUID.randomUUID();
1327 public UUID getUuid() {
1332 public void setUuid(UUID uuid) {
1337 public JobStatus getStatus() {
1338 return JobStatus.PENDING;
1342 public void setStatus(JobStatus status) {
1347 public Map<String, Object> getData() {
1352 public JobSharedData getSharedData() {
1353 return new JobSharedData(uuid, "", null,"");
1357 public void setTypeAndData(JobType jobType, Map<String, Object> commandData) {
1362 public UUID getTemplateId() {
1367 public void setTemplateId(UUID templateId) {
1372 public Integer getIndexInBulk() {
1377 public void setIndexInBulk(Integer indexInBulk) {
1382 public JobType getType() {
1386 public String getOptimisticUniqueServiceInstanceName() {
1387 return optimisticUniqueServiceInstanceName;
1393 public void testGetVfModuleReplacePath_asMSOexpected()
1395 String path = asyncInstantiationBL.getVfModuleReplacePath("myService", "myVNF", "myVFModule");
1396 assertThat(path, equalTo("/serviceInstantiation/v7/serviceInstances/myService/vnfs/myVNF/vfModules/myVFModule/replace"));
1400 public void whenCallClearStatusFromRequest_isFailedAndStatusAreRemoved() throws JsonProcessingException {
1401 ServiceInstantiation serviceInstantiation = JACKSON_OBJECT_MAPPER.readValue(
1403 + " \"modelInfo\": {"
1404 + " \"modelType\": \"service\""
1406 + " \"isFailed\": true,"
1407 + " \"statusMessage\": \"some status\","
1409 + " \"vProbe_NC_VNF\": {"
1410 + " \"modelInfo\": {"
1411 + " \"modelType\": \"vnf\""
1413 + " \"isFailed\": true,"
1414 + " \"statusMessage\": \"other status\""
1418 ServiceInstantiation.class);
1419 asyncInstantiationBL.clearStatusFromRequest(serviceInstantiation);
1420 assertThat(serviceInstantiation, allOf(
1421 jsonPartEquals("isFailed", false),
1422 jsonPartEquals("statusMessage", null),
1423 jsonPartEquals("vnfs.vProbe_NC_VNF.isFailed", false),
1424 jsonPartEquals("vnfs.vProbe_NC_VNF.statusMessage", null)