Add pause after completion for vfModule
[vid.git] / vid-app-common / src / test / java / org / onap / vid / job / impl / AsyncInstantiationIntegrationTest.java
index 498708d..061b62a 100644 (file)
 
 package org.onap.vid.job.impl;
 
+import static java.util.stream.Collectors.counting;
+import static java.util.stream.Collectors.groupingBy;
+import static java.util.stream.Collectors.joining;
+import static net.javacrumbs.jsonunit.JsonAssert.assertJsonEquals;
+import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals;
+import static net.javacrumbs.jsonunit.JsonMatchers.jsonNodePresent;
+import static net.javacrumbs.jsonunit.JsonMatchers.jsonPartEquals;
+import static net.javacrumbs.jsonunit.JsonMatchers.jsonPartMatches;
+import static net.javacrumbs.jsonunit.core.Option.IGNORING_ARRAY_ORDER;
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.hasProperty;
+import static org.hamcrest.Matchers.hasSize;
+import static org.hamcrest.core.Every.everyItem;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.argThat;
+import static org.mockito.ArgumentMatchers.endsWith;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.isNull;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.onap.vid.job.Job.JobStatus.COMPLETED;
+import static org.onap.vid.job.Job.JobStatus.COMPLETED_WITH_ERRORS;
+import static org.onap.vid.job.Job.JobStatus.COMPLETED_WITH_NO_ACTION;
+import static org.onap.vid.job.Job.JobStatus.FAILED;
+import static org.onap.vid.job.Job.JobStatus.IN_PROGRESS;
+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.PENDING_RESOURCE;
+import static org.onap.vid.job.Job.JobStatus.RESOURCE_IN_PROGRESS;
+import static org.onap.vid.job.Job.JobStatus.STOPPED;
+import static org.onap.vid.job.impl.JobSchedulerInitializer.WORKERS_TOPICS;
+import static org.onap.vid.model.JobAuditStatus.SourceStatus.VID;
+import static org.onap.vid.testUtils.TestUtils.readJsonResourceFileAsObject;
+import static org.testng.Assert.assertNull;
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertFalse;
+import static org.testng.AssertJUnit.assertTrue;
+
 import com.fasterxml.jackson.databind.JsonNode;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
+import java.lang.reflect.Method;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Stack;
+import java.util.UUID;
+import java.util.function.BiConsumer;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+import javax.inject.Inject;
+import javax.ws.rs.ProcessingException;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.commons.lang3.mutable.MutableInt;
 import org.jetbrains.annotations.NotNull;
@@ -33,13 +92,21 @@ import org.onap.portalsdk.core.service.DataAccessService;
 import org.onap.portalsdk.core.util.SystemProperties;
 import org.onap.vid.asdc.AsdcCatalogException;
 import org.onap.vid.changeManagement.RequestDetailsWrapper;
+import org.onap.vid.config.DataSourceConfig;
+import org.onap.vid.config.JobCommandsConfigWithMockedMso;
+import org.onap.vid.config.MockedAaiClientAndFeatureManagerConfig;
 import org.onap.vid.job.Job;
 import org.onap.vid.job.Job.JobStatus;
 import org.onap.vid.job.JobType;
 import org.onap.vid.job.JobsBrokerService;
 import org.onap.vid.job.command.CommandUtils;
 import org.onap.vid.job.command.InternalState;
-import org.onap.vid.model.*;
+import org.onap.vid.model.Action;
+import org.onap.vid.model.JobAuditStatus;
+import org.onap.vid.model.NameCounter;
+import org.onap.vid.model.RequestReferencesContainer;
+import org.onap.vid.model.ServiceInfo;
+import org.onap.vid.model.ServiceModel;
 import org.onap.vid.model.serviceInstantiation.BaseResource;
 import org.onap.vid.model.serviceInstantiation.InstanceGroup;
 import org.onap.vid.model.serviceInstantiation.ServiceInstantiation;
@@ -49,15 +116,13 @@ import org.onap.vid.mso.model.RequestReferences;
 import org.onap.vid.mso.rest.AsyncRequestStatus;
 import org.onap.vid.mso.rest.AsyncRequestStatusList;
 import org.onap.vid.properties.Features;
+import org.onap.vid.services.AsyncInstantiationBaseTest;
 import org.onap.vid.services.AsyncInstantiationBusinessLogic;
 import org.onap.vid.services.AuditService;
+import org.onap.vid.services.InstantiationTemplatesService;
 import org.onap.vid.services.VersionService;
