Honor user-cookie to select a temporal feature set
[vid.git] / vid-app-common / src / test / java / org / onap / vid / services / AsyncInstantiationBusinessLogicTest.java
index c1a6abc..0749aaf 100644 (file)
@@ -23,8 +23,10 @@ package org.onap.vid.services;
 import static net.javacrumbs.jsonunit.JsonAssert.assertJsonEquals;
 import static net.javacrumbs.jsonunit.JsonAssert.whenIgnoringPaths;
 import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals;
+import static net.javacrumbs.jsonunit.JsonMatchers.jsonPartEquals;
 import static net.javacrumbs.jsonunit.core.Option.IGNORING_ARRAY_ORDER;
 import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.allOf;
 import static org.hamcrest.Matchers.containsInAnyOrder;
 import static org.hamcrest.Matchers.containsString;
 import static org.hamcrest.Matchers.hasItem;
@@ -37,13 +39,13 @@ import static org.hamcrest.Matchers.not;
 import static org.hamcrest.Matchers.nullValue;
 import static org.hamcrest.core.Every.everyItem;
 import static org.hamcrest.core.IsEqual.equalTo;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.anyInt;
-import static org.mockito.Mockito.anyString;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.doNothing;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.eq;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.reset;
 import static org.mockito.Mockito.spy;
@@ -59,12 +61,14 @@ import static org.onap.vid.job.Job.JobStatus.PAUSE;
 import static org.onap.vid.job.Job.JobStatus.PENDING;
 import static org.onap.vid.job.Job.JobStatus.STOPPED;
 import static org.onap.vid.testUtils.TestUtils.generateRandomAlphaNumeric;
+import static org.onap.vid.utils.KotlinUtilsKt.JACKSON_OBJECT_MAPPER;
 import static org.testng.Assert.assertEquals;
 import static org.testng.Assert.assertFalse;
 import static org.testng.Assert.assertNotNull;
 import static org.testng.Assert.assertNull;
 import static org.testng.Assert.assertTrue;
 
+import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
@@ -93,10 +97,8 @@ import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import java.util.stream.Collectors;
 import java.util.stream.IntStream;
-import javax.inject.Inject;
 import org.apache.commons.io.IOUtils;
 import org.apache.commons.lang3.time.DateUtils;
-import org.hibernate.SessionFactory;
 import org.jetbrains.annotations.NotNull;
 import org.json.JSONException;
 import org.mockito.ArgumentCaptor;
@@ -104,8 +106,6 @@ import org.mockito.Mock;
 import org.mockito.Mockito;
 import org.mockito.MockitoAnnotations;
 import org.mockito.stubbing.Answer;
-import org.onap.portalsdk.core.domain.FusionObject;
-import org.onap.portalsdk.core.service.DataAccessService;
 import org.onap.portalsdk.core.util.SystemProperties;
 import org.onap.vid.aai.ExceptionWithRequestInfo;
 import org.onap.vid.aai.model.ResourceType;
@@ -143,7 +143,6 @@ import org.onap.vid.properties.Features;
 import org.onap.vid.testUtils.TestUtils;
 import org.onap.vid.utils.DaoUtils;
 import org.onap.vid.utils.TimeUtils;
-import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.test.context.ContextConfiguration;
 import org.testng.Assert;
 import org.testng.annotations.AfterMethod;
