clear isFailed and statusMessage when get it from frontend request
[vid.git] / vid-app-common / src / test / java / org / onap / vid / services / AsyncInstantiationBusinessLogicTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.vid.services;
22
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;
70
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;
77 import java.net.URL;
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;
91 import java.util.Map;
92 import java.util.Optional;
93 import java.util.Set;
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;
153
154 @ContextConfiguration(classes = {DataSourceConfig.class, SystemProperties.class, MockedAaiClientAndFeatureManagerConfig.class})
155 public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseTest {
156
157     @Mock
158     private JobAdapter jobAdapterMock;
159
160     @Mock
161     private JobsBrokerService jobsBrokerServiceMock;
162
163     private AsyncInstantiationRepository asyncInstantiationRepository;
164
165     private AuditService auditService;
166
167
168     private AsyncInstantiationBusinessLogicImpl asyncInstantiationBL;
169
170     protected MsoRequestBuilder msoRequestBuilder;
171
172     private static final String UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE =
173             "Failed to retrieve class .*ServiceInfo with jobId .* from table. no resource found";
174
175     private static final String DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE =
176             "Service status does not allow deletion from the queue";
177
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));
180
181
182     @BeforeClass
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);
188
189         auditService = new AuditServiceImpl(null, asyncInstantiationRepository);
190
191         AsyncInstantiationBusinessLogicImpl realAsyncInstantiationBL = new AsyncInstantiationBusinessLogicImpl(jobAdapterMock, jobsBrokerServiceMock, sessionFactory, aaiClient, featureManager, cloudOwnerService, asyncInstantiationRepository, auditService);
192         asyncInstantiationBL = Mockito.spy(realAsyncInstantiationBL);
193
194         msoRequestBuilder = new MsoRequestBuilder(asyncInstantiationBL, cloudOwnerService, aaiClient, featureManager);
195
196         createInstanceParamsMaps();
197     }
198
199     @BeforeMethod
200     void defineMocks() {
201         Mockito.reset(aaiClient);
202         Mockito.reset(jobAdapterMock);
203         Mockito.reset(jobsBrokerServiceMock);
204         Mockito.reset(asyncInstantiationRepository);
205         mockAaiClientAnyNameFree();
206         enableAddCloudOwnerOnMsoRequest();
207     }
208
209     @BeforeMethod
210     void resetServiceCount() {
211         serviceCount = 0;
212     }
213
214     @AfterMethod
215     void clearDb() {
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());
220     }
221
222
223     private void createNewTestServicesInfoForFilter(String userId) {
224         LocalDateTime createdDate, modifiedDate;
225         LocalDateTime NOW = LocalDateTime.now();
226         UUID uuid;
227
228         // Old job
229         uuid = UUID.randomUUID();
230         addNewJob(uuid);
231         createdDate = NOW.minusYears(1);
232         addNewServiceInfo(uuid, userId, "Old", createdDate, createdDate, COMPLETED, false, false,
233             MODEL_UUID);
234
235         uuid = UUID.randomUUID();
236         addNewJob(uuid);
237         createdDate = NOW.minusDays(20);
238         modifiedDate = NOW.minusDays(19);
239         addNewServiceInfo(uuid, userId, "Hidden", createdDate, modifiedDate, PAUSE, true, false,
240             MODEL_UUID);
241
242         createNewTestServicesInfo(String.valueOf(userId));
243     }
244
245     private void createNewTestServicesInfo(String userId) {
246
247         LocalDateTime createdDate, modifiedDate;
248         LocalDateTime NOW = LocalDateTime.now();
249         UUID uuid;
250
251         uuid = UUID.randomUUID();
252         addNewJob(uuid);
253
254         createdDate = NOW.minusDays(40);
255         addNewServiceInfo(uuid, userId, "service instance 5", createdDate, createdDate, COMPLETED, false, false,
256             MODEL_UUID);
257         addNewServiceInfo(uuid, userId, "service instance 6", createdDate, createdDate, STOPPED, false, false,
258             MODEL_UUID);
259
260         uuid = UUID.randomUUID();
261         addNewJob(uuid);
262
263         createdDate = NOW.minusDays(20);
264         modifiedDate = NOW.minusDays(10);
265         addNewServiceInfo(uuid, userId, "service instance 4", createdDate, modifiedDate, STOPPED, false, false,
266             MODEL_UUID);
267         addNewServiceInfo(uuid, userId, "service instance 2", createdDate, modifiedDate, COMPLETED, false, false,
268             MODEL_UUID);
269         addNewServiceInfo(uuid, userId, "service instance 3", createdDate, modifiedDate, PAUSE, false, false,
270             MODEL_UUID);
271
272         modifiedDate = NOW.minusDays(19);
273         addNewServiceInfo(uuid, userId, "service instance 1", createdDate, modifiedDate, FAILED, false, false,
274             MODEL_UUID);
275
276
277         // Job to a different user
278         uuid = UUID.randomUUID();
279         addNewJob(uuid);
280
281         createdDate = NOW.minusMonths(2);
282         addNewServiceInfo(uuid, "2221", "service instance 7", createdDate, createdDate, COMPLETED, false, false,
283             MODEL_UUID);
284
285     }
286
287
288
289     private UUID createServicesInfoWithDefaultValues(Job.JobStatus status) {
290
291         LocalDateTime NOW = LocalDateTime.now();
292         UUID uuid;
293
294         uuid = UUID.randomUUID();
295         addNewJob(uuid, status);
296
297         addNewServiceInfo(uuid, null, "service instance 1", NOW, NOW, status, false, false,
298             MODEL_UUID);
299
300         return uuid;
301
302     }
303
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;
309     }
310
311
312
313     private LocalDateTime fromDate(Date date) {
314         return Instant.ofEpochMilli(date.getTime())
315                 .atZone(ZoneId.systemDefault())
316                 .toLocalDateTime();
317     }
318
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);
327                     });
328             return 1;
329         });
330     }
331
332     private void addNewJob(UUID uuid) {
333         addNewJob(uuid, null);
334     }
335
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());
341     }
342
343     private ServiceInstantiation addOriginalService(UUID jobId, String userID){
344         addNewServiceInfo(jobId, userID, "name", LocalDateTime.now(), LocalDateTime.now(), COMPLETED_WITH_ERRORS, false,
345             true,
346             MODEL_UUID);
347         assertThat(asyncInstantiationRepository.getServiceInfoByJobId(jobId).isRetryEnabled(), is(true));
348         ServiceInstantiation originalServiceInstantiation = prepareServiceInstantiation(true, 1);
349         doReturn(originalServiceInstantiation).when(asyncInstantiationRepository).getJobRequest(jobId);
350         return originalServiceInstantiation;
351     }
352
353     private void assertRetryDisabled(UUID jobId){
354         assertThat(asyncInstantiationRepository.getServiceInfoByJobId(jobId).isRetryEnabled(), is(false));
355     }
356
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)));
360
361         ArgumentCaptor<ServiceInstantiation> requestsCaptor = ArgumentCaptor.forClass(ServiceInstantiation.class);
362         ArgumentCaptor<UUID> uuidsCaptor = ArgumentCaptor.forClass(UUID.class);
363         ArgumentCaptor<JobType> jobTypeCaptor = ArgumentCaptor.forClass(JobType.class);
364
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());
368
369         requestsCaptor.getAllValues().forEach(x->assertJsonEquals(expectedServiceInstantiation, x, whenIgnoringPaths(
370                 "trackById",
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"
374         )));
375
376     }
377
378     @Test
379     public void testServiceInfoAreOrderedAsExpected() {
380         int userId = 2222;
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));
385     }
386
387     @Test
388     public void whenNewServiceInfoCreated_isRetryEnablesIsFalse() {
389         UUID uuid = createServicesInfoWithDefaultValues(PENDING);
390         assertFalse(asyncInstantiationRepository.getServiceInfoByJobId(uuid).isRetryEnabled());
391     }
392
393     @Test
394     public void testServiceInfoAreFilteredAsExpected() {
395         int userId = 2222;
396         createNewTestServicesInfoForFilter(String.valueOf(userId));
397         List<ServiceInfo> expectedOrderServiceInfo = getFullList();
398
399         List<ServiceInfo> expectedFilterByUser = expectedOrderServiceInfo.stream().filter(x ->
400                 !x.getServiceInstanceName().equals("Old") && !x.getServiceInstanceName().equals("Hidden")
401
402         ).collect(Collectors.toList());
403
404
405         List<ServiceInfo> serviceInfoFilteredByUser = asyncInstantiationBL.getAllServicesInfo();
406         assertThat("Services aren't ordered filtered as expected", serviceInfoFilteredByUser, equalTo(expectedFilterByUser));
407     }
408
409     @Test(dataProvider = "pauseAndInstanceParams")
410     public void createMacroServiceInstantiationMsoRequestUniqueName(Boolean isPause, HashMap<String, String> vfModuleInstanceParamsMap, List vnfInstanceParams) throws Exception {
411         defineMocks();
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]);
417         });
418
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();
424         });
425
426         when(asyncInstantiationBL.isPartOfBulk(any())).thenReturn(true);
427
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);
449         }
450     }
451
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);
456     }
457
458
459
460
461     @DataProvider
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("", "", "")},
466         };
467     }
468
469     @Test(dataProvider="dataProviderForInstanceNames")
470     public void pushBulkJob_bulkWithSize3_instancesNamesAreExactlyAsExpected(boolean isUserProvidedNaming, List<String> expectedNames) {
471         final ServiceInstantiation request = prepareServiceInstantiation(isUserProvidedNaming, 3);
472
473
474         asyncInstantiationBL.pushBulkJob(request, "myUserId");
475
476         List<ServiceInfo> serviceInfoList = dataAccessService.getList(ServiceInfo.class, getPropsMap());
477         assertEquals(serviceInfoList.stream().map(ServiceInfo::getServiceInstanceName).collect(Collectors.toList()), expectedNames);
478     }
479
480     protected ServiceInstantiation prepareServiceInstantiation(String projectName, boolean isUserProvidedNaming, int bulkSize) {
481         final ServiceInstantiation request = generateMockMacroServiceInstantiationPayload(
482                 false,
483                 createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true),
484                 bulkSize, isUserProvidedNaming, projectName, true
485         );
486
487         // in "createServiceInstantiationJob()" we will probe the service, with the generated names
488         configureMockitoWithMockedJob();
489         return request;
490     }
491
492     protected ServiceInstantiation prepareServiceInstantiation(boolean isUserProvidedNaming, int bulkSize) {
493         return prepareServiceInstantiation(PROJECT_NAME, isUserProvidedNaming, bulkSize);
494     }
495
496     @DataProvider
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)},
502
503         };
504     }
505
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);
512     }
513
514     @Test
515     public void requestSummaryOrNull_givenActionWhichIsNotCreate_yieldNullRegardlessOfPayload(){
516         ServiceInstantiation serviceInstantiation = mock(ServiceInstantiation.class);
517
518         when(serviceInstantiation.getAction()).thenReturn(Action.Upgrade);
519         when(featureManager.isActive(Features.FLAG_2004_CREATE_ANOTHER_INSTANCE_FROM_TEMPLATE)).thenReturn(true);
520
521         assertThat(asyncInstantiationBL.requestSummaryOrNull(serviceInstantiation), is(nullValue()));
522     }
523
524     @Test
525     public void whenPushBulkJob_thenJobRequestIsSaveInJobRequestDb() {
526         Mockito.reset(asyncInstantiationRepository);
527         int bulkSize = 3;
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");
531
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());
538
539         //verify that all for each job we saved an row in jobRequest table
540         assertThat(uuidsCaptor.getAllValues(), containsInAnyOrder(jobIds.toArray()));
541
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()));
544
545         assertThat(requestsCaptor.getAllValues(),everyItem(hasProperty("bulkSize", is(1))));
546
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(
549                 "bulkSize",
550                 "trackById",
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"
554         )));
555
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));
559     }
560
561     @Test
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);
570     }
571
572     @Test
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);
581     }
582
583     @Test
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);
592     }
593
594     @Test
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);
603     }
604
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);
609
610         final ServiceInstantiation asObject = mapper.readValue(asString, ServiceInstantiation.class);
611         final String asString2 = mapper.writeValueAsString(asObject);
612
613         assertJsonEquals(asString, asString2);
614     }
615
616     @DataProvider
617     public Object[][] aLaCarteAndMacroPayload() {
618         ServiceInstantiation macroPayload = generateMockMacroServiceInstantiationPayload(
619                 false,
620                 createVnfList(instanceParamsMapWithoutParams, ImmutableList.of(vnfInstanceParamsMapWithParamsToRemove, vnfInstanceParamsMapWithParamsToRemove), true),
621                 2, false,PROJECT_NAME, false);
622         ServiceInstantiation aLaCartePayload = generateALaCarteServiceInstantiationPayload();
623
624         return new Object[][]{
625                 {macroPayload},
626                 {aLaCartePayload}
627         };
628     }
629
630     public static class ServiceInfoComparator implements Comparator<ServiceInfo> {
631
632         @Override
633         public int compare(ServiceInfo o1, ServiceInfo o2) {
634             int compare;
635
636             compare = o1.getCreatedBulkDate().compareTo(o2.getCreatedBulkDate());
637             if (compare != 0) {
638                 return -compare;
639             }
640
641             // check jobStatus priority
642             int o1Priority = getPriority(o1);
643             int o2Priority = getPriority(o2);
644             compare = o1Priority - o2Priority;
645             if (compare != 0) {
646                 return compare;
647             }
648
649             // check statusModifiedDate
650             return o1.getStatusModifiedDate().compareTo(o2.getStatusModifiedDate());
651         }
652
653         private int getPriority(ServiceInfo o) throws JSONException {
654             Job.JobStatus status = o.getJobStatus();
655             switch (status) {
656                 case COMPLETED:
657                 case FAILED:
658                     return 1;
659                 case IN_PROGRESS:
660                     return 2;
661                 case PAUSE:
662                     return 3;
663                 case STOPPED:
664                 case PENDING:
665                     return 4;
666                 default:
667                     return 5;
668             }
669         }
670     }
671
672     @DataProvider
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)}
678         };
679     }
680
681     @Test
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);
688         });
689         Optional<ServiceInfo> optionalServiceInfo = getJobById(uuid);
690         assertThat(optionalServiceInfo.get().getServiceInstanceName(), equalTo(STEPH_CURRY));
691         assertThat(optionalServiceInfo.get().getJobStatus(), equalTo(Job.JobStatus.IN_PROGRESS));
692     }
693
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();
697     }
698
699     private UUID createFakedJobAndServiceInfo() {
700         UUID uuid = UUID.randomUUID();
701         addNewJob(uuid);
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());
707         return uuid;
708     }
709
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"));
713     }
714
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"));
722     }
723
724
725     @DataProvider
726     public static Object[][] isPauseAndPropertyDataProvider() {
727         return new Object[][]{
728                 {true, "mso.restapi.serviceInstanceAssign"},
729                 {false, "mso.restapi.service.instance"},
730         };
731     }
732
733
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));
739     }
740
741     @Test
742     public void testCreateVnfEndpoint_useProvidedInstanceId() {
743         String path = asyncInstantiationBL.getVnfInstantiationPath("myGreatId");
744         assertThat(path, equalTo("/serviceInstantiation/v7/serviceInstances/myGreatId/vnfs"));
745     }
746
747
748
749     @Test
750     public void pushBulkJob_macroServiceverifyCreatedDateBehavior_createdDateIsTheSameForAllServicesInSameBulk() {
751         LocalDateTime startTestDate = LocalDateTime.now().withNano(0);
752         final ServiceInstantiation request = generateMockMacroServiceInstantiationPayload(
753                 false,
754                 createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true),
755                 100, true,PROJECT_NAME, true
756         );
757
758         pushJobAndAssertDates(startTestDate, request);
759     }
760
761     @Test
762     public void whenCreateServiceInfo_thenModelId_isModelVersionId() {
763         ServiceInfo serviceInfo = asyncInstantiationBL.createServiceInfo("userID",
764                 generateALaCarteWithVnfsServiceInstantiationPayload(),
765                 UUID.randomUUID(),
766                 UUID.randomUUID(),
767                 new Date(),
768                 "myName", ServiceInfo.ServiceAction.INSTANTIATE, null);
769         assertEquals(SERVICE_MODEL_VERSION_ID, serviceInfo.getServiceModelId());
770
771     }
772
773     @Test
774     public void pushBulkJob_aLaCarteServiceverifyCreatedDateBehavior_createdDateIsTheSameForAllServicesInSameBulk() {
775         LocalDateTime startTestDate = LocalDateTime.now().withNano(0);
776         final ServiceInstantiation request = generateALaCarteServiceInstantiationPayload();
777         pushJobAndAssertDates(startTestDate, request);
778     }
779
780     protected void pushJobAndAssertDates(LocalDateTime startTestDate, ServiceInstantiation request) {
781         // in "createServiceInstantiationJob()" we will probe the service, with the generated names
782         configureMockitoWithMockedJob();
783
784         asyncInstantiationBL.pushBulkJob(request, "myUserId");
785         List<ServiceInfo> serviceInfoList = dataAccessService.getList(ServiceInfo.class, getPropsMap());
786
787         List<Date> creationDates = new ArrayList<>();
788         for (ServiceInfo serviceInfo : serviceInfoList) {
789             creationDates.add(serviceInfo.getCreatedBulkDate());
790         }
791         LocalDateTime endTestDate = LocalDateTime.now();
792
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));
798     }
799
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());
807     }
808
809     @DataProvider
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},
827         };
828     }
829
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));
834     }
835
836     @DataProvider
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"}
842         };
843     }
844
845     @Test(dataProvider="msoRequestStatusFiles")
846     public void verifyAsyncRequestStatus_canBeReadFromSample(String msoResponseFile) throws IOException {
847         AsyncRequestStatus asyncRequestStatus = TestUtils.readJsonResourceFileAsObject(
848                 msoResponseFile,
849                 AsyncRequestStatus.class);
850         assertThat(asyncRequestStatus.request.requestStatus.getRequestState(), equalTo("COMPLETE"));
851     }
852
853     @Test
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");
859     }
860
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());
865         try {
866             asyncInstantiationBL.deleteJob(uuid);
867         } catch (Exception e) {
868             assertNull(asyncInstantiationRepository.getServiceInfoByJobId(uuid).getDeletedAt(), "service info shouldn't deleted");
869             throw e;
870         }
871     }
872
873     @DataProvider
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[][]{});
878     }
879
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));
886
887         asyncInstantiationBL.hideServiceInfo(uuidToHide);
888         serviceInfoList = listServicesUUID();
889         assertThat(serviceInfoList, hasItem(uuidToShown));
890         assertThat(serviceInfoList, not(hasItem(uuidToHide)));
891
892     }
893
894     protected List<UUID> listServicesUUID() {
895         return asyncInstantiationBL.getAllServicesInfo().stream().map(ServiceInfo::getJobId).collect(Collectors.toList());
896     }
897
898     @DataProvider
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[][]{});
903     }
904
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);
910         try {
911             asyncInstantiationBL.hideServiceInfo(uuid);
912         } catch (Exception e) {
913             assertFalse(asyncInstantiationRepository.getServiceInfoByJobId(uuid).isHidden(), "service info shouldn't be hidden");
914             throw e;
915         }
916     }
917
918     @Test
919     public void whenUseGetCounterInMultiThreads_EachThreadGetDifferentCounter() throws InterruptedException {
920         int SIZE = 200;
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)
927                 .forEach(future -> {
928                     try {
929                         assertTrue( expectedResults.remove(future.get()), "got unexpected counter");
930                     }
931                     catch (Exception e) {
932                         throw new RuntimeException(e);
933                     }
934                 });
935
936         assertThat(expectedResults.size(), is(0));
937     }
938
939     @Test
940     public void whenUseGetCounterForSameName_numbersReturnedByOrder() {
941
942         String name = UUID.randomUUID().toString();
943         int SIZE=10;
944         for (int i=0; i<SIZE; i++) {
945             assertThat(asyncInstantiationBL.getCounterForName(name), is(i));
946         }
947     }
948
949     @Test
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"));
956     }
957
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"));
967     }
968
969     private String someCommonStepsAndGetName() {
970         mockAaiClientAaiStatusOK();
971         return UUID.randomUUID().toString();
972     }
973
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);
980     }
981
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);
989     }
990
991     @Test
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"));
999     }
1000
1001     @Test
1002     public void pushBulkJob_verifyAlacarteFlow_useALaCartServiceInstantiationJobType(){
1003         final ServiceInstantiation request = generateALaCarteServiceInstantiationPayload();
1004
1005         // in "createServiceInstantiationJob()" we will probe the service, with the generated names
1006         configureMockitoWithMockedJob();
1007
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));
1012     }
1013
1014     @Test
1015     public void pushBulkJob_verifyMacroFlow_useMacroServiceInstantiationJobType(){
1016         final ServiceInstantiation request = generateMacroMockServiceInstantiationPayload(false, Collections.emptyMap());
1017
1018         // in "createServiceInstantiationJob()" we will probe the service, with the generated names
1019         configureMockitoWithMockedJob();
1020
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));
1025     }
1026
1027
1028
1029     @Test
1030     public void getALaCarteServiceDeletionPath_verifyPathIsAsExpected() {
1031
1032         String expected = "/serviceInstantiation/v7/serviceInstances/f36f5734-e9df-4fbf-9f35-61be13f028a1";
1033
1034         String result = asyncInstantiationBL.getServiceDeletionPath("f36f5734-e9df-4fbf-9f35-61be13f028a1");
1035
1036         assertThat(expected,equalTo(result));
1037     }
1038
1039     @Test
1040     public void getResumeRequestPath_verifyPathIsAsExpected() {
1041
1042         String expected = "/orchestrationRequests/v7/rq1234d1-5a33-55df-13ab-12abad84e333/resume";
1043
1044         String result = asyncInstantiationBL.getResumeRequestPath("rq1234d1-5a33-55df-13ab-12abad84e333");
1045
1046         assertThat(expected, equalTo(result));
1047     }
1048
1049     @Test
1050     public void getInstanceGroupsDeletionPath_verifyPathIsAsExpected()  {
1051         assertEquals(asyncInstantiationBL.getInstanceGroupDeletePath("9aada4af-0f9b-424f-ae21-e693bd3e005b"),
1052                 "/serviceInstantiation/v7/instanceGroups/9aada4af-0f9b-424f-ae21-e693bd3e005b");
1053     }
1054
1055     @Test
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);
1060         assertThat(vnf.getLcpCloudRegionId(), equalTo(legacyCloudRegion));
1061     }
1062
1063     @Test
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);
1069         assertThat(service.getLcpCloudRegionId(), equalTo(legacyCloudRegion));
1070     }
1071
1072     @DataProvider
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},
1078         };
1079     }
1080
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));
1085     }
1086
1087     @NotNull
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);
1093     }
1094
1095     @DataProvider
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},
1106         };
1107     }
1108
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());
1118
1119         //we don't test serviceInfo.getStatusModifiedDate() because it's too complicated
1120
1121         assertEquals(expectedIsRetry, serviceInfo.isRetryEnabled());
1122     }
1123
1124     @Test
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<>());
1131     }
1132
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());
1138         }
1139         baseResource.getChildren().forEach(x->assertTrackByIdRecursively(x, matcher, usedUuids));
1140     }
1141
1142     @Test
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));
1150     }
1151
1152     @Test
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
1165
1166         doReturn(mockedResourceInfoMap).when(asyncInstantiationRepository).getResourceInfoByRootJobId(jobId);
1167         ServiceInstantiation modifiedServiceInstantiation = asyncInstantiationBL.enrichBulkForRetry(serviceInstantiation,jobId);
1168         assertThat(modifiedServiceInstantiation, jsonEquals(expectedServiceInstantiation).when(IGNORING_ARRAY_ORDER));
1169     }
1170
1171     @DataProvider
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[][]{
1177                 {null, null},
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."}
1182         };
1183     }
1184
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));
1190     }
1191
1192     @Test
1193     public void testAddResourceInfoForOkResponse() {
1194         reset(asyncInstantiationRepository);
1195         String serviceInstanceId = "service-instance-id";
1196         UUID jobUuid = UUID.randomUUID();
1197
1198         asyncInstantiationBL.addResourceInfo(prepareSharedDataForAddResourceInfo(jobUuid), JobStatus.IN_PROGRESS, serviceInstanceId);
1199
1200         ArgumentCaptor<ResourceInfo> resourceInfoCaptor = ArgumentCaptor.forClass(ResourceInfo.class);
1201         verify(asyncInstantiationRepository).saveResourceInfo(resourceInfoCaptor.capture());
1202
1203         ResourceInfo resourceInfo = resourceInfoCaptor.getValue();
1204         assertResourceInfoValues(resourceInfo, serviceInstanceId, jobUuid, JobStatus.IN_PROGRESS);
1205         assertThat(resourceInfo.getErrorMessage(), is(nullValue()));
1206     }
1207
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, "");
1212     }
1213
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"));
1219     }
1220
1221     @DataProvider
1222     public static Object[][] addResourceInfoWithError() {
1223         String message = "Failed to create service instance";
1224         return new Object[][]{
1225                 {500, message},
1226                 {199, "{\"serviceException\":{\"messageId\":\"SVC2000\",\"text\":\"Error: " + message + "\"}}"}
1227         };
1228     }
1229
1230     @Test(dataProvider = "addResourceInfoWithError")
1231     public void testAddResourceInfoForErrorResponse(int errorCode, String errorMessage) {
1232         reset(asyncInstantiationRepository);
1233         UUID jobUuid = UUID.randomUUID();
1234
1235         RestObject restObject = mock(RestObject.class);
1236         when(restObject.getStatusCode()).thenReturn(errorCode);
1237         when(restObject.getRaw()).thenReturn(errorMessage);
1238         asyncInstantiationBL.addFailedResourceInfo(prepareSharedDataForAddResourceInfo(jobUuid), restObject);
1239
1240         ArgumentCaptor<ResourceInfo> resourceInfoCaptor = ArgumentCaptor.forClass(ResourceInfo.class);
1241         verify(asyncInstantiationRepository).saveResourceInfo(resourceInfoCaptor.capture());
1242
1243         ResourceInfo resourceInfo = resourceInfoCaptor.getValue();
1244         assertResourceInfoValues(resourceInfo, null, jobUuid, JobStatus.FAILED);
1245         assertThat(resourceInfo.getErrorMessage().request.requestStatus.getStatusMessage(), containsString("Failed to create service instance"));
1246         assertThat(resourceInfo.getErrorMessage().request.requestStatus.getStatusMessage(), containsString(String.valueOf(errorCode)));
1247         ZonedDateTime parsedDate = TimeUtils.parseZonedDateTime(resourceInfo.getErrorMessage().request.requestStatus.getTimestamp());
1248         assertThat(parsedDate.toLocalDate(), is(LocalDate.now()));
1249
1250         doReturn(resourceInfo).when(asyncInstantiationRepository).getResourceInfoByTrackId(any());
1251         JobAuditStatus jobAuditStatus = auditService.getResourceAuditStatus(resourceInfo.getTrackById());
1252         assertThat(jobAuditStatus.getJobStatus(), equalTo("FAILED"));
1253         assertThat(jobAuditStatus.getAdditionalInfo(), containsString("Failed to create service instance"));
1254         assertThat(jobAuditStatus.getAdditionalInfo(), containsString(String.valueOf(errorCode)));
1255         assertTrue(DateUtils.isSameDay(jobAuditStatus.getCreatedDate(), new Date()));
1256     }
1257
1258     @DataProvider
1259     public static Object[][] updateResourceInfoParameters() {
1260         return new Object[][] {
1261                 {JobStatus.COMPLETED, "Instance was created successfully"},
1262                 {JobStatus.FAILED, "Failed to create instance"}
1263         };
1264     }
1265
1266     @Test(dataProvider = "updateResourceInfoParameters")
1267     public void testUpdateResourceInfo(JobStatus jobStatus, String message) {
1268         reset(asyncInstantiationRepository);
1269         UUID jobUuid = UUID.randomUUID();
1270         JobSharedData sharedData = new JobSharedData(jobUuid, "", mock(ServiceInstantiation.class),"");
1271
1272         ResourceInfo resourceInfoMock = new ResourceInfo();
1273         resourceInfoMock.setTrackById(UUID.randomUUID().toString());
1274         doReturn(resourceInfoMock).when(asyncInstantiationRepository).getResourceInfoByTrackId(any());
1275
1276         AsyncRequestStatus asyncRequestStatus = asyncInstantiationBL.convertMessageToAsyncRequestStatus(message);
1277
1278         asyncInstantiationBL.updateResourceInfo(sharedData, jobStatus, asyncRequestStatus);
1279
1280         ArgumentCaptor<ResourceInfo> resourceInfoCaptor = ArgumentCaptor.forClass(ResourceInfo.class);
1281         verify(asyncInstantiationRepository).saveResourceInfo(resourceInfoCaptor.capture());
1282
1283         ResourceInfo resourceInfo = resourceInfoCaptor.getValue();
1284         assertThat(resourceInfo.getJobStatus(), equalTo(jobStatus));
1285         if (jobStatus == JobStatus.FAILED) {
1286             assertThat(resourceInfo.getErrorMessage(), is(not(nullValue())));
1287             assertThat(resourceInfo.getErrorMessage().request.requestStatus.getStatusMessage(), equalTo(message));
1288             ZonedDateTime parsedDate = TimeUtils.parseZonedDateTime(resourceInfo.getErrorMessage().request.requestStatus.getTimestamp());
1289             assertThat(parsedDate.toLocalDate(), is(LocalDate.now()));
1290         } else {
1291             assertThat(resourceInfo.getErrorMessage(), is(nullValue()));
1292         }
1293
1294         JobAuditStatus jobAuditStatus = auditService.getResourceAuditStatus(resourceInfo.getTrackById());
1295         if (jobStatus == JobStatus.FAILED) {
1296             assertThat(jobAuditStatus.getJobStatus(), equalTo("FAILED"));
1297             assertThat(jobAuditStatus.getAdditionalInfo(), equalTo(message));
1298         } else {
1299             assertThat(jobAuditStatus, is(nullValue()));
1300         }
1301
1302     }
1303
1304     static class MockedJob implements Job {
1305
1306         private static Map<UUID, MockedJob> uuidToJob = new HashMap<>();
1307
1308         public static void putJob(UUID uuid, MockedJob job) {
1309             uuidToJob.put(uuid, job);
1310         }
1311
1312         public static MockedJob getJob(UUID uuid) {
1313             return uuidToJob.get(uuid);
1314         }
1315
1316
1317         private String optimisticUniqueServiceInstanceName;
1318
1319         public MockedJob(String optimisticUniqueServiceInstanceName) {
1320             this.optimisticUniqueServiceInstanceName = optimisticUniqueServiceInstanceName;
1321         }
1322
1323         private UUID uuid = UUID.randomUUID();
1324
1325         @Override
1326         public UUID getUuid() {
1327             return uuid;
1328         }
1329
1330         @Override
1331         public void setUuid(UUID uuid) {
1332             this.uuid = uuid;
1333         }
1334
1335         @Override
1336         public JobStatus getStatus() {
1337             return JobStatus.PENDING;
1338         }
1339
1340         @Override
1341         public void setStatus(JobStatus status) {
1342
1343         }
1344
1345         @Override
1346         public Map<String, Object> getData() {
1347             return null;
1348         }
1349
1350         @Override
1351         public JobSharedData getSharedData() {
1352             return new JobSharedData(uuid, "", null,"");
1353         }
1354
1355         @Override
1356         public void setTypeAndData(JobType jobType, Map<String, Object> commandData) {
1357
1358         }
1359
1360         @Override
1361         public UUID getTemplateId() {
1362             return null;
1363         }
1364
1365         @Override
1366         public void setTemplateId(UUID templateId) {
1367
1368         }
1369
1370         @Override
1371         public Integer getIndexInBulk() {
1372             return null;
1373         }
1374
1375         @Override
1376         public void setIndexInBulk(Integer indexInBulk) {
1377
1378         }
1379
1380         @Override
1381         public JobType getType() {
1382             return null;
1383         }
1384
1385         public String getOptimisticUniqueServiceInstanceName() {
1386             return optimisticUniqueServiceInstanceName;
1387         }
1388     }
1389
1390
1391     @Test
1392     public void testGetVfModuleReplacePath_asMSOexpected()
1393     {
1394         String path = asyncInstantiationBL.getVfModuleReplacePath("myService", "myVNF", "myVFModule");
1395         assertThat(path, equalTo("/serviceInstantiation/v7/serviceInstances/myService/vnfs/myVNF/vfModules/myVFModule/replace"));
1396     }
1397
1398     @Test
1399     public void whenCallClearStatusFromRequest_isFailedAndStatusAreRemoved() throws JsonProcessingException {
1400         ServiceInstantiation serviceInstantiation = JACKSON_OBJECT_MAPPER.readValue(
1401                "{"
1402                 + "    \"modelInfo\": {"
1403                 + "        \"modelType\": \"service\""
1404                 + "    },"
1405                 + "    \"isFailed\": true,"
1406                 + "    \"statusMessage\": \"some status\","
1407                 + "    \"vnfs\": {"
1408                 + "        \"vProbe_NC_VNF\": {"
1409                 + "            \"modelInfo\": {"
1410                 + "                \"modelType\": \"vnf\""
1411                 + "            },"
1412                 + "            \"isFailed\": true,"
1413                 + "            \"statusMessage\": \"other status\""
1414                 + "        }"
1415                 + "    }"
1416                 + "}",
1417             ServiceInstantiation.class);
1418         asyncInstantiationBL.clearStatusFromRequest(serviceInstantiation);
1419         assertThat(serviceInstantiation, allOf(
1420             jsonPartEquals("isFailed", false),
1421             jsonPartEquals("statusMessage", null),
1422             jsonPartEquals("vnfs.vProbe_NC_VNF.isFailed", false),
1423             jsonPartEquals("vnfs.vProbe_NC_VNF.statusMessage", null)
1424         ));
1425     }
1426
1427
1428 }