-import org.onap.vid.utils.DaoUtils;
-import org.onap.vid.config.DataSourceConfig;
-import org.onap.vid.config.JobCommandsConfigWithMockedMso;
-import org.onap.vid.config.MockedAaiClientAndFeatureManagerConfig;
-import org.onap.vid.services.AsyncInstantiationBaseTest;
 import org.onap.vid.testUtils.TestUtils;
+import org.onap.vid.utils.DaoUtils;
 import org.springframework.http.HttpMethod;
 import org.springframework.test.context.ContextConfiguration;
 import org.testng.annotations.BeforeClass;
@@ -66,34 +131,6 @@ import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
 import org.togglz.core.manager.FeatureManager;
 
-import javax.inject.Inject;
-import javax.ws.rs.ProcessingException;
-import java.io.IOException;
-import java.lang.reflect.Method;
-import java.util.*;
-import java.util.function.BiConsumer;
-import java.util.function.Supplier;
-import java.util.stream.Collectors;
-import java.util.stream.IntStream;
-import java.util.stream.Stream;
-
-import static java.util.stream.Collectors.*;
-import static net.javacrumbs.jsonunit.JsonAssert.assertJsonEquals;
-import static net.javacrumbs.jsonunit.JsonMatchers.*;
-import static org.hamcrest.CoreMatchers.*;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.hasProperty;
-import static org.hamcrest.Matchers.hasSize;
-import static org.hamcrest.core.Every.everyItem;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.endsWith;
-import static org.mockito.ArgumentMatchers.*;
-import static org.mockito.Mockito.*;
-import static org.onap.vid.job.Job.JobStatus.*;
-import static org.onap.vid.job.impl.JobSchedulerInitializer.WORKERS_TOPICS;
-import static org.onap.vid.model.JobAuditStatus.SourceStatus.VID;
-import static org.testng.AssertJUnit.*;
-
 //it's more like integration test than UT
 //But it's very hard to test in API test so I use UT
 @ContextConfiguration(classes = {DataSourceConfig.class, SystemProperties.class, MockedAaiClientAndFeatureManagerConfig.class, JobCommandsConfigWithMockedMso.class})
@@ -136,6 +173,9 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
     @Inject
     private CommandUtils commandUtils;
 
+    @Inject
+    private InstantiationTemplatesService instantiationTemplates;
+
     @BeforeClass
     void initServicesInfoService() {
         createInstanceParamsMaps();
@@ -153,7 +193,12 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
     void defineMocks() {
         Mockito.reset(restMso);
         Mockito.reset(aaiClient);
+        Mockito.reset(commandUtils);
         mockAaiClientAnyNameFree();
+
+        when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(true);
+        when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VFMODULE)).thenReturn(true);
+        when(featureManager.isActive(Features.FLAG_2006_VFMODULE_TAKES_TENANT_AND_REGION_FROM_VNF)).thenReturn(true);
     }
 
     @Test
@@ -335,9 +380,7 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
 
            * not looking on audit (yet)
         */
-        reset(restMso);
-        when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(true);
-        when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VFMODULE)).thenReturn(false);
+        when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VFMODULE)).thenReturn(false); // this makes the test pass without mocking the vfModules
         final String SERVICE_REQUEST_ID = UUID.randomUUID().toString();
         final String SERVICE_INSTANCE_ID = UUID.randomUUID().toString();
         final String VNF_REQUEST_ID = UUID.randomUUID().toString();
@@ -380,8 +423,6 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
 
 
         String msoVnfStatus = COMPLETE_STR;
-        when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(true);
-        when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VFMODULE)).thenReturn(true);
         final String SERVICE_REQUEST_ID = UUID.randomUUID().toString();
         final String SERVICE_INSTANCE_ID = UUID.randomUUID().toString();
         final String VNF_REQUEST_ID = UUID.randomUUID().toString();
@@ -395,7 +436,6 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
         //push alacarte with 1 vnf, verify STATUS pending
         UUID uuid = pushALaCarteWithVnf();
         singleServicesAndAssertStatus(JobStatus.PENDING, uuid);
-        reset(restMso);
 
         /*---------- service -----------*/
 
@@ -417,13 +457,11 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
         when(restMso.GetForObject(endsWith(VNF_REQUEST_ID), eq(AsyncRequestStatus.class))).
             thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR));
 