@@ -155,9 +154,6 @@ import org.testng.annotations.Test;
 @ContextConfiguration(classes = {DataSourceConfig.class, SystemProperties.class, MockedAaiClientAndFeatureManagerConfig.class})
 public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseTest {
 
-    @Inject
-    private DataAccessService dataAccessService;
-
     @Mock
     private JobAdapter jobAdapterMock;
 
@@ -168,15 +164,11 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT
 
     private AuditService auditService;
 
-    @Autowired
-    private SessionFactory sessionFactory;
 
     private AsyncInstantiationBusinessLogicImpl asyncInstantiationBL;
 
     protected MsoRequestBuilder msoRequestBuilder;
 
-    private int serviceCount = 0;
-
     private static final String UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE =
             "Failed to retrieve class .*ServiceInfo with jobId .* from table. no resource found";
 
@@ -209,6 +201,7 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT
         Mockito.reset(aaiClient);
         Mockito.reset(jobAdapterMock);
         Mockito.reset(jobsBrokerServiceMock);
+        Mockito.reset(asyncInstantiationRepository);
         mockAaiClientAnyNameFree();
         enableAddCloudOwnerOnMsoRequest();
     }
@@ -236,13 +229,15 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT
         uuid = UUID.randomUUID();
         addNewJob(uuid);
         createdDate = NOW.minusYears(1);
-        addNewServiceInfo(uuid, userId, "Old", createdDate, createdDate, COMPLETED, false, false);
+        addNewServiceInfo(uuid, userId, "Old", createdDate, createdDate, COMPLETED, false, false,
+            MODEL_UUID);
 
         uuid = UUID.randomUUID();
         addNewJob(uuid);
         createdDate = NOW.minusDays(20);
         modifiedDate = NOW.minusDays(19);
-        addNewServiceInfo(uuid, userId, "Hidden", createdDate, modifiedDate, PAUSE, true, false);
+        addNewServiceInfo(uuid, userId, "Hidden", createdDate, modifiedDate, PAUSE, true, false,
+            MODEL_UUID);
 
         createNewTestServicesInfo(String.valueOf(userId));
     }
@@ -257,20 +252,26 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT
         addNewJob(uuid);
 
         createdDate = NOW.minusDays(40);
-        addNewServiceInfo(uuid, userId, "service instance 5", createdDate, createdDate, COMPLETED, false, false);
-        addNewServiceInfo(uuid, userId, "service instance 6", createdDate, createdDate, STOPPED, false, false);
+        addNewServiceInfo(uuid, userId, "service instance 5", createdDate, createdDate, COMPLETED, false, false,
+            MODEL_UUID);
+        addNewServiceInfo(uuid, userId, "service instance 6", createdDate, createdDate, STOPPED, false, false,
+            MODEL_UUID);
 
         uuid = UUID.randomUUID();
         addNewJob(uuid);
 
         createdDate = NOW.minusDays(20);
         modifiedDate = NOW.minusDays(10);
-        addNewServiceInfo(uuid, userId, "service instance 4", createdDate, modifiedDate, STOPPED, false, false);
-        addNewServiceInfo(uuid, userId, "service instance 2", createdDate, modifiedDate, COMPLETED, false, false);
-        addNewServiceInfo(uuid, userId, "service instance 3", createdDate, modifiedDate, PAUSE, false, false);
+        addNewServiceInfo(uuid, userId, "service instance 4", createdDate, modifiedDate, STOPPED, false, false,
+            MODEL_UUID);
+        addNewServiceInfo(uuid, userId, "service instance 2", createdDate, modifiedDate, COMPLETED, false, false,
+            MODEL_UUID);
+        addNewServiceInfo(uuid, userId, "service instance 3", createdDate, modifiedDate, PAUSE, false, false,
+            MODEL_UUID);
 
         modifiedDate = NOW.minusDays(19);
-        addNewServiceInfo(uuid, userId, "service instance 1", createdDate, modifiedDate, FAILED, false, false);
+        addNewServiceInfo(uuid, userId, "service instance 1", createdDate, modifiedDate, FAILED, false, false,
+            MODEL_UUID);
 
 
         // Job to a different user
@@ -278,10 +279,13 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT
         addNewJob(uuid);
 
         createdDate = NOW.minusMonths(2);
-        addNewServiceInfo(uuid, "2221", "service instance 7", createdDate, createdDate, COMPLETED, false, false);
+        addNewServiceInfo(uuid, "2221", "service instance 7", createdDate, createdDate, COMPLETED, false, false,
+            MODEL_UUID);
 
     }
 