-        try {
-            reset(commandUtils);
-            when(commandUtils.isVfModuleBaseModule(SERVICE_MODEL_VERSION_ID, VF_MODULE_0_MODEL_VERSION_ID)).thenReturn(true);
-            when(commandUtils.isVfModuleBaseModule(SERVICE_MODEL_VERSION_ID, VF_MODULE_1_MODEL_VERSION_ID)).thenReturn(false);
-        } catch (AsdcCatalogException e) {
-
-        }
+        reset(commandUtils);
+        when(commandUtils.isVfModuleBaseModule(eq(SERVICE_MODEL_VERSION_ID),
+            argThat(it -> it.getModelCustomizationId().equals(VF_MODULE_0_MODEL_CUSTOMIZATION_NAME)))).thenReturn(true);
+        when(commandUtils.isVfModuleBaseModule(eq(SERVICE_MODEL_VERSION_ID),
+            argThat(it -> it.getModelCustomizationId().equals(VF_MODULE_1_MODEL_CUSTOMIZATION_NAME)))).thenReturn(false);
 
         /*---------- vf Module without volume group name (base) -----------*/
 
@@ -478,8 +516,6 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
         NetworkDetails networkDetails1 = new NetworkDetails("LukaDoncic", "1");
         NetworkDetails networkDetails2 = new NetworkDetails("KevinDurant", "2");
 
-        reset(restMso);
-
         /*---------- service -----------*/
 
         //mock mso to answer 200 of create service instance request, verify STATUS in progress
@@ -918,7 +954,7 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
         RestObject<AsyncRequestStatus> createStatusResponse,
         RestObject<AsyncRequestStatus> deleteStatusResponse,
         JobStatus expectedJobStatus,
-        int getStatusCounter) throws IOException {
+        int getStatusCounter) {
 
         UUID jobUUID = createAndDeleteIntegrationTest("/payload_jsons/VnfGroupCreate1Delete1None1Request.json",
             "/serviceInstantiation/v7/instanceGroups",
@@ -955,7 +991,7 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
         RestObject<AsyncRequestStatus> createStatusResponse,
         RestObject<AsyncRequestStatus> deleteStatusResponse,
         JobStatus expectedJobStatus,
-        int getStatusCounter) throws IOException {
+        int getStatusCounter) {
 
         createAndDeleteIntegrationTest("/payload_jsons/vnfDelete1Create1Request.json",
             "/serviceInstantiation/v7/serviceInstances/f8791436-8d55-4fde-b4d5-72dd2cf13cfb/vnfs",
@@ -976,12 +1012,12 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
         RestObject<AsyncRequestStatus> createStatusResponse,
         RestObject<AsyncRequestStatus> deleteStatusResponse,
         JobStatus expectedJobStatus,
-        int getStatusCounter) throws IOException, AsdcCatalogException {
+        int getStatusCounter) {
 
-        when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VFMODULE)).thenReturn(true);
-        reset(commandUtils);
-        when(commandUtils.isVfModuleBaseModule("6b528779-44a3-4472-bdff-9cd15ec93450", "f8360508-3f17-4414-a2ed-6bc71161e8db")).thenReturn(true);
-        when(commandUtils.isVfModuleBaseModule("6b528779-44a3-4472-bdff-9cd15ec93450", "25284168-24bb-4698-8cb4-3f509146eca5")).thenReturn(false);
+        when(commandUtils.isVfModuleBaseModule(eq("6b528779-44a3-4472-bdff-9cd15ec93450"),
+            argThat(it -> it.getModelCustomizationName().equals("2017488PasqualeVpe..PASQUALE_base_vPE_BV..module-0")))).thenReturn(true);
+        when(commandUtils.isVfModuleBaseModule(eq("6b528779-44a3-4472-bdff-9cd15ec93450"),
+            argThat(it -> it.getModelCustomizationName().equals("2017488PasqualeVpe..PASQUALE_vRE_BV..module-1")))).thenReturn(false);
 
         createAndDeleteIntegrationTest("/payload_jsons/vfModuleDelete1Create1None1Request.json",
             "/serviceInstantiation/v7/serviceInstances/f8791436-8d55-4fde-b4d5-72dd2cf13cfb/vnfs/VNF_INSTANCE_ID/vfModules",
@@ -994,6 +1030,40 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
             getStatusCounter);
     }
 
+    @DataProvider
+    public static Object[][] pauseInstantiation(Method test) {
+        return new Object[][]{
+            {true, 2},
+            {false, 3}
+        };
+    }
+
+    @Test (dataProvider = "pauseInstantiation")
+    public void viewEdit_existingVnfCreate3VfModulesPauseAfterTheSecond(boolean flag, int expectedNumberOfInvocation) {
+        RestObject<RequestReferencesContainer> createVfModuleResponse = createResponseRandomIds(202);
+        RestObject<AsyncRequestStatus> createStatusResponse = asyncRequestStatusResponseAsRestObject(COMPLETE_STR);
+        JobStatus expectedJobStatus = COMPLETED;
+
+        when(featureManager.isActive(Features.FLAG_2006_PAUSE_VFMODULE_INSTANTIATION_CREATION)).thenReturn(flag);
+
+        when(commandUtils.isVfModuleBaseModule(eq("6b528779-44a3-4472-bdff-9cd15ec93450"),
+            argThat(it -> it.getModelCustomizationName().equals("2017488PasqualeVpe..PASQUALE_base_vPE_BV..module-0")))).thenReturn(true);
+
+        UUID jobUUID = asyncInstantiationBL.pushBulkJob(
+            readJsonResourceFileAsObject("/payload_jsons/vfModuleCreate2AndPauseRequest.json", ServiceInstantiation.class), "userId")
+            .get(0);
+
+        String createPath= "/serviceInstantiation/v7/serviceInstances/f8791436-8d55-4fde-b4d5-72dd2cf13cfb/vnfs/VNF_INSTANCE_ID/vfModules";
+
+        when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), eq(createPath), any())).thenReturn(createVfModuleResponse);
+        when(restMso.GetForObject(endsWith(createVfModuleResponse.get().getRequestReferences().getRequestId()), eq(AsyncRequestStatus.class))).thenReturn(createStatusResponse);
+
+
+        processJobsCountTimesAndAssertStatus(jobUUID, 40, expectedJobStatus);
+
+        verify(restMso, times(expectedNumberOfInvocation)).restCall(eq(HttpMethod.POST), any(), any(), eq(createPath), any());
+    }
+
     //this test is going along with AsyncInstantiationALaCarteApiTest.delete1Create1NetworkFromService API test
     //The API test has only the happy flow scenario, while this test also test additional MSO responses (mostly non happy)
     @Test(dataProvider="createAndDeleteIntegrationTestDataProvider")
@@ -1004,7 +1074,7 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
         RestObject<AsyncRequestStatus> createStatusResponse,
         RestObject<AsyncRequestStatus> deleteStatusResponse,
         JobStatus expectedJobStatus,
-        int getStatusCounter) throws IOException {
+        int getStatusCounter) {
 
         createAndDeleteIntegrationTest("/payload_jsons/networkDelete1Create1Request.json",
             "/serviceInstantiation/v7/serviceInstances/f8791436-8d55-4fde-b4d5-72dd2cf13cfb/networks",
@@ -1025,9 +1095,9 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
         RestObject<AsyncRequestStatus> createStatusResponse,
         RestObject<AsyncRequestStatus> deleteStatusResponse,
         JobStatus expectedJobStatus,
-        int getStatusCounter) throws IOException {
+        int getStatusCounter) {
         UUID jobUUID = asyncInstantiationBL.pushBulkJob(
-            TestUtils.readJsonResourceFileAsObject(payload, ServiceInstantiation.class), "userId")
+            readJsonResourceFileAsObject(payload, ServiceInstantiation.class), "userId")
             .get(0);
 
         when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), eq(createPath), any())).thenReturn(createResponse);
@@ -1049,7 +1119,7 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
     }
 
     @Test
-    public void whenCreateTransportService_thanExpectedPre1806MacroRequestSent() throws IOException {
+    public void whenCreateTransportService_thanExpectedPre1806MacroRequestSent() {
         UUID jobUUID = asyncInstantiationBL.pushBulkJob(generatePre1806MacroTransportServiceInstantiationPayload(null, null),"az2016").get(0);
         RestObject<RequestReferencesContainer> createResponse = createResponseRandomIds(202);
 
@@ -1059,7 +1129,7 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
             .thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR));
         processJobsCountTimesAndAssertStatus(jobUUID, 20, COMPLETED);
 
-        JsonNode expectedJson = TestUtils.readJsonResourceFileAsObject("/payload_jsons/pre_1806_macro_without_cloudConfiguration.json", JsonNode.class);
+        JsonNode expectedJson = readJsonResourceFileAsObject("/payload_jsons/pre_1806_macro_without_cloudConfiguration.json", JsonNode.class);
         ArgumentCaptor<RequestDetailsWrapper> requestCaptor = ArgumentCaptor.forClass(RequestDetailsWrapper.class);
         verify(restMso).restCall(any(), any(), requestCaptor.capture(), any(), any());
         requestCaptor.getAllValues().forEach(x->assertJsonEquals(expectedJson, x));