+
+
     private UUID createServicesInfoWithDefaultValues(Job.JobStatus status) {
 
         LocalDateTime NOW = LocalDateTime.now();
@@ -290,7 +294,8 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT
         uuid = UUID.randomUUID();
         addNewJob(uuid, status);
 
-        addNewServiceInfo(uuid, null, "service instance 1", NOW, NOW, status, false, false);
+        addNewServiceInfo(uuid, null, "service instance 1", NOW, NOW, status, false, false,
+            MODEL_UUID);
 
         return uuid;
 
@@ -303,9 +308,7 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT
         return expectedOrderServiceInfo;
     }
 
-    private static Date toDate(LocalDateTime localDateTime) {
-        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
-    }
+
 
     private LocalDateTime fromDate(Date date) {
         return Instant.ofEpochMilli(date.getTime())
@@ -313,25 +316,6 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT
                 .toLocalDateTime();
     }
 
-    private void addNewServiceInfo(UUID uuid, String userId, String serviceName, LocalDateTime createDate, LocalDateTime statusModifiedDate, JobStatus status, boolean isHidden, boolean retryEnabled) {
-        ServiceInfo serviceInfo = new ServiceInfo();
-        serviceInfo.setJobId(uuid);
-        serviceInfo.setUserId(userId);
-        serviceInfo.setServiceInstanceName(serviceName);
-        serviceInfo.setStatusModifiedDate(toDate(statusModifiedDate));
-        serviceInfo.setJobStatus(status);
-        serviceInfo.setPause(false);
-        serviceInfo.setOwningEntityId("1234");
-        serviceInfo.setCreatedBulkDate(toDate(createDate));
-        serviceInfo.setRetryEnabled(retryEnabled);
-
-        serviceInfo.setHidden(isHidden);
-        dataAccessService.saveDomainObject(serviceInfo, getPropsMap());
-        setCreateDateToServiceInfo(uuid, createDate);
-        serviceCount++;
-
-    }
-
     private void setCreateDateToServiceInfo(UUID jobUuid, LocalDateTime createDate) {
         List<ServiceInfo> serviceInfoList = dataAccessService.getList(ServiceInfo.class, getPropsMap());
         DaoUtils.tryWithSessionAndTransaction(sessionFactory, session -> {
@@ -357,7 +341,9 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT
     }
 
     private ServiceInstantiation addOriginalService(UUID jobId, String userID){
-        addNewServiceInfo(jobId, userID, "name", LocalDateTime.now(), LocalDateTime.now(), COMPLETED_WITH_ERRORS, false, true);
+        addNewServiceInfo(jobId, userID, "name", LocalDateTime.now(), LocalDateTime.now(), COMPLETED_WITH_ERRORS, false,
+            true,
+            MODEL_UUID);
         assertThat(asyncInstantiationRepository.getServiceInfoByJobId(jobId).isRetryEnabled(), is(true));
         ServiceInstantiation originalServiceInstantiation = prepareServiceInstantiation(true, 1);
         doReturn(originalServiceInstantiation).when(asyncInstantiationRepository).getJobRequest(jobId);
@@ -469,11 +455,7 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT
         when(aaiClient.isNodeTypeExistsByName(uniqueName, serviceInstance)).thenReturn(true);
     }
 
-    private HashMap<String, Object> getPropsMap() {
-        HashMap<String, Object> props = new HashMap<>();
-        props.put(FusionObject.Parameters.PARAM_USERID, 0);
-        return props;
-    }
+
 
 
     @DataProvider
@@ -511,7 +493,33 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT
         return prepareServiceInstantiation(PROJECT_NAME, isUserProvidedNaming, bulkSize);
     }
 
+    @DataProvider
+    public static Object[][] dataProviderSummarizedMap() {
+        return new Object[][]{
+            {"/payload_jsons/templateSummarize4vnfs6vfmodules.json", ImmutableMap.of("vnf", 4L, "vfModule", 6L, "volumeGroup", 1L, "network", 2L)},
+            {"/payload_jsons/templateSummarize3Vnfs8Vfmodule2VolumeGroups.json", ImmutableMap.of("vnf", 3L, "vfModule", 8L, "volumeGroup", 2L)},
+            {"/payload_jsons/templateSummarize3Networks.json", ImmutableMap.of("network", 3L)},
+
+        };
+    }
 
+    @Test(dataProvider = "dataProviderSummarizedMap")
+    public void summarizedChildrenMap_givenServiceInstantiation_yieldCorrectMap(String pathInResource, Map<String, Long> expectedMap){
+        ServiceInstantiation serviceInstantiation = TestUtils.readJsonResourceFileAsObject(
+            pathInResource, ServiceInstantiation.class);
+        Map<String, Long> childrenMap =  asyncInstantiationBL.summarizedChildrenMap(serviceInstantiation);
+        assertEquals(childrenMap,expectedMap);
+    }
+
+    @Test
+    public void requestSummaryOrNull_givenActionWhichIsNotCreate_yieldNullRegardlessOfPayload(){
+        ServiceInstantiation serviceInstantiation = mock(ServiceInstantiation.class);
+
+        when(serviceInstantiation.getAction()).thenReturn(Action.Upgrade);
+        when(featureManager.isActive(Features.FLAG_2004_CREATE_ANOTHER_INSTANCE_FROM_TEMPLATE)).thenReturn(true);
+
+        assertThat(asyncInstantiationBL.requestSummaryOrNull(serviceInstantiation), is(nullValue()));
+    }
 
     @Test
     public void whenPushBulkJob_thenJobRequestIsSaveInJobRequestDb() {
@@ -757,7 +765,7 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT
                 UUID.randomUUID(),
                 UUID.randomUUID(),
                 new Date(),
-                "myName", ServiceInfo.ServiceAction.INSTANTIATE);
+                "myName", ServiceInfo.ServiceAction.INSTANTIATE, null);
         assertEquals(SERVICE_MODEL_VERSION_ID, serviceInfo.getServiceModelId());
 
     }