@@ -1147,7 +1217,7 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
     }
 
     @Test
-    public void whenResumeService_thanExpectedResumeRequestSent() throws IOException {
+    public void whenResumeService_thanExpectedResumeRequestSent() {
         String instanceId = "a565e6ad-75d1-4493-98f1-33234b5c17e2"; //from feRequestResumeMacroService.json
         String originalRequestId = "894089b8-f7f4-418d-81da-34186fd32670"; //from msoResponseGetRequestsOfServiceInstance.json
         String resumeRequestId = randomUuid();
@@ -1181,15 +1251,15 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
     }
 
     @Test
-    public void givenResumeRequest_whenMsoReturnBadResponse_thanJobIsFailed() throws IOException {
+    public void givenResumeRequest_whenMsoReturnBadResponse_thanJobIsFailed() {
         //there is no mocks for restMSO which means restMso return bad response...
         UUID jobUUID = asyncInstantiationBL.pushBulkJob(generateResumeMacroPayload(), "abc").get(0);
         processJobsCountTimesAndAssertStatus(jobUUID, 20, FAILED);
     }
 
     @NotNull
-    private RestObject<AsyncRequestStatusList> createAsyncRequestStatusListByInstanceId() throws IOException {
-        AsyncRequestStatusList asyncRequestStatusList = TestUtils.readJsonResourceFileAsObject(
+    private RestObject<AsyncRequestStatusList> createAsyncRequestStatusListByInstanceId() {
+        AsyncRequestStatusList asyncRequestStatusList = readJsonResourceFileAsObject(
             "/payload_jsons/resume/msoResponseGetRequestsOfServiceInstance.json",
             AsyncRequestStatusList.class);
         RestObject<AsyncRequestStatusList> getRequestByIdResponse = new RestObject<>();
@@ -1198,44 +1268,239 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
         return getRequestByIdResponse;
     }
 
-    private ServiceInstantiation generateResumeMacroPayload() throws IOException {
-        return TestUtils.readJsonResourceFileAsObject("/payload_jsons/resume/feRequestResumeMacroService.json", ServiceInstantiation.class);
+    private ServiceInstantiation generateResumeMacroPayload() {
+        return readJsonResourceFileAsObject("/payload_jsons/resume/feRequestResumeMacroService.json", ServiceInstantiation.class);
     }
 
     @Test
-    public void whenUpgradingAvfModule_thanExpectedReplaceRequestSent() throws IOException {
-        String instanceId = "5d49c3b1-fc90-4762-8c98-e800170baa55"; //from feRequestResumeMacroService.json
+    public void whenUpgradingVfModule_thenExpectedReplaceRequestSent() throws AsdcCatalogException {
+        String currentServiceInstanceId = "6196ab1f-2349-4b32-9b6c-cffeb0ccc79c";
+        String currentVnfInstanceId = "d520268f-7489-4662-be59-f81495b3a069";
+        String currentVfModuleInstanceId = "b0732bed-3ddf-43cc-b193-7f18db84e476";
+
+        assertTestPayloadFitsExpectedIds(upgradeVfModulePayload(), currentServiceInstanceId, currentVnfInstanceId, currentVfModuleInstanceId);
+
         String replaceRequestId = randomUuid();
         String userId = "az2016";
 
+        String modelInvariantId = "b3a1a119-dede-4ed0-b077-2a617fa519a3";
+        String newestModelUuid = "d9a5b318-187e-476d-97f7-a15687a927a9";
 
-        //prepare mocks resume request
-        when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), eq("/serviceInstantiation/v7/serviceInstances/e9993045-cc96-4f3f-bf9a-71b2a400a956/vnfs/5c9c2896-1fe6-4055-b7ec-d0a01e5f9bf5/vfModules/5d49c3b1-fc90-4762-8c98-e800170baa55/replace"), eq(Optional.of(userId))))
-            .thenReturn(createResponse(202, instanceId, replaceRequestId));
+        String expectedMsoReplacePath = "/serviceInstantiation/v7/serviceInstances/"
+            + currentServiceInstanceId + "/vnfs/" + currentVnfInstanceId + "/vfModules/" + currentVfModuleInstanceId + "/replace";
 
+        when(commandUtils.getNewestModelUuid(eq(modelInvariantId))).thenReturn(newestModelUuid);
+        when(commandUtils.getServiceModel(eq(newestModelUuid))).thenReturn(newestServiceModel());
+
+        when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), eq(expectedMsoReplacePath), eq(Optional.of(userId))))
+            .thenReturn(createResponse(202, currentVfModuleInstanceId, replaceRequestId));
 
         when(restMso.GetForObject(eq("/orchestrationRequests/v7/" + replaceRequestId), eq(AsyncRequestStatus.class)))
             .thenReturn(asyncRequestStatusResponseAsRestObject(IN_PROGRESS_STR),
                 asyncRequestStatusResponseAsRestObject(IN_PROGRESS_STR),
                 asyncRequestStatusResponseAsRestObject(COMPLETE_STR));
 
-        ///orchestrationRequests/v7/0174b25a-dd81-45b7-b4af-0057bcc30857
-
-        when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VFMODULE)).thenReturn(true);
         enableAddCloudOwnerOnMsoRequest();
 
-        UUID jobUUID = asyncInstantiationBL.pushBulkJob(generateReplaceVfModulePayload(), userId).get(0);
+
+        UUID jobUUID = asyncInstantiationBL.pushBulkJob(upgradeVfModulePayload(), userId).get(0);
         processJobsCountTimesAndAssertStatus(jobUUID, 20, COMPLETED);
 
 
+        ArgumentCaptor<RequestDetailsWrapper> requestCaptor = ArgumentCaptor.forClass(RequestDetailsWrapper.class);
+        verify(restMso, times(1)).restCall(
+            eq(HttpMethod.POST),
+            eq(RequestReferencesContainer.class),
+            requestCaptor.capture(),
+            eq(expectedMsoReplacePath),
+            eq(Optional.of(userId))
+        );
+
+        JsonNode expectedPayloadToMso = readJsonResourceFileAsObject("/payload_jsons/vfmodule/upgrade_vfmodule_e2e__payload_to_mso.json", JsonNode.class);
+        assertThat(requestCaptor.getValue(), jsonEquals(expectedPayloadToMso).when(IGNORING_ARRAY_ORDER));
+    }
+
+    @Test
+    public void viewEdit_oneNetworkExistsAddAnotherNetwork() {
+        String currentServiceInstanceId = "ce2821fc-3b28-4759-9613-1e514d7563c0";
+        String addNetworkRequestId = randomUuid();
+        String userId = "az2016";
+
+
+        String expectedMsoAddNetworkPath =
+            "/serviceInstantiation/v7/serviceInstances/" + currentServiceInstanceId + "/networks";
+
+        when(restMso.restCall(eq(HttpMethod.POST),eq(RequestReferencesContainer.class),any(), eq(expectedMsoAddNetworkPath), any()))
+            .thenReturn(createResponse(202, currentServiceInstanceId, addNetworkRequestId));
+
+        when(restMso.GetForObject(eq("/orchestrationRequests/v7/" + addNetworkRequestId),eq(AsyncRequestStatus.class)))
+            .thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR));
+
+        List<UUID> uuids= asyncInstantiationBL.pushBulkJob(addNetworkBulkPayload(), userId);
+        assertThat(uuids, hasSize(1));
+        processJobsCountTimesAndAssertStatus(uuids.get(0), 200, COMPLETED);
+
+        verify(restMso, times(1)).restCall(eq(HttpMethod.POST), any(), any(), eq(expectedMsoAddNetworkPath),any());
+        verify(restMso, times(1)).GetForObject(any(),any());
+    }
+
+    @Test
+    public void whenDeletingVfModule_thenExpectedDeleteRequestSent()
+    {
+        String currentServiceInstanceId = "6196ab1f-2349-4b32-9b6c-cffeb0ccc79c";
+        String currentVnfInstanceId = "d520268f-7489-4662-be59-f81495b3a069";
+        String currentVfModuleInstanceId = "b0732bed-3ddf-43cc-b193-7f18db84e476";
+
+        assertTestPayloadFitsExpectedIds(deleteVfModuleBulkPayload(), currentServiceInstanceId, currentVnfInstanceId, currentVfModuleInstanceId);
+
+        String deleteRequestId = randomUuid();
+        String userId = "az2016";
+
+
+        String expectedMsoDeletePath = "/serviceInstantiation/v7/serviceInstances/"
+                + currentServiceInstanceId + "/vnfs/" + currentVnfInstanceId + "/vfModules/" + currentVfModuleInstanceId;
+
+        when(restMso.restCall(eq(HttpMethod.DELETE), eq(RequestReferencesContainer.class), any(), eq(expectedMsoDeletePath), eq(Optional.of(userId))))
+                .thenReturn(createResponse(202, currentVfModuleInstanceId, deleteRequestId));
+
+        when(restMso.GetForObject(eq("/orchestrationRequests/v7/" + deleteRequestId), eq(AsyncRequestStatus.class)))
+                .thenReturn(asyncRequestStatusResponseAsRestObject(IN_PROGRESS_STR),
+                        asyncRequestStatusResponseAsRestObject(IN_PROGRESS_STR),
+                        asyncRequestStatusResponseAsRestObject(COMPLETE_STR));
+
+        enableAddCloudOwnerOnMsoRequest();
+
+
+        UUID jobUUID = asyncInstantiationBL.pushBulkJob(deleteVfModuleBulkPayload(), userId).get(0);
+        processJobsCountTimesAndAssertStatus(jobUUID, 20, COMPLETED);
+
 
-        JsonNode expectedJson = TestUtils.readJsonResourceFileAsObject("/payload_jsons/vfmodule/replace_vfmodule.json", JsonNode.class);
         ArgumentCaptor<RequestDetailsWrapper> requestCaptor = ArgumentCaptor.forClass(RequestDetailsWrapper.class);
-        verify(restMso).restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), requestCaptor.capture(), eq("/serviceInstantiation/v7/serviceInstances/e9993045-cc96-4f3f-bf9a-71b2a400a956/vnfs/5c9c2896-1fe6-4055-b7ec-d0a01e5f9bf5/vfModules/5d49c3b1-fc90-4762-8c98-e800170baa55/replace"), eq(Optional.of(userId)));
-        requestCaptor.getAllValues().forEach(x->assertJsonEquals(expectedJson, x));
+        verify(restMso, times(1)).restCall(
+                eq(HttpMethod.DELETE),
+                eq(RequestReferencesContainer.class),
+                requestCaptor.capture(),
+                eq(expectedMsoDeletePath),
+                eq(Optional.of(userId))
+        );
+
+        assertThat(requestCaptor.getValue(), jsonEquals(getDeleteVfModulePayloadToMso()));
+    }
+
+
+    private ServiceInstantiation deleteVfModuleBulkPayload() {
+        return readJsonResourceFileAsObject("/payload_jsons/vfmodule/delete_1_vfmodule_expected_bulk.json", ServiceInstantiation.class);
+    }
+
+    private ServiceInstantiation addNetworkBulkPayload() {
+        return readJsonResourceFileAsObject("/payload_jsons/Network/one_network_exists_add_another_network_expected_bulk.json", ServiceInstantiation.class);
+    }
+
+    private String getDeleteVfModulePayloadToMso() {
+        return "{ " +
+                "  \"requestDetails\": { " +
+                "    \"requestInfo\": { " +
+                "      \"source\": \"VID\", " +
+                "      \"requestorId\": \"az2016\" " +
+                "    }, " +
+                "    \"modelInfo\": { " +
+                "      \"modelType\": \"vfModule\", " +
+                "      \"modelName\": \"XbiTestModuleReplace..base_ocg..module-0\", " +
+                "      \"modelVersionId\": \"04b21d26-9780-4956-8329-b22b049329f4\", " +
+                "      \"modelVersion\": \"1.0\", " +
+                "      \"modelInvariantId\": \"d887658e-2a89-4baf-83e2-b189601a1a7c\", " +
+                "      \"modelCustomizationName\": \"XbiTestModuleReplace..base_ocg..module-0\", " +
+                "      \"modelCustomizationId\": \"3f1f0fcb-8a88-4612-a794-3912613ed9e8\" " +
+                "    }, " +
+                "    \"cloudConfiguration\": { " +
+                "      \"lcpCloudRegionId\": \"olson5a\", " +
+                "      \"cloudOwner\": \"irma-aic\", " +
+                "      \"tenantId\": \"7ff7b1a4fe954f71ab79d3160ec3eb08\" " +
+                "    } " +
+                "  } " +
+                "}";
+    }
+
+    private void assertTestPayloadFitsExpectedIds(ServiceInstantiation upgradeVfModulePayload, String serviceInstanceId,
+        String vnfInstanceId, String vfModuleInstanceId) {
+        /*
+        Just verifies the test and the input-file are using the same set of instance IDs
+         */
+        assertThat(upgradeVfModulePayload, jsonPartEquals("instanceId", serviceInstanceId));
+        assertThat(upgradeVfModulePayload, jsonNodePresent(
+            "vnfs"
+                + "." + vnfInstanceId
+                + ".vfModules"
+                + ".xbitestmodulereplace0\\.\\.XbiTestModuleReplace\\.\\.base_ocg\\.\\.module-0"
+                + "." + vfModuleInstanceId));
+    }
+
+    private ServiceModel newestServiceModel() {
+        return readJsonResourceFileAsObject("/payload_jsons/vfmodule/upgrade_vfmodule_e2e__target_newest_service_model.json", ServiceModel.class);
+    }
+
+    private ServiceInstantiation upgradeVfModulePayload() {
+        return readJsonResourceFileAsObject("/payload_jsons/vfmodule/upgrade_vfmodule_e2e__fe_input_cypress.json", ServiceInstantiation.class);
+    }
+
+    @Test
+    public void deployService_failIt_retryDeploy_getRetryAsTemplate_makeSureFalsyIsFailedInTemplate() {
+
+        final String SERVICE_REQUEST_ID = UUID.randomUUID().toString();
+
+        //push alacarte with 1 vnf, verify STATUS pending
+        UUID uuid = pushALaCarteWithVnf();
+        singleServicesAndAssertStatus(JobStatus.PENDING, uuid);
+
+        //mock mso to answer 200 of create service instance request, verify STATUS in progress
+        when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), endsWith("serviceInstances"), any())).thenReturn(
+            createResponse(200, SERVICE_INSTANCE_ID, SERVICE_REQUEST_ID));
+
+        //mock mso to answer FAILED for service instance create
+        final RestObject<AsyncRequestStatus> failedResponse = asyncRequestStatusResponseAsRestObject(FAILED_STR);
+        final String failureDescription = "Some deep failure";
+        failedResponse.get().request.requestStatus.setStatusMessage(failureDescription);
+        when(restMso.GetForObject(endsWith(SERVICE_REQUEST_ID), eq(AsyncRequestStatus.class))).
+            thenReturn(failedResponse);
+
+        //Wait till job failed
+        processJobsCountTimesAndAssertStatus(uuid, 3, FAILED);
+
+        //make sure retry request jas isFailed = true, and status message is with failureDescription
+        ServiceInstantiation retryRequest = asyncInstantiationBL.getBulkForRetry(uuid);
+        assertTrue(retryRequest.getIsFailed());
+        assertEquals(failureDescription, retryRequest.getStatusMessage());
+
+        //deploy retry job and it's template
+        UUID retryUuid = asyncInstantiationBL.pushBulkJob(retryRequest, USER_ID).get(0);
+        ServiceInstantiation templateOfRetry = instantiationTemplates.getJobRequestAsTemplate(retryUuid);
+
+        //make sure the template request has isFailed = false, and no status message
+        assertFalse(templateOfRetry.getIsFailed());
+        assertNull(templateOfRetry.getStatusMessage());
     }
 