@@ -1385,6 +1393,36 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT
     {
         String path = asyncInstantiationBL.getVfModuleReplacePath("myService", "myVNF", "myVFModule");
         assertThat(path, equalTo("/serviceInstantiation/v7/serviceInstances/myService/vnfs/myVNF/vfModules/myVFModule/replace"));
+    }
 
+    @Test
+    public void whenCallClearStatusFromRequest_isFailedAndStatusAreRemoved() throws JsonProcessingException {
+        ServiceInstantiation serviceInstantiation = JACKSON_OBJECT_MAPPER.readValue(
+               "{"
+                + "    \"modelInfo\": {"
+                + "        \"modelType\": \"service\""
+                + "    },"
+                + "    \"isFailed\": true,"
+                + "    \"statusMessage\": \"some status\","
+                + "    \"vnfs\": {"
+                + "        \"vProbe_NC_VNF\": {"
+                + "            \"modelInfo\": {"
+                + "                \"modelType\": \"vnf\""
+                + "            },"
+                + "            \"isFailed\": true,"
+                + "            \"statusMessage\": \"other status\""
+                + "        }"
+                + "    }"
+                + "}",
+            ServiceInstantiation.class);
+        asyncInstantiationBL.clearStatusFromRequest(serviceInstantiation);
+        assertThat(serviceInstantiation, allOf(
+            jsonPartEquals("isFailed", false),
+            jsonPartEquals("statusMessage", null),
+            jsonPartEquals("vnfs.vProbe_NC_VNF.isFailed", false),
+            jsonPartEquals("vnfs.vProbe_NC_VNF.statusMessage", null)
+        ));
     }
+
+
 }