-    private ServiceInstantiation generateReplaceVfModulePayload() throws IOException {
-        return TestUtils.readJsonResourceFileAsObject("/payload_jsons/vfmodule/replace_vfmodule_fe_input.json", ServiceInstantiation.class);
+    @Test
+    public void oneVnfExistsAddAnotherVnf(){
+        final String VNF_REQUEST_ID = UUID.randomUUID().toString();
+        final String VNF_INSTANCE_ID = UUID.randomUUID().toString();
+
+        ServiceInstantiation serviceInstantiation = readJsonResourceFileAsObject("/payload_jsons/vnf/one_vnf_exists_add_another_vnf_expected_bulk.json",
+            ServiceInstantiation.class);
+        List<UUID> uuids = asyncInstantiationBL.pushBulkJob(serviceInstantiation, USER_ID);
+        assertThat(uuids, hasSize(1));
+
+        //mock mso to answer 200 of create vnf instance request
+        when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), endsWith("e6cc1c4f-05f7-49bc-8e86-ac2eb92baaaa/vnfs"), any())).thenReturn(
+            createResponse(200, VNF_INSTANCE_ID, VNF_REQUEST_ID));
+
+        //mock mso to answer msoVnfStatus (COMPLETE) for vnf creation status,
+        when(restMso.GetForObject(endsWith(VNF_REQUEST_ID), eq(AsyncRequestStatus.class))).
+            thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR));
+
+        processJobsCountTimesAndAssertStatus(uuids.get(0), 200, COMPLETED);
+        verify(restMso, times(1)).restCall(eq(HttpMethod.POST), any(), any(), endsWith("e6cc1c4f-05f7-49bc-8e86-ac2eb92baaaa/vnfs"), any());
+        verify(restMso, times(1)).GetForObject(any(), any());
     }
+
 }