From e601bbdc43bae9a08e2e10c5139a6f76b47860d7 Mon Sep 17 00:00:00 2001 From: Einat Vinouze Date: Tue, 16 Jul 2019 17:17:36 +0300 Subject: Implant vid-app-common org.onap.vid.job (main and test) Issue-ID: VID-378 Change-Id: I41b0bdc2c4e3635f3f3319b1cd63cefc61912dfc Signed-off-by: Einat Vinouze Signed-off-by: Ittay Stern --- .../org/onap/vid/aai/AAITreeConverterTest.java | 134 +- .../test/java/org/onap/vid/aai/AaiClientTest.java | 184 ++- .../onap/vid/aai/AaiResponseTranslatorTest.java | 6 +- .../onap/vid/asdc/parser/ToscaParserImpl2Test.java | 86 +- .../vid/asdc/parser/ToscaParserInflatorTest.java | 29 +- .../vid/asdc/parser/VidNotionsBuilderTest.java | 340 ++++- .../WorkflowRequestDetailTest.java | 6 +- .../java/org/onap/vid/config/DataSourceConfig.java | 2 +- .../java/org/onap/vid/config/JobAdapterConfig.java | 25 +- .../vid/config/JobCommandsConfigWithMockedMso.java | 175 ++- .../org/onap/vid/controller/AaiControllerTest.java | 56 +- ...ServiceInstanceStandardQueryControllerTest.java | 26 +- .../org/onap/vid/controller/LocalWebConfig.java | 5 +- .../onap/vid/controller/MsoControllerNewTest.java | 12 +- .../org/onap/vid/controller/MsoControllerTest.java | 5 +- .../onap/vid/controller/ToscaParserMockHelper.java | 20 +- .../org/onap/vid/controller/VidControllerTest.java | 2 +- .../vid/dal/AsyncInstantiationRepositoryTest.java | 103 ++ .../org/onap/vid/job/command/CommandUtilsTest.java | 4 +- .../job/command/InProgressStatusServiceTest.java | 83 +- .../vid/job/command/InstanceGroupCommandTest.java | 71 +- .../vid/job/command/JobCommandFactoryTest.java | 8 +- .../vid/job/command/MacroServiceCommandTest.java | 136 ++ .../job/command/MsoResultHandlerServiceTest.java | 95 ++ .../onap/vid/job/command/ResourceCommandTest.java | 258 +++- .../ResourceInProgressStatusCommandTest.java | 60 - .../ServiceInProgressStatusCommandTest.java | 157 +-- .../vid/job/command/WatchChildrenJobsBLTest.java | 6 +- .../onap/vid/job/command/WatchingCommandTest.java | 97 -- .../impl/AsyncInstantiationIntegrationTest.java | 1020 +++++++++------ .../DeleteOldJobsSchedulerInitializerTest.java | 55 + .../onap/vid/job/impl/DeleteOldJobsWorkerTest.java | 43 + .../java/org/onap/vid/job/impl/JobAdapterTest.java | 43 +- .../java/org/onap/vid/job/impl/JobWorkerTest.java | 13 +- .../org/onap/vid/model/JobAuditStatusTest.java | 12 +- .../org/onap/vid/model/aaiTree/VpnBindingKtTest.kt | 16 + .../org/onap/vid/mso/MsoBusinessLogicImplTest.java | 181 +-- .../vid/mso/MsoOperationalEnvironmentTest.java | 17 +- .../onap/vid/mso/rest/MsoRestClientNewTest.java | 36 +- .../org/onap/vid/mso/rest/RequestDetailsTest.java | 23 +- .../onap/vid/services/AAITreeNodeBuilderTest.java | 469 ++++++- .../org/onap/vid/services/AaiServiceImplTest.java | 1354 ++++++++++---------- .../vid/services/AsyncInstantiationBaseTest.java | 119 +- .../AsyncInstantiationBusinessLogicTest.java | 1105 +++++++--------- .../onap/vid/services/AuditServiceImplTest.java | 99 +- .../onap/vid/services/JobsBrokerServiceTest.java | 390 ++++-- .../vid/services/PortDetailsTranslatorTest.java | 10 +- .../vid/services/RoleGenaratorServiceImplTest.java | 4 +- .../java/org/onap/vid/testUtils/TestUtils.java | 51 +- 49 files changed, 4561 insertions(+), 2690 deletions(-) create mode 100644 vid-app-common/src/test/java/org/onap/vid/dal/AsyncInstantiationRepositoryTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/job/command/MacroServiceCommandTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/job/command/MsoResultHandlerServiceTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/job/command/ResourceInProgressStatusCommandTest.java delete mode 100644 vid-app-common/src/test/java/org/onap/vid/job/command/WatchingCommandTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/job/impl/DeleteOldJobsSchedulerInitializerTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/job/impl/DeleteOldJobsWorkerTest.java create mode 100644 vid-app-common/src/test/java/org/onap/vid/model/aaiTree/VpnBindingKtTest.kt (limited to 'vid-app-common/src/test/java/org') diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/AAITreeConverterTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/AAITreeConverterTest.java index 5bdfd1207..560e6cb5f 100644 --- a/vid-app-common/src/test/java/org/onap/vid/aai/AAITreeConverterTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/aai/AAITreeConverterTest.java @@ -25,17 +25,16 @@ import org.mockito.InjectMocks; import org.mockito.MockitoAnnotations; import org.onap.vid.aai.util.AAITreeConverter; import org.onap.vid.model.Action; -import org.onap.vid.model.aaiTree.AAITreeNode; -import org.onap.vid.model.aaiTree.Network; +import org.onap.vid.model.aaiTree.*; import org.onap.vid.model.aaiTree.ServiceInstance; -import org.onap.vid.model.aaiTree.VfModule; -import org.onap.vid.model.aaiTree.Vnf; +import org.onap.vid.mso.model.CloudConfiguration; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.util.List; +import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.emptyOrNullString; import static org.hamcrest.Matchers.hasKey; @@ -43,6 +42,7 @@ import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.onap.vid.asdc.parser.ToscaParserImpl2.Constants.A_LA_CARTE; +import static org.testng.Assert.assertNull; public class AAITreeConverterTest { @@ -59,28 +59,41 @@ public class AAITreeConverterTest { AAITreeNode aaiTree = generateAaiTreeToConvert(0, 0); - ServiceInstance result = aaiTreeConverter.convertTreeToUIModel(aaiTree, "global-customer-id", "service-type", A_LA_CARTE); + ServiceInstance result = aaiTreeConverter.convertTreeToUIModel(aaiTree, "global-customer-id", "service-type", A_LA_CARTE, "", ""); assertService(result, 0, 0, true); } @Test - public void testConvertTreeToUIModel_MultipleChildren() throws Exception { + public void testConvertTreeToUIModel_MultipleChildren() { AAITreeNode aaiTree = generateAaiTreeToConvert(2, 2); - ServiceInstance serviceInstance = aaiTreeConverter.convertTreeToUIModel(aaiTree, "global-customer-id", "service-type", null); + ServiceInstance serviceInstance = aaiTreeConverter.convertTreeToUIModel(aaiTree, "global-customer-id", "service-type", null, "", ""); assertService(serviceInstance, 2, 2, false); int nodesCounter = 0; assertThat(serviceInstance.getVnfs().entrySet(), hasSize(2)); - assertVnf(serviceInstance.getVnfs().get("vnf-model-version-id:00"+(nodesCounter++)), 0, 0, false); - assertVnf(serviceInstance.getVnfs().get("vnf-model-version-id:00"+(nodesCounter++)), 0, 0, false); + assertVnf(serviceInstance.getVnfs().get("vnf-instance-id" + (nodesCounter++)), 0, 0); + assertVnf(serviceInstance.getVnfs().get("vnf-instance-id" + (nodesCounter++)), 0, 0); assertThat(serviceInstance.getNetworks().entrySet(), hasSize(2)); - assertNetwork(serviceInstance.getNetworks().get("network-model-version-id:00"+(nodesCounter++)), false); - assertNetwork(serviceInstance.getNetworks().get("network-model-version-id:00"+(nodesCounter)), false); + assertNetwork(serviceInstance.getNetworks().get("network-instance-id" + (nodesCounter++)), false); + assertNetwork(serviceInstance.getNetworks().get("network-instance-id" + (nodesCounter++)), false); + + assertThat(serviceInstance.getVnfGroups().size(), equalTo(1)); + assertThat(serviceInstance.getVnfGroups().get("vnf-group-id" + (nodesCounter++)).getInstanceId(), startsWith("vnf-group-id")); + + assertThat(serviceInstance.getCollectionResources().size(), equalTo(1)); + CollectionResource cr = serviceInstance.getCollectionResources().get("cr-id" + (nodesCounter++)); + assertThat(cr.getInstanceId(), startsWith("cr-id")); + + assertThat(cr.getNcfs().size(), equalTo(1)); + assertThat(cr.getNcfs().get("ncf-id").getInstanceId(), startsWith("ncf-id")); + + assertThat(serviceInstance.getExistingVNFCounterMap().get("vnf-model-customization-id"), equalTo(2L)); + assertThat(serviceInstance.getExistingNetworksCounterMap().get("network-model-customization-id"), equalTo(2L)); } @DataProvider @@ -99,7 +112,7 @@ public class AAITreeConverterTest { int nodesCounter = 0; for (Boolean customizationName: vfModules) { - vnfTreeNode.getChildren().add(createVfModule(nodesCounter++, customizationName)); + vnfTreeNode.getChildren().add(createVfModule(customizationName)); } for (Boolean customizationName: networks) { @@ -108,24 +121,21 @@ public class AAITreeConverterTest { Vnf actualVnf = Vnf.from(vnfTreeNode); - assertVnf(actualVnf, vfModules.size(), networks.size(), false); + assertVnf(actualVnf, vfModules.size(), networks.size()); nodesCounter = 0; for (Boolean customizationName: vfModules) { String key = customizationName ? "vfModule key in model" : "vfModule-model-version-id"; assertThat(actualVnf.getVfModules(), hasKey(key)); - assertThat(actualVnf.getVfModules().get(key), hasKey(key + ":00" + nodesCounter)); - VfModule actualVfModule = actualVnf.getVfModules().get(key).get(key + ":00" + nodesCounter); + assertThat(actualVnf.getVfModules().get(key), hasKey("vfModule-instance-id")); + VfModule actualVfModule = actualVnf.getVfModules().get(key).get("vfModule-instance-id"); assertVfModule(actualVfModule, customizationName); - nodesCounter++; } for (Boolean customizationName: networks) { - String key = customizationName ? "network key in model" : "network-model-version-id"; - - assertThat(actualVnf.getNetworks(), hasKey(key + ":00" + nodesCounter)); - Network actualNetwork = actualVnf.getNetworks().get(key + ":00" + nodesCounter); + assertThat(actualVnf.getNetworks(), hasKey("network-instance-id" + nodesCounter)); + Network actualNetwork = actualVnf.getNetworks().get("network-instance-id" + nodesCounter); assertNetwork(actualNetwork, customizationName); nodesCounter++; } @@ -142,45 +152,79 @@ public class AAITreeConverterTest { private AAITreeNode createVnf(int uniqueNumber, boolean hasCustomizationName) { AAITreeNode vnfTreeNode = new AAITreeNode(); - vnfTreeNode.setId("vnf-instance-id"); + vnfTreeNode.setId("vnf-instance-id" + uniqueNumber); vnfTreeNode.setName("vnf-instance-name"); - vnfTreeNode.setType("generic-vnf"); + vnfTreeNode.setType(NodeType.GENERIC_VNF); vnfTreeNode.setModelVersionId("vnf-model-version-id"); + vnfTreeNode.setModelCustomizationId("vnf-model-customization-id"); if (hasCustomizationName) { vnfTreeNode.setModelCustomizationName("vnf model customization name"); vnfTreeNode.setKeyInModel("vnf key in model"); } - vnfTreeNode.setUniqueNumber(uniqueNumber); return vnfTreeNode; } - private AAITreeNode createVfModule(int uniqueNumber, boolean hasCustomizationName) { + private AAITreeNode createVnfGroup(int uniqueNumber) { + AAITreeNode treeNode = new AAITreeNode(); + treeNode.setId("vnf-group-id" + uniqueNumber); + treeNode.setType(NodeType.INSTANCE_GROUP); + treeNode.getAdditionalProperties().put("instance-group-type", "vnfGroup-type"); + return treeNode; + } + + private AAITreeNode createCollectionResource(int uniqueNumber) { + AAITreeNode treeNode = new AAITreeNode(); + treeNode.setId("cr-id" + uniqueNumber); + treeNode.setType(NodeType.COLLECTION_RESOURCE); + treeNode.getChildren().add(createNCF()); + return treeNode; + } + + private AAITreeNode createNCF() { + AAITreeNode treeNode = new AAITreeNode(); + treeNode.setId("ncf-id"); + treeNode.setType(NodeType.INSTANCE_GROUP); + treeNode.getAdditionalProperties().put("instance-group-type", "L3-NETWORK"); + return treeNode; + } + + @Test + public void givenPlacementIsNull_whenConvertToNetwork_relevantFieldsAreAlsoNull() { + AAITreeNode aaiTreeNode = new AAITreeNode(); + aaiTreeNode.setType(NodeType.NETWORK); + Network actualNetwork = Network.from(aaiTreeNode); + assertNull(actualNetwork.getCloudOwner()); + assertNull(actualNetwork.getLcpCloudRegionId()); + assertNull(actualNetwork.getTenantId()); + } + + private AAITreeNode createVfModule(boolean hasCustomizationName) { AAITreeNode vfModuleTreeNode = new AAITreeNode(); vfModuleTreeNode.setId("vfModule-instance-id"); vfModuleTreeNode.setName("vfModule-instance-name"); - vfModuleTreeNode.setType("vf-module"); + vfModuleTreeNode.setType(NodeType.VF_MODULE); vfModuleTreeNode.setModelVersionId("vfModule-model-version-id"); + vfModuleTreeNode.setModelCustomizationId("vfModule-model-customization-id"); if (hasCustomizationName) { vfModuleTreeNode.setModelCustomizationName("vfModule model customization name"); vfModuleTreeNode.setKeyInModel("vfModule key in model"); } - vfModuleTreeNode.setUniqueNumber(uniqueNumber); - + vfModuleTreeNode.setCloudConfiguration(new CloudConfiguration("lcpRegion2", "tenant3", "cloudOwner1")); return vfModuleTreeNode; } private AAITreeNode createNetwork(int uniqueNumber, boolean hasCustomizationName) { AAITreeNode networkTreeNode = new AAITreeNode(); - networkTreeNode.setId("network-instance-id"); + networkTreeNode.setId("network-instance-id" + uniqueNumber); networkTreeNode.setName("network-instance-name"); - networkTreeNode.setType("l3-network"); + networkTreeNode.setType(NodeType.NETWORK); networkTreeNode.setModelVersionId("network-model-version-id"); + networkTreeNode.setModelCustomizationId("network-model-customization-id"); if (hasCustomizationName) { networkTreeNode.setModelCustomizationName("network model customization name"); networkTreeNode.setKeyInModel("network key in model"); } - networkTreeNode.setUniqueNumber(uniqueNumber); - + networkTreeNode.setCloudConfiguration(new CloudConfiguration("auk51a", "b530fc990b6d4334bd45518bebca6a51", "att-nc")); return networkTreeNode; } @@ -196,17 +240,16 @@ public class AAITreeConverterTest { assertThat(serviceInstance.getIsALaCarte(), is(isALaCarte)); } - private void assertVnf(Vnf actualVnf, int expectedVfModules, int expectedNetworks, boolean hasCustomizationName) { - assertThat(actualVnf.getInstanceId(), is("vnf-instance-id")); + private void assertVnf(Vnf actualVnf, int expectedVfModules, int expectedNetworks) { + assertThat(actualVnf.getInstanceId(), containsString("vnf-instance-id")); assertThat(actualVnf.getInstanceName(), is("vnf-instance-name")); assertThat(actualVnf.getAction(), is(Action.None)); assertThat(actualVnf.getModelInfo().getModelType(), is("vnf")); assertThat(actualVnf.getModelInfo().getModelVersionId(), is("vnf-model-version-id")); assertThat(actualVnf.getVfModules().entrySet(), hasSize(expectedVfModules)); assertThat(actualVnf.getNetworks().entrySet(), hasSize(expectedNetworks)); - assertThat(actualVnf.getTrackById(), is(not(emptyOrNullString()))); - String expectedCustomizationName = hasCustomizationName ? "vnf model customization name" : null; - assertThat(actualVnf.getModelInfo().getModelCustomizationName(), is(expectedCustomizationName)); + assertThat(actualVnf.getTrackById(), containsString("vnf-instance-id")); + assertNull(actualVnf.getModelInfo().getModelCustomizationName()); } private void assertVfModule(VfModule actualVfModule, boolean hasCustomizationName) { @@ -215,20 +258,27 @@ public class AAITreeConverterTest { assertThat(actualVfModule.getAction(), is(Action.None)); assertThat(actualVfModule.getModelInfo().getModelType(), is("vfModule")); assertThat(actualVfModule.getModelInfo().getModelVersionId(), is("vfModule-model-version-id")); - assertThat(actualVfModule.getTrackById(), is(not(emptyOrNullString()))); + assertThat(actualVfModule.getTrackById(), is("vfModule-instance-id")); String expectedCustomizationName = hasCustomizationName ? "vfModule model customization name" : null; assertThat(actualVfModule.getModelInfo().getModelCustomizationName(), is(expectedCustomizationName)); + assertThat(actualVfModule.getCloudOwner(), is("cloudOwner1")); + assertThat(actualVfModule.getLcpCloudRegionId(), is("lcpRegion2")); + assertThat(actualVfModule.getTenantId(), is("tenant3")); } private void assertNetwork(Network actualNetwork, boolean hasCustomizationName) { - assertThat(actualNetwork.getInstanceId(), is("network-instance-id")); + assertThat(actualNetwork.getInstanceId(), containsString("network-instance-id")); assertThat(actualNetwork.getInstanceName(), is("network-instance-name")); assertThat(actualNetwork.getAction(), is(Action.None)); assertThat(actualNetwork.getModelInfo().getModelType(), is("network")); assertThat(actualNetwork.getModelInfo().getModelVersionId(), is("network-model-version-id")); - assertThat(actualNetwork.getTrackById(), is(not(emptyOrNullString()))); + assertThat(actualNetwork.getTrackById(), containsString("network-instance-id")); String expectedCustomizationName = hasCustomizationName ? "network model customization name" : null; assertThat(actualNetwork.getModelInfo().getModelCustomizationName(), is(expectedCustomizationName)); + assertThat(actualNetwork.getCloudOwner(), is("att-nc")); + assertThat(actualNetwork.getLcpCloudRegionId(), is("auk51a")); + assertThat(actualNetwork.getTenantId(), is("b530fc990b6d4334bd45518bebca6a51")); + } private AAITreeNode generateAaiTreeToConvert(int numberOfVnfs, int numberOfNetworks) { @@ -236,6 +286,7 @@ public class AAITreeConverterTest { AAITreeNode aaiTree = new AAITreeNode(); aaiTree.setId("service-instance-id"); aaiTree.setName("service-instance-name"); + aaiTree.setType(NodeType.SERVICE_INSTANCE); for (int i = 0; i < numberOfVnfs; i++) { aaiTree.getChildren().add(createVnf(counter++, false)); @@ -245,6 +296,9 @@ public class AAITreeConverterTest { aaiTree.getChildren().add(createNetwork(counter++, false)); } + aaiTree.getChildren().add(createVnfGroup(counter++)); + aaiTree.getChildren().add(createCollectionResource(counter++)); + return aaiTree; } -} +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/AaiClientTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/AaiClientTest.java index fdeeb0076..b2d8e85fa 100644 --- a/vid-app-common/src/test/java/org/onap/vid/aai/AaiClientTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/aai/AaiClientTest.java @@ -20,9 +20,51 @@ package org.onap.vid.aai; +import static java.util.stream.Collectors.toList; +import static org.apache.commons.lang3.StringUtils.equalsIgnoreCase; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.either; +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.sameInstance; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.onap.vid.utils.KotlinUtilsKt.JACKSON_OBJECT_MAPPER; +import static org.onap.vid.utils.Unchecked.toURI; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.fail; + import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.net.URI; +import java.security.cert.CertificateException; +import java.util.ArrayList; +import java.util.Map; +import java.util.function.BiConsumer; +import java.util.function.Function; +import java.util.stream.Stream; +import javax.crypto.BadPaddingException; +import javax.net.ssl.SSLHandshakeException; +import javax.servlet.ServletContext; +import javax.ws.rs.ProcessingException; +import javax.ws.rs.client.Client; +import javax.ws.rs.core.Response; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.apache.commons.lang3.exception.ExceptionUtils; @@ -32,10 +74,20 @@ import org.apache.http.HttpStatus; import org.mockito.Mockito; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; -import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.RelatedToProperty; import org.onap.vid.aai.model.AaiGetTenatns.GetTenantsResponse; -import org.onap.vid.aai.model.*; -import org.onap.vid.aai.util.*; +import org.onap.vid.aai.model.CustomQuerySimpleResult; +import org.onap.vid.aai.model.ModelVer; +import org.onap.vid.aai.model.ModelVersions; +import org.onap.vid.aai.model.PortDetailsTranslator; +import org.onap.vid.aai.model.Properties; +import org.onap.vid.aai.model.RelatedToProperty; +import org.onap.vid.aai.model.ResourceType; +import org.onap.vid.aai.model.SimpleResult; +import org.onap.vid.aai.util.AAIRestInterface; +import org.onap.vid.aai.util.CacheProvider; +import org.onap.vid.aai.util.HttpsAuthClient; +import org.onap.vid.aai.util.ServletRequestHelper; +import org.onap.vid.aai.util.SystemPropertyHelper; import org.onap.vid.controller.LocalWebConfig; import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.model.Subscriber; @@ -55,37 +107,6 @@ import org.testng.annotations.Test; import sun.security.provider.certpath.SunCertPathBuilderException; import sun.security.validator.ValidatorException; -import javax.crypto.BadPaddingException; -import javax.net.ssl.SSLHandshakeException; -import javax.servlet.ServletContext; -import javax.ws.rs.ProcessingException; -import javax.ws.rs.client.Client; -import javax.ws.rs.core.Response; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.net.URI; -import java.security.cert.CertificateException; -import java.util.ArrayList; -import java.util.Map; -import java.util.function.BiConsumer; -import java.util.function.Function; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import static org.apache.commons.lang3.StringUtils.equalsIgnoreCase; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.mockito.ArgumentMatchers.nullable; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyBoolean; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.argThat; -import static org.mockito.Matchers.eq; -import static org.mockito.Matchers.isNull; -import static org.mockito.Mockito.*; -import static org.onap.vid.utils.Unchecked.toURI; -import static org.testng.Assert.*; - @ContextConfiguration(classes = {LocalWebConfig.class, SystemProperties.class}) @WebAppConfiguration public class AaiClientTest { @@ -345,7 +366,7 @@ public class AaiClientTest { Assert.assertTrue(response.t.length> 0); - Assert.assertEquals(tenants[0].cloudOwner,"att-aic-cloud-owner"); + Assert.assertEquals(tenants[0].cloudOwner,"irma-aic-cloud-owner"); } final String tenantResponseRaw ="" + @@ -355,10 +376,10 @@ public class AaiClientTest { "\"relationship-list\": {" + "\"relationship\": [{" + "\"related-to\": \"tenant\"," + - "\"related-link\": \"/aai/v11/cloud-infrastructure/cloud-regions/cloud-region/att-aic/AAIAIC25/tenants/tenant/092eb9e8e4b7412e8787dd091bc58e86\"," + + "\"related-link\": \"/aai/v11/cloud-infrastructure/cloud-regions/cloud-region/irma-aic/AAIAIC25/tenants/tenant/092eb9e8e4b7412e8787dd091bc58e86\"," + "\"relationship-data\": [{" + "\"relationship-key\": \"cloud-region.cloud-owner\"," + - "\"relationship-value\": \"att-aic-cloud-owner\"" + + "\"relationship-value\": \"irma-aic-cloud-owner\"" + "}," + "{" + "\"relationship-key\": \"cloud-region.cloud-region-id\"," + @@ -427,11 +448,11 @@ public class AaiClientTest { " {" + " \"related-to\": \"volume-group\"," + " \"relationship-label\": \"org.onap.relationships.inventory.Uses\"," + - " \"related-link\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/volume-groups/volume-group/66013ebe-0c81-44b9-a24f-7c6acba73a39\"," + + " \"related-link\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/irma-aic/rdm5b/volume-groups/volume-group/66013ebe-0c81-44b9-a24f-7c6acba73a39\"," + " \"relationship-data\": [" + " {" + " \"relationship-key\": \"cloud-region.cloud-owner\"," + - " \"relationship-value\": \"att-aic\"" + + " \"relationship-value\": \"irma-aic\"" + " }," + " {" + " \"relationship-key\": \"cloud-region.cloud-region-id\"," + @@ -446,11 +467,11 @@ public class AaiClientTest { " {" + " \"related-to\": \"vserver\"," + " \"relationship-label\": \"org.onap.relationships.inventory.Uses\"," + - " \"related-link\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/db1818f7f2e34862b378bfb2cc520f91/vservers/vserver/5eef9f6d-9933-4bc6-9a1a-862d61309437\"," + + " \"related-link\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/irma-aic/rdm5b/tenants/tenant/db1818f7f2e34862b378bfb2cc520f91/vservers/vserver/5eef9f6d-9933-4bc6-9a1a-862d61309437\"," + " \"relationship-data\": [" + " {" + " \"relationship-key\": \"cloud-region.cloud-owner\"," + - " \"relationship-value\": \"att-aic\"" + + " \"relationship-value\": \"irma-aic\"" + " }," + " {" + " \"relationship-key\": \"cloud-region.cloud-region-id\"," + @@ -490,7 +511,7 @@ public class AaiClientTest { GetTenantsResponse tenant = aaiClientMock.getHomingDataByVfModule("vnfInstanceId", "vfModuleId"); - Assert.assertEquals(tenant.cloudOwner,"att-aic"); + Assert.assertEquals(tenant.cloudOwner,"irma-aic" ); Assert.assertEquals(tenant.cloudRegionID,"rdm5b"); Assert.assertEquals(tenant.tenantID,"db1818f7f2e34862b378bfb2cc520f91"); @@ -601,7 +622,7 @@ public class AaiClientTest { // double each case to propagateExceptions = true/false, to verify that "don't propagate" really still work ImmutableList.of(l.getLeft(), l.getRight(), true).toArray(), ImmutableList.of(l.getLeft(), l.getRight(), false).toArray() - )).collect(Collectors.toList()).toArray(new Object[][]{}); + )).collect(toList()).toArray(new Object[][]{}); } private static UncheckedBiConsumer mockExceptionOnClientProvider(Exception e) { @@ -734,6 +755,83 @@ public class AaiClientTest { }; } + @Test + public void testGetLatestVersionByInvariantId() throws IOException { + + ModelVersions modelVersions = JACKSON_OBJECT_MAPPER.readValue("" + + "{\n" + + " \"results\": [\n" + + " {\n" + + " \"model\": {\n" + + " \"model-invariant-id\": \"f6342be5-d66b-4d03-a1aa-c82c3094c4ea\",\n" + + " \"model-type\": \"service\",\n" + + " \"resource-version\": \"1534274421300\"\n" + + " }\n" + + " },\n" + + " {\n" + + " \"model-ver\": {\n" + + " \"model-version-id\": \"a92f899d-a3ec-465b-baed-1663b0a5aee1\",\n" + + " \"model-name\": \"NCM_VLAN_SVC_ym161f\",\n" + + " \"model-version\": \"bbb\",\n" + + " \"distribution-status\": \"DISTRIBUTION_COMPLETE_OK\",\n" + + " \"model-description\": \"Network Collection service for vLAN tagging\",\n" + + " \"resource-version\": \"1534788756086\"\n" + + " }\n" + + " },\n" + + " {\n" + + " \"model-ver\": {\n" + + " \"model-version-id\": \"d2fda667-e92e-4cfa-9620-5da5de01a319\",\n" + + " \"model-name\": \"NCM_VLAN_SVC_ym161f\",\n" + + " \"model-version\": \"aaa\",\n" + + " \"distribution-status\": \"DISTRIBUTION_COMPLETE_OK\",\n" + + " \"model-description\": \"Network Collection service for vLAN tagging\",\n" + + " \"resource-version\": \"1534444087221\"\n" + + " }\n" + + " }]}", ModelVersions.class); + + + final AaiClient aaiClient = new AaiClient(null, null, null); + + assertThat(aaiClient.toModelVerStream(modelVersions).collect(toList()), + containsInAnyOrder( + hasProperty("modelVersionId", is("a92f899d-a3ec-465b-baed-1663b0a5aee1")), + hasProperty("modelVersionId", is("d2fda667-e92e-4cfa-9620-5da5de01a319")) + )); + + } + + @DataProvider + public static Object[][] versionsDataProvider() { + return new Object[][] { + { Stream.of("10","20","30"), "30" }, + { Stream.of("10","20","20"), "20" }, + { Stream.of("c","b","a"), "c" }, + { Stream.of("1.0","2.0","1.8"), "2.0" }, + { Stream.of("1.0.7","2.0.2","2.0.9"), "2.0.9" }, + { Stream.of("0","0","0"), "0" }, + { Stream.of("","10"), "10" }, + + }; + } + + @Test(dataProvider = "versionsDataProvider") + public void maxModelVer(Stream input, String expected) { + Stream modelVerStream = input.map(version -> { + ModelVer mv = new ModelVer(); + mv.setModelVersion(version); + return mv; + }); + + final AaiClient aaiClient = new AaiClient(null, null, null); + + assertThat(aaiClient.maxModelVer(modelVerStream), hasProperty("modelVersion", is(expected))); + } + + @Test(expectedExceptions = GenericUncheckedException.class) + public void maxModelVerException() { + final AaiClient aaiClient = new AaiClient(null, null, null); + aaiClient.maxModelVer(Stream.of(new ModelVer())); + } @Test(dataProvider = "cloudRegionAndTenantDataProvider") public void getCloudRegionAndTenantByVnfId(String tenantName, String cloudRegionId) throws JsonProcessingException { SimpleResult tenant = new SimpleResult(); diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/AaiResponseTranslatorTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/AaiResponseTranslatorTest.java index 12f7429eb..045488605 100644 --- a/vid-app-common/src/test/java/org/onap/vid/aai/AaiResponseTranslatorTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/aai/AaiResponseTranslatorTest.java @@ -45,9 +45,9 @@ public class AaiResponseTranslatorTest { " \"results\": [{" + " \"id\": \"2979590232\"," + " \"node-type\": \"cloud-region\"," + - " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/SDNO-S-BcloudReg-E1802\"," + + " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/irma-aic/SDNO-S-BcloudReg-E1802\"," + " \"properties\": {" + - " \"cloud-owner\": \"att-aic\"," + + " \"cloud-owner\": \"irma-aic\"," + " \"cloud-region-id\": \"THE-EXPECTED-REGION-ID\"," + " \"sriov-automation\": false," + " \"resource-version\": \"1513631040564\"" + @@ -122,7 +122,7 @@ public class AaiResponseTranslatorTest { "{" + " \"results\": [{" + " \"node-type\": \"cloud-region\"," + - " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/SDNO-S-BcloudReg-E1802\"," + + " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/irma-aic/SDNO-S-BcloudReg-E1802\"," + " \"properties\": {" + " \"resource-version\": \"1513631040564\"" + " }" + diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/parser/ToscaParserImpl2Test.java b/vid-app-common/src/test/java/org/onap/vid/asdc/parser/ToscaParserImpl2Test.java index 91c480526..92d78d43e 100644 --- a/vid-app-common/src/test/java/org/onap/vid/asdc/parser/ToscaParserImpl2Test.java +++ b/vid-app-common/src/test/java/org/onap/vid/asdc/parser/ToscaParserImpl2Test.java @@ -20,11 +20,33 @@ package org.onap.vid.asdc.parser; +import static com.google.common.collect.Lists.newArrayList; +import static org.hamcrest.Matchers.aMapWithSize; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.hasKey; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.onap.vid.asdc.parser.ToscaParserImpl2.Constants.ECOMP_GENERATED_NAMING_PROPERTY; +import static org.onap.vid.testUtils.TestUtils.assertJsonStringEqualsIgnoreNulls; + import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.Stream; import net.javacrumbs.jsonunit.JsonAssert; import org.apache.commons.io.IOUtils; import org.apache.log4j.LogManager; @@ -43,7 +65,19 @@ import org.onap.vid.asdc.AsdcCatalogException; import org.onap.vid.asdc.AsdcClient; import org.onap.vid.asdc.local.LocalAsdcClient; import org.onap.vid.controller.ToscaParserMockHelper; -import org.onap.vid.model.*; +import org.onap.vid.model.CR; +import org.onap.vid.model.Network; +import org.onap.vid.model.NetworkCollection; +import org.onap.vid.model.Node; +import org.onap.vid.model.PortMirroringConfig; +import org.onap.vid.model.ResourceGroup; +import org.onap.vid.model.Service; +import org.onap.vid.model.ServiceModel; +import org.onap.vid.model.ServiceProxy; +import org.onap.vid.model.VNF; +import org.onap.vid.model.VfModule; +import org.onap.vid.model.VidNotions; +import org.onap.vid.model.VolumeGroup; import org.onap.vid.properties.Features; import org.testng.Assert; import org.testng.annotations.BeforeClass; @@ -52,22 +86,6 @@ import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.togglz.core.manager.FeatureManager; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Path; -import java.util.*; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import static com.google.common.collect.Lists.newArrayList; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.onap.vid.asdc.parser.ToscaParserImpl2.Constants.ECOMP_GENERATED_NAMING_PROPERTY; -import static org.onap.vid.testUtils.TestUtils.assertJsonStringEqualsIgnoreNulls; - public class ToscaParserImpl2Test { private final String myUUID = "myUUID"; @@ -101,7 +119,7 @@ public class ToscaParserImpl2Test { @Test(dataProvider = "expectedServiceModel") public void assertEqualsBetweenServices(String uuid, ToscaParserMockHelper mockHelper) throws Exception { - Service expectedService = mockHelper.getNewServiceModel().getService(); + Service expectedService = mockHelper.getServiceModel().getService(); Service actualService = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getService(); assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(expectedService), om.writeValueAsString(actualService)); } @@ -111,12 +129,12 @@ public class ToscaParserImpl2Test { final Path csarPath = getCsarPath(mockHelper.getUuid()); log.info("Comparing for csar " + csarPath); ServiceModel actualServiceModel = toscaParserImpl2.makeServiceModel(csarPath, getServiceByUuid(mockHelper.getUuid())); - assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(mockHelper.getNewServiceModel()), om.writeValueAsString(actualServiceModel)); + assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(mockHelper.getServiceModel()), om.writeValueAsString(actualServiceModel)); } @Test(dataProvider = "expectedServiceModel") public void assertEqualsBetweenNetworkNodes(String uuid, ToscaParserMockHelper mockHelper) throws Exception { - Map expectedNetworksMap = mockHelper.getNewServiceModel().getNetworks(); + Map expectedNetworksMap = mockHelper.getServiceModel().getNetworks(); Map actualNetworksMap = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getNetworks(); for (Map.Entry entry : expectedNetworksMap.entrySet()) { Network expectedNetwork = entry.getValue(); @@ -130,7 +148,7 @@ public class ToscaParserImpl2Test { //Because we are not supporting the old flow, the JSON are different by definition. @Test(dataProvider = "expectedServiceModel") public void assertEqualsBetweenVnfsOfTosca(String uuid, ToscaParserMockHelper mockHelper) throws Exception { - Map expectedVnfsMap = mockHelper.getNewServiceModel().getVnfs(); + Map expectedVnfsMap = mockHelper.getServiceModel().getVnfs(); Map actualVnfsMap = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getVnfs(); for (Map.Entry entry : expectedVnfsMap.entrySet()) { VNF expectedVnf = entry.getValue(); @@ -142,10 +160,12 @@ public class ToscaParserImpl2Test { } } + + @Test(dataProvider = "expectedServiceModel") public void assertEqualsBetweenCollectionResourcesOfTosca(String uuid, ToscaParserMockHelper mockHelper) throws Exception { - Map expectedVnfsMap = mockHelper.getNewServiceModel().getCollectionResource(); - Map actualCRsMap = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getCollectionResource(); + Map expectedVnfsMap = mockHelper.getServiceModel().getCollectionResources(); + Map actualCRsMap = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getCollectionResources(); if(!actualCRsMap.isEmpty()) { for (Map.Entry entry : expectedVnfsMap.entrySet()) { CR expectedCR = entry.getValue(); @@ -201,28 +221,28 @@ public class ToscaParserImpl2Test { @Test(dataProvider = "expectedServiceModel") public void assertEqualsBetweenVolumeGroups(String uuid, ToscaParserMockHelper mockHelper) throws Exception { Map actualVolumeGroups = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getVolumeGroups(); - Map expectedVolumeGroups = mockHelper.getNewServiceModel().getVolumeGroups(); + Map expectedVolumeGroups = mockHelper.getServiceModel().getVolumeGroups(); assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(expectedVolumeGroups), om.writeValueAsString(actualVolumeGroups)); } @Test(dataProvider = "expectedServiceModel") public void assertEqualsBetweenVfModules(String uuid, ToscaParserMockHelper mockHelper) throws Exception { Map actualVfModules = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getVfModules(); - Map expectedVfModules = mockHelper.getNewServiceModel().getVfModules(); + Map expectedVfModules = mockHelper.getServiceModel().getVfModules(); assertJsonStringEqualsIgnoreNulls(om.writeValueAsString(expectedVfModules), om.writeValueAsString(actualVfModules)); } @Test(dataProvider = "expectedServiceModel") public void assertEqualsBetweenPolicyConfigurationNodes(String uuid, ToscaParserMockHelper mockHelper) throws Exception { Map actualConfigurations = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getConfigurations(); - Map expectedConfigurations = mockHelper.getNewServiceModel().getConfigurations(); + Map expectedConfigurations = mockHelper.getServiceModel().getConfigurations(); JsonAssert.assertJsonEquals(actualConfigurations, expectedConfigurations); } @Test public void assertEqualsBetweenPolicyConfigurationByPolicyFalse() throws Exception { ToscaParserMockHelper mockHelper = new ToscaParserMockHelper(Constants.configurationByPolicyFalseUuid, Constants.configurationByPolicyFalseFilePath); - Map expectedConfigurations = mockHelper.getNewServiceModel().getConfigurations(); + Map expectedConfigurations = mockHelper.getServiceModel().getConfigurations(); Map actualConfigurations = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getConfigurations(); setPprobeServiceProxy(expectedConfigurations); @@ -250,7 +270,7 @@ public class ToscaParserImpl2Test { final ToscaParserMockHelper mockHelper = new ToscaParserMockHelper("90fe6842-aa76-4b68-8329-5c86ff564407", "empty.json"); final ServiceModel serviceModel = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())); - assertJsonStringEqualsIgnoreNulls("{ vfModules: { 201712488_adiodvpe10..201712488AdiodVpe1..ADIOD_vRE_BV..module-1: { inputs: { availability_zone_0: { } } } } }", om.writeValueAsString(serviceModel)); + assertJsonStringEqualsIgnoreNulls("{ vfModules: { 201712488_pasqualevpe10..201712488PasqualeVpe1..PASQUALE_vRE_BV..module-1: { inputs: { availability_zone_0: { } } } } }", om.writeValueAsString(serviceModel)); } @Test @@ -260,7 +280,7 @@ public class ToscaParserImpl2Test { assertJsonStringEqualsIgnoreNulls("" + "{ vnfs: " + - " { \"201712-488_ADIOD-vPE-1 0\": " + + " { \"201712-488_PASQUALE-vPE-1 0\": " + " { properties: { " + " ecomp_generated_naming: \"true\", " + " nf_naming: \"{naming_policy=SDNC_Policy.Config_MS_1806SRIOV_VPE_ADIoDJson, ecomp_generated_naming=true}\" " + @@ -278,14 +298,14 @@ public class ToscaParserImpl2Test { @Test(dataProvider = "expectedServiceModel") public void assertEqualsBetweenServiceProxyNodes(String uuid, ToscaParserMockHelper mockHelper) throws Exception { Map actualServiceProxies = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getServiceProxies(); - Map expectedServiceProxies = mockHelper.getNewServiceModel().getServiceProxies(); + Map expectedServiceProxies = mockHelper.getServiceModel().getServiceProxies(); JsonAssert.assertJsonEquals(actualServiceProxies, expectedServiceProxies); } @Test(dataProvider = "expectedServiceModel") public void assertEqualsBetweenVnfGroups(String uuid, ToscaParserMockHelper mockHelper) throws Exception { Map actualVnfGroups = toscaParserImpl2.makeServiceModel(getCsarPath(mockHelper.getUuid()), getServiceByUuid(mockHelper.getUuid())).getVnfGroups(); - Map expectedVnfGroups = mockHelper.getNewServiceModel().getVnfGroups(); + Map expectedVnfGroups = mockHelper.getServiceModel().getVnfGroups(); JsonAssert.assertJsonEquals(actualVnfGroups, expectedVnfGroups); } @@ -342,7 +362,7 @@ public class ToscaParserImpl2Test { static final String vfWithAnnotationUuid = "f4d84bb4-a416-4b4e-997e-0059973630b9"; static final String vlUuid = "cb49608f-5a24-4789-b0f7-2595473cb997"; static final String crUuid = "76f27dfe-33e5-472f-8e0b-acf524adc4f0"; - static final String vfWithVfcGroup = "6bce7302-70bd-4057-b48e-8d5b99e686ca"; //service-VdbeSrv-csar.zip + static final String vfWithVfcGroup = "6bce7302-70bd-4057-b48e-8d5b99e686ca"; //service-VdorotheaSrv-csar.zip // public static final String PNFUuid = "68101369-6f08-4e99-9a28-fa6327d344f3"; static final String vfFilePath = "vf-csar.JSON"; static final String vlFilePath = "vl-csar.JSON"; @@ -358,6 +378,8 @@ public class ToscaParserImpl2Test { //public static final String vnfGroupingUuid = "4117a0b6-e234-467d-b5b9-fe2f68c8b0fc"; //public static final String vnfGroupingFilePath = "vnf-grouping-csar.json"; + public static final String QUANTITY = "quantity"; + } diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/parser/ToscaParserInflatorTest.java b/vid-app-common/src/test/java/org/onap/vid/asdc/parser/ToscaParserInflatorTest.java index 4c5cc9787..d6c080d55 100644 --- a/vid-app-common/src/test/java/org/onap/vid/asdc/parser/ToscaParserInflatorTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/asdc/parser/ToscaParserInflatorTest.java @@ -20,7 +20,16 @@ package org.onap.vid.asdc.parser; +import static java.util.Collections.emptyMap; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + import com.google.common.collect.ImmutableMap; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Path; +import java.util.Map; +import java.util.UUID; import org.apache.commons.io.IOUtils; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; @@ -41,16 +50,6 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Path; -import java.util.Map; -import java.util.UUID; - -import static java.util.Collections.emptyMap; -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.assertThat; - public class ToscaParserInflatorTest { private static final Logger log = LogManager.getLogger(ToscaParserInflatorTest.class); @@ -83,15 +82,15 @@ public class ToscaParserInflatorTest { @Test public void inflateFabricConfigurationModel_allIdsAreGiven() throws Exception { - final String fabricConfigurationUuid = "90fe6842-aa76-4b68-8329-5c86ff564407"; + final String fabricConfigurationUuid = "12344bb4-a416-4b4e-997e-0059973630b9"; final Map inflated = inflateModelByUuid(fabricConfigurationUuid); // see vf-with-annotation-csar.json assertThat(inflated, is(ImmutableMap.of( - "8df1892c-377d-460b-8a8d-fc8a116e9d92", doubleName("201712-488_ADIOD-vPE-1 0"), - "8d521692-7661-4296-b77e-a2058bb62e87", new Names("201712488AdiodVpe1..ADIOD_vRE_BV..module-1", "201712488_adiodvpe10..201712488AdiodVpe1..ADIOD_vRE_BV..module-1"), - "79fbee20-7fba-4166-ae4b-b94c869e7d8b", new Names("201712488AdiodVpe1..ADIOD_vPFE_BV..module-2","201712488_adiodvpe10..201712488AdiodVpe1..ADIOD_vPFE_BV..module-2"), - "806505b8-7a7c-47a2-acef-b4d26fe95a92", new Names("201712488AdiodVpe1..ADIOD_base_vPE_BV..module-0","201712488_adiodvpe10..201712488AdiodVpe1..ADIOD_base_vPE_BV..module-0") + "ea81d6f7-0861-44a7-b7d5-d173b562c350", doubleName("2017-488_PASQUALE-vPE 0"), + "a5d8df05-11cb-4351-96e0-b6d4168ea4df", new Names("2017488PasqualeVpe..PASQUALE_vRE_BV..module-1", "2017488_pasqualevpe0..2017488PasqualeVpe..PASQUALE_vRE_BV..module-1"), + "b3e8b26e-cff0-49fc-a4e6-f3e16c8440fe", new Names("2017488PasqualeVpe..PASQUALE_vPFE_BV..module-2","2017488_pasqualevpe0..2017488PasqualeVpe..PASQUALE_vPFE_BV..module-2"), + "040e591e-5d30-4e0d-850f-7266e5a8e013", new Names("2017488PasqualeVpe..PASQUALE_base_vPE_BV..module-0","2017488_pasqualevpe0..2017488PasqualeVpe..PASQUALE_base_vPE_BV..module-0") ))); } diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/parser/VidNotionsBuilderTest.java b/vid-app-common/src/test/java/org/onap/vid/asdc/parser/VidNotionsBuilderTest.java index 788f78084..edaf7125f 100644 --- a/vid-app-common/src/test/java/org/onap/vid/asdc/parser/VidNotionsBuilderTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/asdc/parser/VidNotionsBuilderTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -30,28 +30,35 @@ import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.onap.sdc.tosca.parser.api.ISdcCsarHelper; import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException; -import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory; import org.onap.sdc.toscaparser.api.NodeTemplate; import org.onap.sdc.toscaparser.api.Property; import org.onap.sdc.toscaparser.api.elements.Metadata; import org.onap.vid.model.*; import org.onap.vid.properties.Features; +import org.onap.vid.testUtils.TestUtils; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import org.togglz.core.manager.FeatureManager; -import java.util.LinkedHashMap; -import java.util.UUID; +import java.io.File; +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.*; import java.util.function.BiConsumer; +import static java.util.Collections.emptyList; +import static java.util.Collections.emptyMap; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasProperty; import static org.hamcrest.Matchers.is; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import static org.testng.Assert.assertEquals; +import static org.onap.vid.model.VidNotions.*; +import static org.testng.AssertJUnit.assertEquals; public class VidNotionsBuilderTest { @@ -61,6 +68,10 @@ public class VidNotionsBuilderTest { @Mock private FeatureManager featureManagerMock; + private ServiceModel serviceModel; + + private ISdcCsarHelper csarHelper; + @BeforeClass public void initMocks() { MockitoAnnotations.initMocks(this); @@ -75,12 +86,12 @@ public class VidNotionsBuilderTest { public void VLNetworkWithPropertyNetworkTechnologyOVS_UIHintIsPositive() { ISdcCsarHelper csarHelper = mockForNonLegacyInstantiationUI(); - assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper), is(VidNotions.InstantiationUI.NETWORK_WITH_PROPERTY_NETWORK_TECHNOLOGY_EQUALS_STANDARD_SRIOV_OR_OVS)); - assertThat(vidNotionsBuilder.suggestModelCategory(csarHelper) , is(VidNotions.ModelCategory.IS_5G_PROVIDER_NETWORK_MODEL)); + assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper, serviceModel), is(InstantiationUI.NETWORK_WITH_PROPERTY_NETWORK_TECHNOLOGY_EQUALS_STANDARD_SRIOV_OR_OVS)); + assertThat(vidNotionsBuilder.suggestModelCategory(csarHelper, serviceModel) , is(ModelCategory.IS_5G_PROVIDER_NETWORK_MODEL)); } @NotNull - protected ISdcCsarHelper mockForNonLegacyInstantiationUI() { + private ISdcCsarHelper mockForNonLegacyInstantiationUI() { ISdcCsarHelper csarHelper = ToscaParserImpl2Test.getMockedSdcCsarHelper(UUID.randomUUID().toString()); NodeTemplate nodeTemplate = mock(NodeTemplate.class); @@ -98,15 +109,16 @@ public class VidNotionsBuilderTest { @DataProvider public static Object[][] anyAlacarteDataProvider() { return new Object[][] { - {"A-La-Carte", VidNotions.InstantiationUI.ANY_ALACARTE_NEW_UI}, - {"Macro", VidNotions.InstantiationUI.LEGACY}, + {"A-La-Carte", InstantiationUI.ANY_ALACARTE_NEW_UI}, + {"Macro", InstantiationUI.LEGACY}, }; } @Test(dataProvider = "anyAlacarteDataProvider") - public void FLAG_EXP_ANY_ALACARTE_NEW_INSTANTIATION_UI_is_active_UIHintIsPositive(String instantiationType, VidNotions.InstantiationUI expectedInstantiationUI) { + public void FLAG_EXP_ANY_ALACARTE_NEW_INSTANTIATION_UI_is_active_UIHintIsPositive(String instantiationType, InstantiationUI expectedInstantiationUI) { + initServiceModelAndscarHelperWithMocks(); + when(featureManagerMock.isActive(Features.FLAG_EXP_ANY_ALACARTE_NEW_INSTANTIATION_UI)).thenReturn(true); - ISdcCsarHelper csarHelper = ToscaParserImpl2Test.getMockedSdcCsarHelper(UUID.randomUUID().toString()); when(csarHelper.getServiceMetadata()).thenReturn(new Metadata(ImmutableMap.of( "instantiationType", instantiationType ))); @@ -119,12 +131,12 @@ public class VidNotionsBuilderTest { when(csarHelper.getServiceVlList()).thenReturn(ImmutableList.of(nodeTemplate)); - assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper), is(expectedInstantiationUI)); + assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper, serviceModel), is(expectedInstantiationUI)); } @Test public void VLNetworkWithPropertyNetworkTechnologyNot5G_UIHintIsNegative() { - ISdcCsarHelper csarHelper = ToscaParserImpl2Test.getMockedSdcCsarHelper(UUID.randomUUID().toString()); + initServiceModelAndscarHelperWithMocks(); NodeTemplate nodeTemplate = mock(NodeTemplate.class); @@ -135,85 +147,91 @@ public class VidNotionsBuilderTest { when(csarHelper.getServiceVlList()).thenReturn(ImmutableList.of(nodeTemplate)); - assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper), is(VidNotions.InstantiationUI.LEGACY)); - assertThat(vidNotionsBuilder.suggestModelCategory(csarHelper) , is(VidNotions.ModelCategory.OTHER)); + assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper, serviceModel), is(InstantiationUI.LEGACY)); + assertThat(vidNotionsBuilder.suggestModelCategory(csarHelper, serviceModel) , is(ModelCategory.OTHER)); } @Test - public void withoutMocks_givenZippedToscaFile_hasAnyNetworkWithPropertyEqualsToAnyOfYieldsTrue() throws SdcToscaParserException { - SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance(); - ISdcCsarHelper csarHelper = factory.getSdcCsarHelper(getClass().getClassLoader().getResource("service-vl-csar.zip").getPath(),false); - + public void withoutMocks_givenZippedToscaFile_hasAnyNetworkWithPropertyEqualsToAnyOfYieldsTrue() throws SdcToscaParserException, IOException { + initServiceModelAndscarHelperWithRealCsar("/csars/service-vl-csar.zip"); assertThat(vidNotionsBuilder.isALaCarte(csarHelper), is(false)); assertThat(vidNotionsBuilder.hasAnyNetworkWithPropertyEqualsToAnyOf(csarHelper, "unexpected_property_name"), is(false)); assertThat(vidNotionsBuilder.hasAnyNetworkWithPropertyEqualsToAnyOf(csarHelper, "network_technology","Standard-SR-IOV"), is(true)); - assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper), is(VidNotions.InstantiationUI.LEGACY)); + assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper, serviceModel), is(InstantiationUI.LEGACY)); } - //@Test - //public void withoutMocks_givenZippedToscaFile_hasFabricConfigurationYieldsTrue() throws SdcToscaParserException { - // SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance(); - // ISdcCsarHelper csarHelper = factory.getSdcCsarHelper(getClass().getClassLoader().getResource("service-fabric-configuration.zip").getPath(),false); - // - // assertThat(vidNotionsBuilder.isALaCarte(csarHelper), is(false)); - // assertThat(vidNotionsBuilder.hasFabricConfiguration(csarHelper), is(true)); - // assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper), is(VidNotions.InstantiationUI.LEGACY)); - //} + @Test + public void withoutMocks_givenZippedToscaFile_hasFabricConfigurationYieldsTrue() throws SdcToscaParserException, IOException { + initServiceModelAndscarHelperWithRealCsar("/csars/service-fabric-configuration.zip"); + assertThat(vidNotionsBuilder.isALaCarte(csarHelper), is(false)); + assertThat(vidNotionsBuilder.hasFabricConfiguration(csarHelper), is(true)); + assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper, serviceModel), is(InstantiationUI.LEGACY)); + } + + @Test(dataProvider = "trueAndFalse", dataProviderClass = TestUtils.class) + public void withoutMocks_givenZippedToscaFileOfTransportService_InstantiationUIAndCategoryAreRight(boolean flagValue) throws SdcToscaParserException, IOException { + initServiceModelAndscarHelperWithRealCsar("/csars/csarTransportWithPnfs.zip"); + when(featureManagerMock.isActive(Features.FLAG_1908_TRANSPORT_SERVICE_NEW_INSTANTIATION_UI)).thenReturn(flagValue); + + assertThat(vidNotionsBuilder.isALaCarte(csarHelper), is(false)); + assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper, serviceModel), is(flagValue ? InstantiationUI.TRANSPORT_SERVICE : InstantiationUI.LEGACY)); + assertThat(vidNotionsBuilder.suggestModelCategory(csarHelper, serviceModel), is(ModelCategory.Transport)); + } + + @Test(dataProvider = "trueAndFalse", dataProviderClass = TestUtils.class) + public void withoutMocks_givenZippedToscaFileOfInfraStructureVpn_InstantiationUIIsRight(boolean flagValue) throws SdcToscaParserException, IOException { + initServiceModelAndscarHelperWithRealCsar("/csars/service-Infravpn-csar.zip"); + when(featureManagerMock.isActive(Features.FLAG_1908_INFRASTRUCTURE_VPN)).thenReturn(flagValue); + assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper, serviceModel), is(flagValue ? InstantiationUI.INFRASTRUCTURE_VPN : InstantiationUI.LEGACY)); + assertThat(vidNotionsBuilder.suggestModelCategory(csarHelper, serviceModel), is(ModelCategory.INFRASTRUCTURE_VPN)); + } @Test public void uuidIsExactly1ffce89fEtc_UIHintIsPositive() { - ISdcCsarHelper csarHelper = ToscaParserImpl2Test.getMockedSdcCsarHelper(UUID.randomUUID().toString()); + initServiceModelAndscarHelperWithMocks(); when(csarHelper.getServiceMetadata()).thenReturn(new Metadata(ImmutableMap.of( "UUID", "95eb2c44-bff2-4e8b-ad5d-8266870b7717" ))); when(featureManagerMock.isActive(Features.FLAG_5G_IN_NEW_INSTANTIATION_UI)).thenReturn(true); - assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper), is(VidNotions.InstantiationUI.SERVICE_UUID_IS_1ffce89f_ef3f_4cbb_8b37_82134590c5de)); - } - - - @DataProvider - public static Object[][] trueAndFalse() { - return new Object[][] {{true}, {false}}; + assertThat(vidNotionsBuilder.suggestInstantiationUI(csarHelper, serviceModel), is(InstantiationUI.SERVICE_UUID_IS_1ffce89f_ef3f_4cbb_8b37_82134590c5de)); } - @Test(dataProvider = "trueAndFalse") + @Test(dataProvider = "trueAndFalse", dataProviderClass = TestUtils.class) public void buildVidNotions_nullByFlag(boolean flagValue) { - ISdcCsarHelper csarHelper = ToscaParserImpl2Test.getMockedSdcCsarHelper(UUID.randomUUID().toString()); + initServiceModelAndscarHelperWithMocks(); when(featureManagerMock.isActive(Features.FLAG_5G_IN_NEW_INSTANTIATION_UI)).thenReturn(flagValue); - assertThat(vidNotionsBuilder.buildVidNotions(csarHelper, null), hasProperty("instantiationUI", is(VidNotions.InstantiationUI.LEGACY))); + assertThat(vidNotionsBuilder.buildVidNotions(csarHelper, serviceModel), hasProperty("instantiationUI", is(InstantiationUI.LEGACY))); } @DataProvider public static Object[][] ServiceRoleTypesDataProvider() { return new Object[][] { - {"gROUPING", VidNotions.InstantiationUI.SERVICE_WITH_VNF_GROUPING}, - {"", VidNotions.InstantiationUI.LEGACY}, + {"gROUPING", InstantiationUI.SERVICE_WITH_VNF_GROUPING}, + {"", InstantiationUI.LEGACY}, }; } @Test(dataProvider = "ServiceRoleTypesDataProvider") - public void testGetViewEditUITypeForResourceGroup(String serviceRole, VidNotions.InstantiationUI expectedViewEditUI) { - when(featureManagerMock.isActive(Features.FLAG_ASYNC_INSTANTIATION)).thenReturn(true); + public void testGetViewEditUITypeForResourceGroup(String serviceRole, InstantiationUI expectedViewEditUI) { + initServiceModelAndscarHelperWithMocks(); when(featureManagerMock.isActive(Features.FLAG_1902_VNF_GROUPING)).thenReturn(true); - ISdcCsarHelper csarHelper = ToscaParserImpl2Test.getMockedSdcCsarHelper(UUID.randomUUID().toString()); when(csarHelper.getServiceMetadata()).thenReturn(new Metadata(ImmutableMap.of( "serviceRole", serviceRole ))); - assertThat(vidNotionsBuilder.suggestViewEditUI(csarHelper, null), is(expectedViewEditUI)); + assertThat(vidNotionsBuilder.suggestViewEditUI(csarHelper, serviceModel), is(expectedViewEditUI)); } @DataProvider public static Object[][] macroToViewEditDataProvider() { return new Object[][] { - {"macro service + not excluded + needed flags are open", true, false, true, true, VidNotions.InstantiationUI.MACRO_SERVICE}, - {"not macro service", false, false, true, true, VidNotions.InstantiationUI.LEGACY}, - {"macro that shall be excluded because it has pnf", true, true, true, true, VidNotions.InstantiationUI.LEGACY}, - {"macro service + FLAG_ASYNC_INSTANTIATION off", true, false, false, true, VidNotions.InstantiationUI.LEGACY}, - {"macro service + FLAG_1902_NEW_VIEW_EDIT off", true, false, true, false, VidNotions.InstantiationUI.LEGACY}, + {"macro service + not excluded + needed flags are open", true, false, true, InstantiationUI.MACRO_SERVICE}, + {"not macro service", false, true, true, InstantiationUI.LEGACY}, + {"macro that shall be excluded because it has pnf", true, true, true, InstantiationUI.LEGACY}, + {"macro service + FLAG_1902_NEW_VIEW_EDIT off", true, false, false, InstantiationUI.LEGACY}, }; } @@ -222,19 +240,16 @@ public class VidNotionsBuilderTest { String testDescription, boolean isMacro, boolean isExcluded, - boolean isFlagAsyncInstantiationActive, boolean isFlag1902NewViewEdit, - VidNotions.InstantiationUI expectedViewEditUi) { + InstantiationUI expectedViewEditUi) { - ISdcCsarHelper csarHelper = mock(ISdcCsarHelper.class); - ServiceModel serviceModel = mock(ServiceModel.class); + initServiceModelAndscarHelperWithMocks(); //mock for is Macro String instantiationType = isMacro ? ToscaParserImpl2.Constants.MACRO : ToscaParserImpl2.Constants.A_LA_CARTE; Service service = mock(Service.class); when(serviceModel.getService()).thenReturn(service); when(service.getInstantiationType()).thenReturn(instantiationType); - when(featureManagerMock.isActive(Features.FLAG_ASYNC_INSTANTIATION)).thenReturn(isFlagAsyncInstantiationActive); when(featureManagerMock.isActive(Features.FLAG_1902_NEW_VIEW_EDIT)).thenReturn(isFlag1902NewViewEdit); //mock for isExcluded @@ -242,17 +257,16 @@ public class VidNotionsBuilderTest { when(serviceModel.getPnfs()).thenReturn(ImmutableMap.of("a", mock(Node.class))); } - VidNotions.InstantiationUI result = vidNotionsBuilder.suggestViewEditUI(csarHelper, serviceModel); + InstantiationUI result = vidNotionsBuilder.suggestViewEditUI(csarHelper, serviceModel); assertEquals(expectedViewEditUi, result); } @DataProvider public static Object[][] instantiationUIToViewEditDataProvider() { return new Object[][] { - {"network cloud(5G) service + needed flags are open", true, true, true, VidNotions.InstantiationUI.NETWORK_WITH_PROPERTY_NETWORK_TECHNOLOGY_EQUALS_STANDARD_SRIOV_OR_OVS}, - {"mocked service + needed flags are open", false, true, true, VidNotions.InstantiationUI.LEGACY}, - {"network cloud(5G) service + FLAG_ASYNC_INSTANTIATION is off", true, false, true, VidNotions.InstantiationUI.LEGACY}, - {"network cloud(5G) service + FLAG_1902_NEW_VIEW_EDIT is off", true, true, false, VidNotions.InstantiationUI.LEGACY}, + {"network cloud(5G) service + needed flags are open", true, true, InstantiationUI.NETWORK_WITH_PROPERTY_NETWORK_TECHNOLOGY_EQUALS_STANDARD_SRIOV_OR_OVS}, + {"mocked service + needed flags are open", false, true, InstantiationUI.LEGACY}, + {"network cloud(5G) service + FLAG_1902_NEW_VIEW_EDIT is off", true, false, InstantiationUI.LEGACY}, }; } @@ -261,12 +275,10 @@ public class VidNotionsBuilderTest { public void whenInstantiationUIIsNotLegacy_viewEditIsRight( String testDescription, boolean isInstantiationUINotLegacy, - boolean isFlagAsyncInstantiationActive, boolean isFlag1902NewViewEdit, - VidNotions.InstantiationUI expectedViewEditUi) { + InstantiationUI expectedViewEditUi) { ISdcCsarHelper csarHelper = isInstantiationUINotLegacy ? mockForNonLegacyInstantiationUI() : mock(ISdcCsarHelper.class); - when(featureManagerMock.isActive(Features.FLAG_ASYNC_INSTANTIATION)).thenReturn(isFlagAsyncInstantiationActive); when(featureManagerMock.isActive(Features.FLAG_1902_NEW_VIEW_EDIT)).thenReturn(isFlag1902NewViewEdit); ServiceModel serviceModel = mock(ServiceModel.class); @@ -274,7 +286,7 @@ public class VidNotionsBuilderTest { when(serviceModel.getService()).thenReturn(service); when(service.getInstantiationType()).thenReturn(ToscaParserImpl2.Constants.A_LA_CARTE); - VidNotions.InstantiationUI result = vidNotionsBuilder.suggestViewEditUI(csarHelper, serviceModel); + InstantiationUI result = vidNotionsBuilder.suggestViewEditUI(csarHelper, serviceModel); assertEquals(expectedViewEditUi, result); } @@ -282,7 +294,7 @@ public class VidNotionsBuilderTest { public static Object[][] mockerForMacroExcluded() { return new Object[][] { {"service with pnfs", (BiConsumer) (serviceModel, fm)->when(serviceModel.getPnfs()).thenReturn(ImmutableMap.of("a", mock(Node.class))), true}, - {"service with collection resource", (BiConsumer) (serviceModel, fm)->when(serviceModel.getCollectionResource()).thenReturn(ImmutableMap.of("a", mock(CR.class))), true}, + {"service with collection resource", (BiConsumer) (serviceModel, fm) -> when(serviceModel.getCollectionResources()).thenReturn(ImmutableMap.of("a", mock(CR.class))), true}, {"service with network + FLAG_NETWORK_TO_ASYNC_INSTANTIATION false ", (BiConsumer) (serviceModel, fm)->{ when(serviceModel.getNetworks()).thenReturn(ImmutableMap.of("a", mock(Network.class))); when(fm.isActive(Features.FLAG_NETWORK_TO_ASYNC_INSTANTIATION)).thenReturn(false);} @@ -290,7 +302,7 @@ public class VidNotionsBuilderTest { {"service with network + FLAG_NETWORK_TO_ASYNC_INSTANTIATION true", (BiConsumer) (serviceModel, fm)->{ when(serviceModel.getNetworks()).thenReturn(ImmutableMap.of("a", mock(Network.class))); when(fm.isActive(Features.FLAG_NETWORK_TO_ASYNC_INSTANTIATION)).thenReturn(true);} - , false}, + , false}, {"empty service + FLAG_NETWORK_TO_ASYNC_INSTANTIATION false", (BiConsumer) (serviceModel, fm)->when(fm.isActive(Features.FLAG_NETWORK_TO_ASYNC_INSTANTIATION)).thenReturn(false), false}, }; } @@ -302,9 +314,197 @@ public class VidNotionsBuilderTest { assertEquals(shallBeExcluded, vidNotionsBuilder.isMacroExcludedFromAsyncFlow(serviceModel)); } + @DataProvider + public static Object[][] toscaParserInstantiationTypeToVidNotion() { + return new Object[][] { + {ToscaParserImpl2.Constants.MACRO, InstantiationType.Macro}, + {ToscaParserImpl2.Constants.A_LA_CARTE, InstantiationType.ALaCarte}, + {ToscaParserImpl2.Constants.CLIENT_CONFIG, InstantiationType.ClientConfig}, + {"I dont know", InstantiationType.ClientConfig}, + {"", InstantiationType.ClientConfig} + }; + } + + @Test(dataProvider="toscaParserInstantiationTypeToVidNotion") + public void testSuggestInstantiationTypeWhenInstantiationUiLegacy(String toscaParserInstantiationType, InstantiationType expectedInstantiationType) { + ServiceModel serviceModel = mock(ServiceModel.class); + Service service = mock(Service.class); + when(serviceModel.getService()).thenReturn(service); + when(service.getInstantiationType()).thenReturn(toscaParserInstantiationType); + assertEquals(expectedInstantiationType, vidNotionsBuilder.suggestInstantiationType(serviceModel, ModelCategory.OTHER)); + } + + @DataProvider + public static Object[][] instantiationUIAndFeatureFlagsForInstantiationType() { + return new Object[][] { + {ModelCategory.Transport, Features.FLAG_1908_TRANSPORT_SERVICE_NEW_INSTANTIATION_UI, true, InstantiationType.Macro}, + {ModelCategory.Transport, Features.FLAG_1908_TRANSPORT_SERVICE_NEW_INSTANTIATION_UI, false, InstantiationType.ALaCarte}, + {ModelCategory.INFRASTRUCTURE_VPN, Features.FLAG_1908_INFRASTRUCTURE_VPN, true, InstantiationType.Macro}, + {ModelCategory.INFRASTRUCTURE_VPN, Features.FLAG_1908_INFRASTRUCTURE_VPN, false, InstantiationType.ALaCarte}, + {ModelCategory.OTHER, Features.FLAG_1908_INFRASTRUCTURE_VPN, true, InstantiationType.ALaCarte}, //not mapped InstantiationUI + }; + } + @Test(dataProvider="instantiationUIAndFeatureFlagsForInstantiationType") + public void testSuggestInstantiationTypeByModelCategoryAndFeatureFlags( + ModelCategory instantiationUI, + Features featureFlag, + boolean isFeatureOn, + InstantiationType expectedInstantiationType) { + ServiceModel serviceModel = mock(ServiceModel.class); + Service service = mock(Service.class); + when(serviceModel.getService()).thenReturn(service); + when(service.getInstantiationType()).thenReturn(ToscaParserImpl2.Constants.A_LA_CARTE); + when(featureManagerMock.isActive(featureFlag)).thenReturn(isFeatureOn); + assertEquals(expectedInstantiationType, vidNotionsBuilder.suggestInstantiationType(serviceModel, instantiationUI)); + } + @DataProvider + public static Object[][] FLAG_1908_COLLECTION_RESOURCE_NEW_INSTANTIATION_UIValueAndCollectionResourceForVidNotions() { + return new Object[][] { + {true, ImmutableMap.of("Some string", mock(CR.class)), InstantiationUI.SERVICE_WITH_COLLECTION_RESOURCE, ModelCategory.SERVICE_WITH_COLLECTION_RESOURCE}, + {true, Collections.EMPTY_MAP, InstantiationUI.LEGACY, ModelCategory.OTHER}, + {true, null, InstantiationUI.LEGACY, ModelCategory.OTHER}, + {false, ImmutableMap.of("Some string", mock(CR.class)), InstantiationUI.LEGACY, ModelCategory.SERVICE_WITH_COLLECTION_RESOURCE}, + {false, Collections.EMPTY_MAP, InstantiationUI.LEGACY, ModelCategory.OTHER}, + {false, null, InstantiationUI.LEGACY, ModelCategory.OTHER} + }; + } + @Test(dataProvider="FLAG_1908_COLLECTION_RESOURCE_NEW_INSTANTIATION_UIValueAndCollectionResourceForVidNotions") + public void testSuggestInstantiationUiAndModelCategoryByCollectionResourceAndFeatureFlag_FLAG_1908_COLLECTION_RESOURCE_NEW_INSTANTIATION_UI( + boolean featureFlagValue, + Map collectionResource, + VidNotions.InstantiationUI expectedInstantiationUi, + VidNotions.ModelCategory expectedModelCategory) { + initServiceModelAndscarHelperWithMocks(); + Service service = mock(Service.class); + when(service.getInstantiationType()).thenReturn(ToscaParserImpl2.Constants.MACRO); + when(serviceModel.getService()).thenReturn(service); + when(serviceModel.getCollectionResources()).thenReturn(collectionResource); + when(featureManagerMock.isActive(Features.FLAG_1908_COLLECTION_RESOURCE_NEW_INSTANTIATION_UI)).thenReturn(featureFlagValue); + VidNotions vidNotions = vidNotionsBuilder.buildVidNotions(csarHelper, serviceModel); + assertEquals(expectedInstantiationUi, vidNotions.getInstantiationUI()); + assertEquals(expectedModelCategory, vidNotions.getModelCategory()); + assertEquals(InstantiationUI.LEGACY, vidNotions.getViewEditUI()); + assertEquals(InstantiationType.Macro, vidNotions.getInstantiationType()); + } -} + @DataProvider + public static Object[][] givenCollectionResourceServiceDataProvider() { + return new Object[][]{ + {false, true, InstantiationUI.LEGACY}, + {true, false, InstantiationUI.LEGACY}, + {true, true, InstantiationUI.SERVICE_WITH_COLLECTION_RESOURCE} + }; + } + + @Test(dataProvider = "givenCollectionResourceServiceDataProvider") + public void givenCollectionResourceService_whenSuggestViewEdit_thenResultAccordingFeatureFlag( + boolean crFlag, boolean resumeFlag, VidNotions.InstantiationUI expectedViewEditUi) { + + //mock service with CR + ServiceModel mockServiceModel = mock(ServiceModel.class); + when(mockServiceModel.getCollectionResources()).thenReturn(ImmutableMap.of("a", mock(CR.class))); + + //mock feature flags + when(featureManagerMock.isActive(Features.FLAG_1908_COLLECTION_RESOURCE_NEW_INSTANTIATION_UI)).thenReturn(crFlag); + when(featureManagerMock.isActive(Features.FLAG_1908_RESUME_MACRO_SERVICE)).thenReturn(resumeFlag); + + assertEquals(expectedViewEditUi, vidNotionsBuilder.suggestViewEditUI(mock(ISdcCsarHelper.class), mockServiceModel)); + } + + @Test + public void whenServiceModelIsNull_thenInstantiationTypeIsClientConfig() { + assertEquals( InstantiationType.ClientConfig, vidNotionsBuilder.suggestInstantiationType(null, ModelCategory.OTHER)); + } + + @Test + public void whenServiceInServiceModelIsNull_thenInstantiationTypeIsClientConfig() { + assertEquals( InstantiationType.ClientConfig, vidNotionsBuilder.suggestInstantiationType(mock(ServiceModel.class), ModelCategory.OTHER)); + } + + @Test + public void whenInstantiationTypeInServiceModelIsNull_thenInstantiationTypeIsClientConfig() { + initServiceModelAndscarHelperWithMocks(); + Service service = mock(Service.class); + when(serviceModel.getService()).thenReturn(service); + when(service.getInstantiationType()).thenReturn(null); + assertEquals( InstantiationType.ClientConfig, vidNotionsBuilder.suggestInstantiationType(serviceModel, ModelCategory.OTHER)); + } + + private void initServiceModelAndscarHelperWithRealCsar(String path) throws SdcToscaParserException, IOException { + Path csarPath = Paths.get(new File(getClass().getResource(path).getPath()).getCanonicalPath()); + ToscaParserImpl2 toscaParser = new ToscaParserImpl2(vidNotionsBuilder); + org.onap.vid.asdc.beans.Service asdcServiceMetadata = mock(org.onap.vid.asdc.beans.Service.class); + when(asdcServiceMetadata.getVersion()).thenReturn("versions"); + serviceModel = toscaParser.makeServiceModel(csarPath, asdcServiceMetadata); + csarHelper = toscaParser.getSdcCsarHelper(csarPath); + } + + private void initServiceModelAndscarHelperWithMocks() { + csarHelper = ToscaParserImpl2Test.getMockedSdcCsarHelper(UUID.randomUUID().toString()); + serviceModel = mock(ServiceModel.class); + } + + @DataProvider + public static Object[][] VnfNcIndicationDataProvider() { + return new Object[][] { + {true, "VNF", InstantiationUI.A_LA_CARTE_VNF_SERVICE_ROLE}, + {false, "VNF", InstantiationUI.LEGACY}, + {false, "notVNF", InstantiationUI.LEGACY}, + {true, null, InstantiationUI.LEGACY}, + {true, "notVNF", InstantiationUI.LEGACY}, + {true, "vnf", InstantiationUI.A_LA_CARTE_VNF_SERVICE_ROLE}, + }; + } + + @Test (dataProvider = "VnfNcIndicationDataProvider") + public void whenServiceRoleVnf_thenInstantiationTypeNewUI(boolean flagOn, String serviceRole, InstantiationUI expectedViewEditUi){ + initServiceModelAndscarHelperWithMocks(); + + when(featureManagerMock.isActive(Features.FLAG_1908_A_LA_CARTE_VNF_NEW_INSTANTIATION_UI)).thenReturn(flagOn); + + when(csarHelper.getServiceMetadata()).thenReturn(new Metadata(serviceRole == null ? + emptyMap() : ImmutableMap.of(ToscaParserImpl2.Constants.SERVICE_ROLE, serviceRole) + )); + + assertEquals(expectedViewEditUi, vidNotionsBuilder.suggestInstantiationUI(csarHelper, serviceModel)); + } + + private static NodeTemplate mockNodeTemplateChild(boolean withFabricConfiguration) { + NodeTemplate child = mock(NodeTemplate.class); + when(child.getType()).thenReturn(withFabricConfiguration ? ToscaParserImpl2.Constants.FABRIC_CONFIGURATION_TYPE : "nothing"); + return child; + } + + private static ISdcCsarHelper mockServiceNodeTemplates(ISdcCsarHelper csarHelper, ImmutableList children) { + when(csarHelper.getNodeTemplateChildren(any())).thenReturn(children); + + NodeTemplate parent = mock(NodeTemplate.class); + List nodeTemplates = ImmutableList.of(parent); + + when(csarHelper.getServiceNodeTemplates()).thenReturn(nodeTemplates); + return csarHelper; + } + + @DataProvider + public static Object[][] csarHelpersForFabricConfiguration() { + ISdcCsarHelper csarHelperWithNoNodes = mock(ISdcCsarHelper.class); + when(csarHelperWithNoNodes.getServiceNodeTemplates()).thenReturn(emptyList()); + + return new Object[][] { + { "zero nodes", false, csarHelperWithNoNodes }, + { "single node with no child", false, mockServiceNodeTemplates(mock(ISdcCsarHelper.class), ImmutableList.of()) }, + { "single node with single fabric child", true, mockServiceNodeTemplates(mock(ISdcCsarHelper.class), ImmutableList.of(mockNodeTemplateChild(true))) }, + { "single node with single fabric child and single non-fabric", true, mockServiceNodeTemplates(mock(ISdcCsarHelper.class), ImmutableList.of( + mockNodeTemplateChild(true), mockNodeTemplateChild(true))) }, + }; + } + + @Test (dataProvider = "csarHelpersForFabricConfiguration") + public void hasFabricConfiguration(String desc, boolean shouldHaveFabricConfiguration, ISdcCsarHelper csarHelper) { + assertThat(desc, vidNotionsBuilder.hasFabricConfiguration(csarHelper), is(shouldHaveFabricConfiguration)); + } +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/changeManagement/WorkflowRequestDetailTest.java b/vid-app-common/src/test/java/org/onap/vid/changeManagement/WorkflowRequestDetailTest.java index 38f15d7e5..fbaa763cf 100644 --- a/vid-app-common/src/test/java/org/onap/vid/changeManagement/WorkflowRequestDetailTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/changeManagement/WorkflowRequestDetailTest.java @@ -19,15 +19,17 @@ */ package org.onap.vid.changeManagement; -import org.testng.annotations.Test; - import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSetters; import static org.hamcrest.MatcherAssert.assertThat; +import org.onap.vid.testUtils.TestUtils; +import org.testng.annotations.Test; + public class WorkflowRequestDetailTest { @Test public void shouldHaveProperSettersAndGetters() { + TestUtils.registerCloudConfigurationValueGenerator(); assertThat(WorkflowRequestDetail.class, hasValidGettersAndSetters()); } } diff --git a/vid-app-common/src/test/java/org/onap/vid/config/DataSourceConfig.java b/vid-app-common/src/test/java/org/onap/vid/config/DataSourceConfig.java index 43adc8cf1..15f849a58 100644 --- a/vid-app-common/src/test/java/org/onap/vid/config/DataSourceConfig.java +++ b/vid-app-common/src/test/java/org/onap/vid/config/DataSourceConfig.java @@ -63,7 +63,7 @@ public class DataSourceConfig { Resource[] mappingLocations = { new ClassPathResource("WEB-INF/fusion/orm/Fusion.hbm.xml"), new ClassPathResource("WEB-INF/fusion/orm/Workflow.hbm.xml"), - new ClassPathResource("WEB-INF/fusion/orm/RNoteBookIntegration.hbm.xml") +// new ClassPathResource("WEB-INF/fusion/orm/RNoteBookIntegration.hbm.xml") }; sessionFactory.setHibernateProperties(properties); diff --git a/vid-app-common/src/test/java/org/onap/vid/config/JobAdapterConfig.java b/vid-app-common/src/test/java/org/onap/vid/config/JobAdapterConfig.java index 7462a32b2..149fad354 100644 --- a/vid-app-common/src/test/java/org/onap/vid/config/JobAdapterConfig.java +++ b/vid-app-common/src/test/java/org/onap/vid/config/JobAdapterConfig.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,33 +21,26 @@ package org.onap.vid.config; -import org.hibernate.SessionFactory; +import org.mockito.Mockito; import org.onap.vid.job.JobAdapter; -import org.onap.vid.job.JobsBrokerService; import org.onap.vid.job.impl.JobAdapterImpl; -import org.onap.vid.job.impl.JobsBrokerServiceInDatabaseImpl; -import org.onap.vid.properties.VidProperties; -import org.onap.portalsdk.core.service.DataAccessService; -import org.onap.portalsdk.core.util.SystemProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.transaction.annotation.EnableTransactionManagement; +import org.togglz.core.manager.FeatureManager; @Configuration @EnableTransactionManagement public class JobAdapterConfig { @Bean - public JobAdapter jobAdapter() { - return new JobAdapterImpl(); + public FeatureManager featureManager() { + return Mockito.mock(FeatureManager.class); } @Bean - public JobsBrokerService jobsBrokerService(DataAccessService dataAccessService, SessionFactory sessionFactory) { - int maxOpenedInstantiationRequestsToMso = Integer.parseInt(SystemProperties.getProperty(VidProperties.MSO_MAX_OPENED_INSTANTIATION_REQUESTS)); - int pollingIntervalSeconds = Integer.parseInt(SystemProperties.getProperty(VidProperties.MSO_ASYNC_POLLING_INTERVAL_SECONDS)); - - return new JobsBrokerServiceInDatabaseImpl(dataAccessService, sessionFactory, maxOpenedInstantiationRequestsToMso, pollingIntervalSeconds); + public JobAdapter jobAdapter(FeatureManager featureManager) { + return new JobAdapterImpl(featureManager); } -} +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/config/JobCommandsConfigWithMockedMso.java b/vid-app-common/src/test/java/org/onap/vid/config/JobCommandsConfigWithMockedMso.java index 1fc46eeb9..c4f788689 100644 --- a/vid-app-common/src/test/java/org/onap/vid/config/JobCommandsConfigWithMockedMso.java +++ b/vid-app-common/src/test/java/org/onap/vid/config/JobCommandsConfigWithMockedMso.java @@ -28,6 +28,7 @@ import org.onap.vid.aai.util.HttpsAuthClient; import org.onap.vid.aai.util.SSLContextProvider; import org.onap.vid.aai.util.ServletRequestHelper; import org.onap.vid.aai.util.SystemPropertyHelper; +import org.onap.vid.dal.AsyncInstantiationRepository; import org.onap.vid.job.JobAdapter; import org.onap.vid.job.JobsBrokerService; import org.onap.vid.job.command.*; @@ -52,8 +53,13 @@ public class JobCommandsConfigWithMockedMso { } @Bean - public JobsBrokerService jobsBrokerService(DataAccessService dataAccessService, SessionFactory sessionFactory) { - return new JobsBrokerServiceInDatabaseImpl(dataAccessService, sessionFactory, 200, 0); + public VersionService versionService() { + return Mockito.mock(VersionService.class); + } + + @Bean + public JobsBrokerService jobsBrokerService(DataAccessService dataAccessService, SessionFactory sessionFactory, VersionService versionService) { + return new JobsBrokerServiceInDatabaseImpl(dataAccessService, sessionFactory, 200, 0,versionService); } @Bean @@ -76,9 +82,10 @@ public class JobCommandsConfigWithMockedMso { return new HttpsAuthClient("some random path", systemPropertyHelper, sslContextProvider, featureManager); } + @Bean - public JobAdapter jobAdapter() { - return new JobAdapterImpl(); + public JobAdapter jobAdapter(FeatureManager featureManager) { + return new JobAdapterImpl(featureManager); } @Bean @@ -100,119 +107,159 @@ public class JobCommandsConfigWithMockedMso { } @Bean - public AsyncInstantiationBusinessLogic asyncInstantiationBusinessLogic(DataAccessService dataAccessService, - JobAdapter jobAdapter, - JobsBrokerService jobsBrokerService, - SessionFactory sessionFactory, - AaiClientInterface aaiClient, - FeatureManager featureManager, - CloudOwnerService cloudOwnerService) { - return new AsyncInstantiationBusinessLogicImpl(dataAccessService, jobAdapter, jobsBrokerService, sessionFactory, aaiClient, featureManager, cloudOwnerService); + public MsoRequestBuilder msoRequestHandlerService(AsyncInstantiationBusinessLogic asyncInstantiationBusinessLogic, + CloudOwnerService cloudOwnerService, + AaiClientInterface aaiClient, + FeatureManager featureManager) { + return new MsoRequestBuilder(asyncInstantiationBusinessLogic, cloudOwnerService, aaiClient, featureManager); } - @Bean - @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public MacroServiceInstantiationCommand serviceInstantiationCommand() { - return new MacroServiceInstantiationCommand(); + public AsyncInstantiationRepository asyncInstantiationRepository(DataAccessService dataAccessService) { + return new AsyncInstantiationRepository(dataAccessService); } @Bean - @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public ServiceInProgressStatusCommand inProgressStatusCommand() { - return new ServiceInProgressStatusCommand(); + public AsyncInstantiationBusinessLogic asyncInstantiationBusinessLogic(JobAdapter jobAdapter, + JobsBrokerService jobsBrokerService, + SessionFactory sessionFactory, + AaiClientInterface aaiClient, + FeatureManager featureManager, + CloudOwnerService cloudOwnerService, + AsyncInstantiationRepository asyncInstantiationRepository, + AuditService auditService) { + return new AsyncInstantiationBusinessLogicImpl(jobAdapter, jobsBrokerService, sessionFactory, aaiClient, featureManager, cloudOwnerService, asyncInstantiationRepository, auditService); } - @Bean - @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public ALaCarteServiceInstantiationCommand aLaCarteServiceInstantiationCommand() { - return new ALaCarteServiceInstantiationCommand(); - } @Bean @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) public ALaCarteServiceCommand aLaCarteServiceCommand( AsyncInstantiationBusinessLogic asyncInstantiationBusinessLogic, JobsBrokerService jobsBrokerService, + MsoRequestBuilder msoRequestBuilder, MsoResultHandlerService msoResultHandlerService, JobAdapter jobAdapter, InProgressStatusService inProgressStatusService, WatchChildrenJobsBL watchChildrenJobsBL, - RestMsoImplementation restMso) { - return new ALaCarteServiceCommand(inProgressStatusService, watchChildrenJobsBL, asyncInstantiationBusinessLogic, jobsBrokerService, msoResultHandlerService, jobAdapter, restMso); + RestMsoImplementation restMso, + AuditService auditService) { + return new ALaCarteServiceCommand(inProgressStatusService, watchChildrenJobsBL, asyncInstantiationBusinessLogic, jobsBrokerService, msoRequestBuilder, msoResultHandlerService, jobAdapter, restMso, auditService); } @Bean @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public InstanceGroupCommand instanceGroupCommand( + public MacroServiceCommand macroServiceCommand( AsyncInstantiationBusinessLogic asyncInstantiationBusinessLogic, - MsoResultHandlerService msoResultHandlerService, InProgressStatusService inProgressStatusService, + JobsBrokerService jobsBrokerService, + MsoRequestBuilder msoRequestBuilder, + MsoResultHandlerService msoResultHandlerService, + JobAdapter jobAdapter, + InProgressStatusService inProgressStatusService, WatchChildrenJobsBL watchChildrenJobsBL, - RestMsoImplementation restMso) { - return new InstanceGroupCommand(asyncInstantiationBusinessLogic, restMso, msoResultHandlerService, inProgressStatusService, watchChildrenJobsBL); + RestMsoImplementation restMso, + AuditService auditService) { + return new MacroServiceCommand(inProgressStatusService, watchChildrenJobsBL, asyncInstantiationBusinessLogic, jobsBrokerService, msoRequestBuilder, msoResultHandlerService, jobAdapter, restMso, auditService); } - @Bean - @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public VnfInstantiationCommand vnfInstantiationCommand() { - return new VnfInstantiationCommand(); - } @Bean @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public VolumeGroupInstantiationCommand volumeGroupInstantiationCommand() { - return new VolumeGroupInstantiationCommand(); - } - - @Bean - @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public WatchingCommandBaseModule watchingCommandBaseModule() { - return new WatchingCommandBaseModule(); + public NetworkCommand networkCommand( + AsyncInstantiationBusinessLogic asyncInstantiationBusinessLogic, + RestMsoImplementation restMso, + MsoRequestBuilder msoRequestBuilder, + MsoResultHandlerService msoResultHandlerService, + InProgressStatusService inProgressStatusService, + WatchChildrenJobsBL watchChildrenJobsBL, + JobsBrokerService jobsBrokerService, + JobAdapter jobAdapter) { + return new NetworkCommand(asyncInstantiationBusinessLogic, restMso, msoRequestBuilder, msoResultHandlerService, + inProgressStatusService, watchChildrenJobsBL, jobsBrokerService, jobAdapter); } - @Bean @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public VolumeGroupInProgressStatusCommand volumeGroupInProgressStatusCommand() { - return new VolumeGroupInProgressStatusCommand(); + public InstanceGroupCommand instanceGroupCommand( + AsyncInstantiationBusinessLogic asyncInstantiationBusinessLogic, + MsoRequestBuilder msoRequestBuilder, + MsoResultHandlerService msoResultHandlerService, + InProgressStatusService inProgressStatusService, + WatchChildrenJobsBL watchChildrenJobsBL, + RestMsoImplementation restMso, + JobsBrokerService jobsBrokerService, + JobAdapter jobAdapter) { + return new InstanceGroupCommand(asyncInstantiationBusinessLogic, restMso, msoRequestBuilder, msoResultHandlerService, inProgressStatusService, watchChildrenJobsBL, jobsBrokerService, jobAdapter); } @Bean @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public VfmoduleInstantiationCommand vfmoduleInstantiationCommand() { - return new VfmoduleInstantiationCommand(); + public InstanceGroupMemberCommand instanceGroupMemberCommand ( + AsyncInstantiationBusinessLogic asyncInstantiationBusinessLogic, + MsoRequestBuilder msoRequestBuilder, + MsoResultHandlerService msoResultHandlerService, + InProgressStatusService inProgressStatusService, + WatchChildrenJobsBL watchChildrenJobsBL, + RestMsoImplementation restMso, + JobsBrokerService jobsBrokerService, + JobAdapter jobAdapter) { + return new InstanceGroupMemberCommand(asyncInstantiationBusinessLogic, restMso, msoRequestBuilder, msoResultHandlerService, inProgressStatusService, + watchChildrenJobsBL, jobsBrokerService, jobAdapter); } - @Bean - @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public WatchingCommand watchingCommandCommand() { - return new WatchingCommand(); - } @Bean @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public ResourceInProgressStatusCommand resourceInProgressStatusCommand() { - return new ResourceInProgressStatusCommand(); + public VnfCommand VnfCommand( + AsyncInstantiationBusinessLogic asyncInstantiationBusinessLogic, + RestMsoImplementation restMso, + MsoRequestBuilder msoRequestBuilder, + MsoResultHandlerService msoResultHandlerService, + InProgressStatusService inProgressStatusService, + WatchChildrenJobsBL watchChildrenJobsBL, + JobsBrokerService jobsBrokerService, + JobAdapter jobAdapter, + FeatureManager featureManager) { + return new VnfCommand(asyncInstantiationBusinessLogic, restMso, msoRequestBuilder, msoResultHandlerService, + inProgressStatusService, watchChildrenJobsBL, jobsBrokerService ,jobAdapter, + featureManager); } @Bean @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public VnfInProgressStatusCommand vnfInProgressStatusCommand() { - return new VnfInProgressStatusCommand(); + public VolumeGroupCommand volumeGroupCommand( + AsyncInstantiationBusinessLogic asyncInstantiationBusinessLogic, + RestMsoImplementation restMso, + MsoRequestBuilder msoRequestBuilder, + MsoResultHandlerService msoResultHandlerService, + InProgressStatusService inProgressStatusService, + WatchChildrenJobsBL watchChildrenJobsBL, + JobsBrokerService jobsBrokerService, + JobAdapter jobAdapter) { + return new VolumeGroupCommand(asyncInstantiationBusinessLogic, restMso, msoRequestBuilder, msoResultHandlerService, + inProgressStatusService, watchChildrenJobsBL, jobsBrokerService ,jobAdapter); } @Bean @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) - public InstanceGroupInstantiationCommand instanceGroupInstantiationCommand() { - return new InstanceGroupInstantiationCommand(); + public VfmoduleCommand VfmoduleCommand( + AsyncInstantiationBusinessLogic asyncInstantiationBusinessLogic, + RestMsoImplementation restMso, + MsoRequestBuilder msoRequestBuilder, + MsoResultHandlerService msoResultHandlerService, + InProgressStatusService inProgressStatusService, + WatchChildrenJobsBL watchChildrenJobsBL, + JobsBrokerService jobsBrokerService, + JobAdapter jobAdapter) { + return new VfmoduleCommand(asyncInstantiationBusinessLogic, restMso, msoRequestBuilder, msoResultHandlerService, + inProgressStatusService, watchChildrenJobsBL, jobsBrokerService, jobAdapter); } - @Bean - public AuditService auditService(AsyncInstantiationBusinessLogic asyncInstantiationBL, RestMsoImplementation msoClient) { - return new AuditServiceImpl(asyncInstantiationBL, msoClient); + public AuditService auditService(RestMsoImplementation msoClient, AsyncInstantiationRepository asyncInstantiationRepository) { + return new AuditServiceImpl(msoClient, asyncInstantiationRepository); } @Bean - public InProgressStatusService inProgressStatusService(AsyncInstantiationBusinessLogic asyncInstantiationBL, RestMsoImplementation restMso, AuditService auditService) { - return new InProgressStatusService(asyncInstantiationBL, restMso, auditService); + public InProgressStatusService inProgressStatusService(AsyncInstantiationBusinessLogic asyncInstantiationBL, RestMsoImplementation restMso, AuditService auditService, FeatureManager featureManager) { + return new InProgressStatusService(asyncInstantiationBL, restMso, auditService, featureManager); } @Bean diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java index a60aa7ea6..2377c8055 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java @@ -21,8 +21,14 @@ package org.onap.vid.controller; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.booleanThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; @@ -34,13 +40,16 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; +import java.io.IOException; import java.util.Map; import java.util.UUID; +import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.Response; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; +import org.mockito.MockitoAnnotations; import org.mockito.junit.MockitoJUnitRunner; import org.onap.vid.aai.AaiResponse; import org.onap.vid.aai.AaiResponseTranslator.PortMirroringConfigData; @@ -53,14 +62,18 @@ import org.onap.vid.aai.model.PortDetailsTranslator.PortDetails; import org.onap.vid.aai.model.PortDetailsTranslator.PortDetailsError; import org.onap.vid.aai.model.PortDetailsTranslator.PortDetailsOk; import org.onap.vid.aai.util.AAIRestInterface; +import org.onap.vid.properties.Features; +import org.onap.vid.roles.Role; import org.onap.vid.model.VersionByInvariantIdsRequest; import org.onap.vid.roles.RoleProvider; +import org.onap.vid.roles.RoleValidator; import org.onap.vid.services.AaiService; import org.onap.vid.utils.SystemPropertiesWrapper; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.togglz.core.manager.FeatureManager; @RunWith(MockitoJUnitRunner.class) public class AaiControllerTest { @@ -76,12 +89,16 @@ public class AaiControllerTest { private RoleProvider roleProvider; @Mock private SystemPropertiesWrapper systemPropertiesWrapper; + + @Mock + private FeatureManager featureManager; + private MockMvc mockMvc; private AaiController aaiController; @Before public void setUp() { - aaiController = new AaiController(aaiService, aaiRestInterface, roleProvider, systemPropertiesWrapper); + aaiController = new AaiController(aaiService, aaiRestInterface, roleProvider, systemPropertiesWrapper, featureManager); mockMvc = MockMvcBuilders.standaloneSetup(aaiController).build(); } @@ -248,5 +265,42 @@ public class AaiControllerTest { .andExpect(status().isOk()) .andExpect(content().string(expectedResponse)); } + + @Test + public void getSubscriberDetailsOmitServiceInstances_reduceDepthEnabledAndOmitQueryParam() throws IOException { + getSubscriberDetailsOmitServiceInstances("some subscriber id", + true, true, true); + } + + @Test + public void getSubscriberDetailsOmitServiceInstances_reduceDepthDisabledAndOmitQueryParam() throws IOException { + getSubscriberDetailsOmitServiceInstances("another-subscriber-id-123", + false, true, false); + } + + @Test + public void getSubscriberDetailsOmitServiceInstances_reduceDepthDisabled() throws IOException { + getSubscriberDetailsOmitServiceInstances("123-456-789-123-345-567-6", + false, false, false); + } + + @Test + public void getSubscriberDetailsOmitServiceInstances_reduceDepthEnabled() throws IOException { + getSubscriberDetailsOmitServiceInstances("0000000000000000000000000", + true, false, false); + } + + private void getSubscriberDetailsOmitServiceInstances(String subscriberId, boolean isFlag1906AaiSubDetailsReduceDepthEnabled, + boolean omitServiceInstancesQueryParam, boolean omitServiceInstancesExpectedGetSubscriberDataParam) throws IOException { + when(featureManager.isActive(Features.FLAG_1906_AAI_SUB_DETAILS_REDUCE_DEPTH)).thenReturn(isFlag1906AaiSubDetailsReduceDepthEnabled); + HttpServletRequest request = mock(HttpServletRequest.class); + when(roleProvider.getUserRoles(request)).thenReturn(ImmutableList.of(mock(Role.class), mock(Role.class))); + AaiResponse subscriberData = mock(AaiResponse.class); + when(subscriberData.getT()).thenReturn(null); + when(subscriberData.getHttpCode()).thenReturn(200); + when(aaiService.getSubscriberData(any(), any(), anyBoolean())).thenReturn(subscriberData); + aaiController.getSubscriberDetails(request, subscriberId, omitServiceInstancesQueryParam); + verify(aaiService).getSubscriberData(argThat(subscriberId::equals), any(RoleValidator.class), booleanThat(b -> omitServiceInstancesExpectedGetSubscriberDataParam == b)); + } } diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/AaiServiceInstanceStandardQueryControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/AaiServiceInstanceStandardQueryControllerTest.java index 2a8db9650..b036b4794 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controller/AaiServiceInstanceStandardQueryControllerTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/controller/AaiServiceInstanceStandardQueryControllerTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,18 +20,20 @@ package org.onap.vid.controller; -import org.mockito.Answers; +import com.google.common.collect.ImmutableList; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.onap.vid.aai.util.ServiceInstanceStandardQuery; import org.onap.vid.asdc.AsdcCatalogException; import org.onap.vid.model.Service; import org.onap.vid.model.ServiceModel; import org.onap.vid.model.VidNotions; import org.onap.vid.model.VidNotions.ModelCategory; +import org.onap.vid.model.aaiTree.AAITreeNode; import org.onap.vid.properties.Features; +import org.onap.vid.services.AAIServiceTree; import org.onap.vid.services.VidService; +import org.springframework.http.HttpMethod; import org.springframework.mock.web.MockHttpServletRequest; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; @@ -56,8 +58,9 @@ public class AaiServiceInstanceStandardQueryControllerTest { @Mock private VidService sdcService; - @Mock(answer = Answers.RETURNS_MOCKS) - private ServiceInstanceStandardQuery serviceInstanceStandardQuery; + @Mock + private AAIServiceTree aaiServiceTree; + //Don't use initMocks with @BeforeMethod //because AaiServiceInstanceStandardQueryController contains final members that can not be injected twice @@ -69,7 +72,7 @@ public class AaiServiceInstanceStandardQueryControllerTest { @AfterMethod public void resetMocks() { - reset(sdcService, featureManager, serviceInstanceStandardQuery); + reset(sdcService, featureManager); } @Test @@ -80,13 +83,14 @@ public class AaiServiceInstanceStandardQueryControllerTest { // - assert that AAI was accessed when(featureManager.isActive(Features.FLAG_PRESENT_PROVIDER_NETWORKS_ASSOCIATIONS)).thenReturn(true); + when(aaiServiceTree.buildAAITree(any(), any(), any(HttpMethod.class), any(), anyBoolean())).thenReturn(ImmutableList.of(mock(AAITreeNode.class))); final UUID randomModelUuid = UUID.randomUUID(); mockServiceModel(ModelCategory.IS_5G_PROVIDER_NETWORK_MODEL, randomModelUuid); doGetNetworksToVlansByServiceInstance(randomModelUuid); - verify(serviceInstanceStandardQuery).fetchServiceInstance(any(), any(), any()); + verify(aaiServiceTree).buildAAITree(any(), any(), any(HttpMethod.class), any(), anyBoolean()); } @Test @@ -103,7 +107,7 @@ public class AaiServiceInstanceStandardQueryControllerTest { mockServiceModel(ModelCategory.OTHER, randomModelUuid); assertThat(doGetNetworksToVlansByServiceInstance(randomModelUuid).serviceNetworks, hasSize(0)); - verifyZeroInteractions(serviceInstanceStandardQuery); + verifyZeroInteractions(aaiServiceTree); } @Test @@ -123,7 +127,7 @@ public class AaiServiceInstanceStandardQueryControllerTest { Service mockedService = mock(Service.class); when(mockedModel.getService()).thenReturn(mockedService); when(mockedService.getVidNotions()).thenReturn( - new VidNotions(instantiationUI, modelCategory, VidNotions.InstantiationUI.LEGACY) + new VidNotions(instantiationUI, modelCategory, VidNotions.InstantiationUI.LEGACY, VidNotions.InstantiationType.ALaCarte) ); when(sdcService.getService(randomModelUuid.toString())).thenReturn(mockedModel); @@ -137,4 +141,4 @@ public class AaiServiceInstanceStandardQueryControllerTest { "my service type", "my instance id"); } -} +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/LocalWebConfig.java b/vid-app-common/src/test/java/org/onap/vid/controller/LocalWebConfig.java index 7e50c8959..701f1c62a 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controller/LocalWebConfig.java +++ b/vid-app-common/src/test/java/org/onap/vid/controller/LocalWebConfig.java @@ -44,6 +44,7 @@ import org.togglz.core.manager.FeatureManager; import javax.servlet.ServletContext; import java.io.File; +import java.util.concurrent.ExecutorService; @Configuration public class LocalWebConfig { @@ -66,8 +67,8 @@ public class LocalWebConfig { @Bean public AaiService getAaiService(AaiClientInterface aaiClient, AaiOverTLSClientInterface aaiOverTLSClient, - AaiResponseTranslator aaiResponseTranslator, AAITreeNodeBuilder aaiTreeNode, AAIServiceTree aaiServiceTree) { - return new AaiServiceImpl(aaiClient, aaiOverTLSClient, aaiResponseTranslator, aaiTreeNode, aaiServiceTree); + AaiResponseTranslator aaiResponseTranslator, AAITreeNodeBuilder aaiTreeNode, AAIServiceTree aaiServiceTree, ExecutorService executorService) { + return new AaiServiceImpl(aaiClient, aaiOverTLSClient, aaiResponseTranslator, aaiTreeNode, aaiServiceTree, executorService); } @Bean diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerNewTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerNewTest.java index a5222dd04..43edeebe9 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerNewTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerNewTest.java @@ -20,24 +20,24 @@ package org.onap.vid.controller; +import static org.mockito.Mockito.mock; + +import javax.servlet.http.HttpServletRequest; import org.junit.Test; import org.onap.vid.mso.MsoBusinessLogicImpl; import org.onap.vid.mso.MsoInterface; +import org.onap.vid.mso.rest.MsoRestClientNew; import org.onap.vid.mso.rest.RequestDetails; import org.onap.vid.mso.rest.RequestDetailsWrapper; import org.onap.vid.services.CloudOwnerServiceImpl; import org.springframework.http.ResponseEntity; -import org.togglz.core.manager.FeatureManager; - -import javax.servlet.http.HttpServletRequest; - -import static org.mockito.Mockito.mock; public class MsoControllerNewTest { private MsoController createTestSubject() { try { - return new MsoController(new MsoBusinessLogicImpl(mock(MsoInterface.class),mock(FeatureManager.class)), new CloudOwnerServiceImpl(null, null)); + return new MsoController(new MsoBusinessLogicImpl(mock(MsoInterface.class)), mock(MsoRestClientNew.class), + new CloudOwnerServiceImpl(null, null)); } catch (Exception e) { return null; } diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerTest.java index 02ab287be..a1b45590c 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerTest.java @@ -46,6 +46,7 @@ import org.junit.Before; import org.junit.Test; import org.onap.vid.mso.MsoBusinessLogic; import org.onap.vid.mso.MsoResponseWrapper; +import org.onap.vid.mso.rest.MsoRestClientNew; import org.onap.vid.mso.rest.Request; import org.onap.vid.mso.rest.RequestDetails; import org.onap.vid.mso.rest.Task; @@ -66,12 +67,14 @@ public class MsoControllerTest { private MockMvc mockMvc; private MsoBusinessLogic msoBusinessLogic; private CloudOwnerService cloudService; + private MsoRestClientNew msoRestClient; @Before public void setUp() { msoBusinessLogic = mock(MsoBusinessLogic.class); cloudService = mock(CloudOwnerService.class); - MsoController msoController = new MsoController(msoBusinessLogic, cloudService); + msoRestClient = mock(MsoRestClientNew.class); + MsoController msoController = new MsoController(msoBusinessLogic, msoRestClient, cloudService); mockMvc = MockMvcBuilders.standaloneSetup(msoController).build(); } diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/ToscaParserMockHelper.java b/vid-app-common/src/test/java/org/onap/vid/controller/ToscaParserMockHelper.java index 2eedee9d7..9e77e99e3 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controller/ToscaParserMockHelper.java +++ b/vid-app-common/src/test/java/org/onap/vid/controller/ToscaParserMockHelper.java @@ -22,25 +22,21 @@ package org.onap.vid.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.module.kotlin.KotlinModule; -import org.apache.commons.io.IOUtils; -import org.apache.log4j.LogManager; -import org.apache.log4j.Logger; -import org.onap.vid.model.NewServiceModel; - import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; +import org.apache.commons.io.IOUtils; +import org.apache.log4j.LogManager; +import org.apache.log4j.Logger; +import org.onap.vid.model.ServiceModel; -/** - * Created by moriya1 on 04/07/2017. - */ public class ToscaParserMockHelper { private static final Logger logger = LogManager.getLogger(ToscaParserMockHelper.class); private static final ObjectMapper om = new ObjectMapper(); private final String uuid; private final String filePath; - private final NewServiceModel newServiceModel; + private final ServiceModel serviceModel; public ToscaParserMockHelper(String uuid, String filePath) throws IOException { this.uuid = uuid; @@ -50,7 +46,7 @@ public class ToscaParserMockHelper { logger.info(jsonFile); String expectedJsonAsString = IOUtils.toString(jsonFile, StandardCharsets.UTF_8.name()); om.registerModule(new KotlinModule()); - this.newServiceModel = om.readValue(expectedJsonAsString, NewServiceModel.class); + this.serviceModel = om.readValue(expectedJsonAsString, ServiceModel.class); } public String getUuid() { @@ -61,7 +57,7 @@ public class ToscaParserMockHelper { return filePath; } - public NewServiceModel getNewServiceModel() { - return newServiceModel; + public ServiceModel getServiceModel() { + return serviceModel; } } diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/VidControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/VidControllerTest.java index 39d3cddc7..484f4a034 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controller/VidControllerTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/controller/VidControllerTest.java @@ -178,7 +178,7 @@ public class VidControllerTest { private ServiceModel createServiceModel(int i) { ServiceModel model = new ServiceModel(); - model.setCollectionResource(ImmutableMap.of("resKey" + i, new CR())); + model.setCollectionResources(ImmutableMap.of("resKey" + i, new CR())); model.setNetworks(ImmutableMap.of("network" + i, new Network())); model.setPnfs(ImmutableMap.of("pnf" + i, new Node())); model.setServiceProxies(ImmutableMap.of("servProxy" + i, new ServiceProxy())); diff --git a/vid-app-common/src/test/java/org/onap/vid/dal/AsyncInstantiationRepositoryTest.java b/vid-app-common/src/test/java/org/onap/vid/dal/AsyncInstantiationRepositoryTest.java new file mode 100644 index 000000000..be5a44e82 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/dal/AsyncInstantiationRepositoryTest.java @@ -0,0 +1,103 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.vid.dal; + +import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals; +import static net.javacrumbs.jsonunit.core.Option.IGNORING_ARRAY_ORDER; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.collection.IsCollectionWithSize.hasSize; +import static org.hamcrest.core.IsEqual.equalTo; + +import com.google.common.collect.ImmutableList; +import java.time.ZonedDateTime; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; +import javax.inject.Inject; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.vid.config.DataSourceConfig; +import org.onap.vid.config.MockedAaiClientAndFeatureManagerConfig; +import org.onap.vid.job.Job; +import org.onap.vid.model.ResourceInfo; +import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; +import org.onap.vid.mso.rest.AsyncRequestStatus; +import org.onap.vid.mso.rest.RequestStatus; +import org.onap.vid.services.AsyncInstantiationBaseTest; +import org.onap.vid.utils.TimeUtils; +import org.springframework.test.context.ContextConfiguration; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +@ContextConfiguration(classes = {DataSourceConfig.class, SystemProperties.class, MockedAaiClientAndFeatureManagerConfig.class}) +public class AsyncInstantiationRepositoryTest extends AsyncInstantiationBaseTest { + + @Inject + private DataAccessService dataAccessService; + + @BeforeClass + void initServicesInfoService() { + createInstanceParamsMaps(); + } + + @Test + public void whenSaveNewRequest_thenRequestIsRetrieved() { + AsyncInstantiationRepository underTest = new AsyncInstantiationRepository(dataAccessService); + ServiceInstantiation serviceInstantiation = generateALaCarteWithVnfsServiceInstantiationPayload(); + UUID jobUuid = UUID.randomUUID(); + underTest.addJobRequest(jobUuid, serviceInstantiation); + ServiceInstantiation stored = underTest.getJobRequest(jobUuid); + assertThat(stored, jsonEquals(serviceInstantiation).when(IGNORING_ARRAY_ORDER)); + } + + private AsyncRequestStatus createAsyncRequestStatus(String message, String requestState){ + RequestStatus requestStatus = new RequestStatus(requestState, message, TimeUtils.zonedDateTimeToString(ZonedDateTime.now())); + AsyncRequestStatus.Request request = new AsyncRequestStatus.Request(requestStatus); + return new AsyncRequestStatus(request); + } + + @Test + public void getResourceInfoByRootJobId_returnsMapOfjobIdResources(){ + AsyncInstantiationRepository underTest = new AsyncInstantiationRepository(dataAccessService); + UUID jobId1= UUID.randomUUID(); + UUID jobId2= UUID.randomUUID(); + AsyncRequestStatus errorMessage= createAsyncRequestStatus("MSO failed resource", "FAILED"); + List requestInfoList= ImmutableList.of( + new ResourceInfo("aaaaaa",jobId1, "64f3123a-f9a8-4591-b481-d662134bcb52", Job.JobStatus.COMPLETED, null), + new ResourceInfo("bbbbbb",jobId1, "65f3123a-f9a8-4591-b481-kodj9ig87gdu", Job.JobStatus.COMPLETED_WITH_ERRORS, null), + new ResourceInfo("dddddd",jobId1, null, Job.JobStatus.FAILED, null), + new ResourceInfo("cccccc",jobId1, null, Job.JobStatus.FAILED, errorMessage), + new ResourceInfo("eeeeee",jobId2, null, Job.JobStatus.FAILED, null), + new ResourceInfo("ffffff",jobId2, "66f3123a-f9a8-4591-b481-ghfgh6767567", Job.JobStatus.COMPLETED, null) + ); + for(ResourceInfo info: requestInfoList){ + underTest.saveResourceInfo(info); + } + Map storedByTrackId = underTest.getResourceInfoByRootJobId(jobId1); + assertThat(storedByTrackId.values(), hasSize(4)); + assertThat(storedByTrackId.get("aaaaaa").getInstanceId(), equalTo("64f3123a-f9a8-4591-b481-d662134bcb52")); + assertThat(storedByTrackId.get("cccccc").getErrorMessage().request.requestStatus.getStatusMessage(), equalTo("MSO failed resource")); + assertThat(storedByTrackId.get("cccccc").getErrorMessage().request.requestStatus.getRequestState(), equalTo("FAILED")); + assertThat(storedByTrackId.get("dddddd").getErrorMessage(), equalTo(null)); + assertThat(storedByTrackId.values(), jsonEquals(requestInfoList.stream().filter(i-> i.getRootJobId().equals(jobId1)).collect(Collectors.toList())).when(IGNORING_ARRAY_ORDER)); + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/CommandUtilsTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/CommandUtilsTest.java index da300bf3e..ee43d1f72 100644 --- a/vid-app-common/src/test/java/org/onap/vid/job/command/CommandUtilsTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/CommandUtilsTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/InProgressStatusServiceTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/InProgressStatusServiceTest.java index c8772ee76..125d2ed4c 100644 --- a/vid-app-common/src/test/java/org/onap/vid/job/command/InProgressStatusServiceTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/InProgressStatusServiceTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,8 +20,10 @@ package org.onap.vid.job.command; +import org.jetbrains.annotations.NotNull; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.onap.vid.job.Job; import org.onap.vid.job.impl.JobSharedData; @@ -29,11 +31,16 @@ import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; import org.onap.vid.mso.RestMsoImplementation; import org.onap.vid.mso.RestObject; import org.onap.vid.mso.rest.AsyncRequestStatus; -import org.onap.vid.services.AsyncInstantiationBaseTest; +import org.onap.vid.properties.Features; import org.onap.vid.services.AsyncInstantiationBusinessLogic; +import org.onap.vid.services.AuditService; +import org.onap.vid.services.AsyncInstantiationBaseTest; +import org.onap.vid.testUtils.TestUtils; import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import org.togglz.core.manager.FeatureManager; import java.util.UUID; import java.util.stream.Stream; @@ -51,6 +58,12 @@ public class InProgressStatusServiceTest { @Mock private AsyncInstantiationBusinessLogic asyncInstantiationBL; + @Mock + private AuditService auditService; + + @Mock + private FeatureManager featureManager; + @InjectMocks private InProgressStatusService inProgressStatusService; @@ -59,10 +72,16 @@ public class InProgressStatusServiceTest { MockitoAnnotations.initMocks(this); } + @BeforeMethod + public void resetMocks() { + Mockito.reset(restMso); + Mockito.reset(asyncInstantiationBL); + } + @DataProvider public static Object[][] jobStatuses() { return Stream.of(Job.JobStatus.values()) - .map(student -> new Object[] { student }) + .map(status -> new Object[] { status }) .toArray(Object[][]::new); } @@ -71,16 +90,14 @@ public class InProgressStatusServiceTest { UUID jobUuid = UUID.randomUUID(); String userId = "mockedUserID"; + String testApi = "mockedTestApi"; String requestId = UUID.randomUUID().toString(); ServiceInstantiation serviceInstantiation = mock(ServiceInstantiation.class); when(asyncInstantiationBL.getOrchestrationRequestsPath()).thenReturn(""); - RestObject msoResponse = mock(RestObject.class); AsyncRequestStatus requestStatus = AsyncInstantiationBaseTest.asyncRequestStatusResponse(""); - - when(msoResponse.getStatusCode()).thenReturn(200); - when(msoResponse.get()).thenReturn(requestStatus); + RestObject msoResponse = createMockedAsyncRequestStatus(requestStatus, 200); when(restMso.GetForObject(contains(requestId), eq(AsyncRequestStatus.class))).thenReturn(msoResponse); when(asyncInstantiationBL.calcStatus(any())).thenReturn(expectedJobStatus); @@ -88,16 +105,60 @@ public class InProgressStatusServiceTest { ExpiryChecker expiryChecker = mock(ExpiryChecker.class); when(expiryChecker.isExpired(any())).thenReturn(false); - JobSharedData sharedData = new JobSharedData(jobUuid, userId, serviceInstantiation); + JobSharedData sharedData = new JobSharedData(jobUuid, userId, serviceInstantiation, testApi); Job.JobStatus actualJobStatus = inProgressStatusService.call(expiryChecker, sharedData, requestId); assertEquals(expectedJobStatus, actualJobStatus); - verify(asyncInstantiationBL).auditMsoStatus(eq(jobUuid), same(requestStatus.request)); - + verify(auditService).auditMsoStatus(eq(jobUuid), same(requestStatus.request)); + verify(asyncInstantiationBL).updateResourceInfo(eq(sharedData), eq(expectedJobStatus), eq(requestStatus)); //verify we don't update service info during this case, which shall stay in_progress verify(asyncInstantiationBL, never()).updateServiceInfo(any(), any()); + } + + @NotNull + protected RestObject createMockedAsyncRequestStatus(AsyncRequestStatus requestStatus, int statusCode) { + RestObject msoResponse = mock(RestObject.class); + when(msoResponse.getStatusCode()).thenReturn(statusCode); + when(msoResponse.get()).thenReturn(requestStatus); + return msoResponse; + } + + @Test(dataProvider = "trueAndFalse", dataProviderClass = TestUtils.class) + public void whenGetAsyncRequestStatus_thenRightResponseReturned(boolean isResumeFlagActive) { + String requestId = "abcRequest"; + String baseMso = "/fakeBase/v15"; + + when(asyncInstantiationBL.getOrchestrationRequestsPath()).thenReturn(baseMso); + when(featureManager.isActive(Features.FLAG_1908_RESUME_MACRO_SERVICE)).thenReturn(isResumeFlagActive); + + AsyncRequestStatus requestStatus = AsyncInstantiationBaseTest.asyncRequestStatusResponse(""); + RestObject mockedResponse = createMockedAsyncRequestStatus(requestStatus, 399); + String path = baseMso + "/" + requestId + (isResumeFlagActive ? "?format=detail" : ""); + when(restMso.GetForObject(eq(path), eq(AsyncRequestStatus.class))).thenReturn(mockedResponse); + + assertEquals(mockedResponse, inProgressStatusService.getAsyncRequestStatus(requestId)); + } + + @DataProvider + public static Object[][] getAsyncReturnErrorDataProvider() { + return new Object[][]{ + {AsyncInstantiationBaseTest.asyncRequestStatusResponse("xyz"), 400}, + {AsyncInstantiationBaseTest.asyncRequestStatusResponse("xyz"), 401}, + {AsyncInstantiationBaseTest.asyncRequestStatusResponse("xyz"), 500}, + {null, 200}, + }; + } + + @Test(dataProvider = "getAsyncReturnErrorDataProvider", expectedExceptions = InProgressStatusService.BadResponseFromMso.class) + public void whenGetAsyncReturnError_thenExceptionIsThrown(AsyncRequestStatus requestStatus, int statusCode) { + String requestId = "abcRequest"; + String baseMso = "/fakeBase/v15"; + when(asyncInstantiationBL.getOrchestrationRequestsPath()).thenReturn(baseMso); + RestObject mockedResponse = createMockedAsyncRequestStatus(requestStatus, statusCode); + when(restMso.GetForObject(eq(baseMso + "/" + requestId), eq(AsyncRequestStatus.class))).thenReturn(mockedResponse); + inProgressStatusService.getAsyncRequestStatus(requestId); } } diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/InstanceGroupCommandTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/InstanceGroupCommandTest.java index b4a5c64f5..c68c5f754 100644 --- a/vid-app-common/src/test/java/org/onap/vid/job/command/InstanceGroupCommandTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/InstanceGroupCommandTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,29 +20,35 @@ package org.onap.vid.job.command; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.eq; -import static org.mockito.Mockito.only; -import static org.mockito.Mockito.same; -import static org.mockito.Mockito.verify; - import com.google.common.collect.ImmutableMap; -import java.util.Optional; +import org.apache.commons.beanutils.BeanUtils; import org.mockito.Answers; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.onap.vid.job.JobAdapter; +import org.onap.vid.job.JobsBrokerService; import org.onap.vid.job.impl.JobSharedData; +import org.onap.vid.model.Action; import org.onap.vid.model.RequestReferencesContainer; import org.onap.vid.model.serviceInstantiation.InstanceGroup; import org.onap.vid.mso.RestMsoImplementation; import org.onap.vid.mso.model.ModelInfo; import org.onap.vid.services.AsyncInstantiationBusinessLogic; -import org.onap.vid.testUtils.TestUtils; import org.springframework.http.HttpMethod; import org.testng.annotations.BeforeMethod; +import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import java.util.Optional; +import java.util.Set; + +import static java.util.function.Function.identity; +import static java.util.stream.Collectors.toMap; +import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + public class InstanceGroupCommandTest { @Mock(answer = Answers.RETURNS_MOCKS) @@ -53,11 +59,20 @@ public class InstanceGroupCommandTest { @Mock(answer = Answers.RETURNS_MOCKS) MsoResultHandlerService msoResultHandlerService; + @Mock(answer = Answers.RETURNS_MOCKS) + MsoRequestBuilder msoRequestBuilder; + @Mock WatchChildrenJobsBL watchChildrenJobsBL; @Mock(answer = Answers.RETURNS_MOCKS) AsyncInstantiationBusinessLogic asyncInstantiationBL; + @Mock(answer = Answers.RETURNS_MOCKS) + JobsBrokerService jobsBrokerService; + + @Mock(answer = Answers.RETURNS_MOCKS) + JobAdapter jobAdapter; + @Mock InProgressStatusService inProgressStatusService; @InjectMocks @@ -68,29 +83,41 @@ public class InstanceGroupCommandTest { command = null; MockitoAnnotations.initMocks(this); } - - @Test - public void createMyself_callsMso() { - final ModelInfo serviceModelInfo = setStrings(new ModelInfo()); + @DataProvider + public static Object[][] testApis() { + return new Object[][]{ + {"VNF_API"}, {null}}; + } + @Test(dataProvider = "testApis") + public void createMyself_callsMso(String testApi) { + final ModelInfo serviceModelInfo = setRandomStrings(new ModelInfo()); final String serviceInstanceId = "service-instance-id"; final String userId = "ff3223"; - command.init(new JobSharedData( - null, userId, instanceGroupRequest - ), ImmutableMap.of( + when(instanceGroupRequest.getAction()).thenReturn(Action.Delete); + + JobSharedData sharedData = new JobSharedData( + null, userId, instanceGroupRequest, testApi); + command.init(sharedData, ImmutableMap.of( "resourceModelInfos", ImmutableMap.of("SERVICE_MODEL_INFO", serviceModelInfo), "resourceInstancesIds", ImmutableMap.of("SERVICE_INSTANCE_ID", serviceInstanceId) )); command.createMyself(); - verify(asyncInstantiationBL).generateInstanceGroupInstantiationRequest( - same(instanceGroupRequest), eq(serviceModelInfo), eq(serviceInstanceId), eq(userId)); + verify(msoRequestBuilder).generateInstanceGroupInstantiationRequest( + same(instanceGroupRequest), eq(serviceModelInfo), eq(serviceInstanceId), eq(userId), eq(testApi)); verify(restMso, only()).restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), any(), eq(Optional.empty())); - } - private ModelInfo setStrings(ModelInfo object) { - return TestUtils.setStringsInStringProperties(object); + private ModelInfo setRandomStrings(ModelInfo object) { + try { + Set fields = BeanUtils.describe(object).keySet(); + BeanUtils.populate(object, + fields.stream().collect(toMap(identity(), s -> randomAlphanumeric(4)))); + return object; + } catch (Exception e) { + throw new RuntimeException(e); + } } } diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/JobCommandFactoryTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/JobCommandFactoryTest.java index d7389ad0a..72336e5a9 100644 --- a/vid-app-common/src/test/java/org/onap/vid/job/command/JobCommandFactoryTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/JobCommandFactoryTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -105,7 +105,7 @@ public class JobCommandFactoryTest { final UUID uuid = UUID.randomUUID(); final Map data = ImmutableMap.of("foo", "bar"); - final JobSharedData sharedData = new JobSharedData(uuid, "userid", new MockedRequest(1,"a")); + final JobSharedData sharedData = new JobSharedData(uuid, "userid", new MockedRequest(1,"a"), "testApi"); when(job.getType()).thenReturn(jobType); when(job.getUuid()).thenReturn(uuid); @@ -119,4 +119,4 @@ public class JobCommandFactoryTest { assertThat(command, equalTo(mockCommand)); } -} +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/MacroServiceCommandTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/MacroServiceCommandTest.java new file mode 100644 index 000000000..e4771611c --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/MacroServiceCommandTest.java @@ -0,0 +1,136 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.vid.job.command; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.onap.vid.model.VidNotions.ModelCategory.INFRASTRUCTURE_VPN; +import static org.onap.vid.model.VidNotions.ModelCategory.IS_5G_FABRIC_CONFIGURATION_MODEL; +import static org.onap.vid.model.VidNotions.ModelCategory.IS_5G_PROVIDER_NETWORK_MODEL; +import static org.onap.vid.model.VidNotions.ModelCategory.OTHER; +import static org.onap.vid.model.VidNotions.ModelCategory.SERVICE_WITH_COLLECTION_RESOURCE; +import static org.onap.vid.model.VidNotions.ModelCategory.Transport; +import static org.testng.AssertJUnit.assertEquals; + +import com.google.common.collect.ImmutableList; +import java.util.Collections; +import java.util.List; +import java.util.UUID; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.vid.job.Job; +import org.onap.vid.job.JobAdapter; +import org.onap.vid.job.JobsBrokerService; +import org.onap.vid.job.impl.JobSharedData; +import org.onap.vid.model.Action; +import org.onap.vid.model.VidNotions; +import org.onap.vid.model.serviceInstantiation.BaseResource; +import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; +import org.onap.vid.mso.RestMsoImplementation; +import org.onap.vid.mso.rest.AsyncRequestStatus; +import org.onap.vid.services.AsyncInstantiationBusinessLogic; +import org.onap.vid.services.AuditService; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +public class MacroServiceCommandTest { + + @Mock + private InProgressStatusService inProgressStatusService; + + @Mock + private WatchChildrenJobsBL watchChildrenJobsB; + + @Mock + private AsyncInstantiationBusinessLogic asyncInstantiationBL; + + @Mock + private JobsBrokerService jobsBrokerService; + + @Mock + private MsoRequestBuilder msoRequestBuilder; + + @Mock + private MsoResultHandlerService msoResultHandlerService; + + @Mock + private JobAdapter jobAdapter; + + @Mock + private RestMsoImplementation restMso; + + @Mock + private AuditService auditService; + + @InjectMocks + private MacroServiceCommand macroServiceCommand; + + @DataProvider + public static Object[][] modelCategoryPre1806DataProvider() { + return new Object[][]{ + {IS_5G_PROVIDER_NETWORK_MODEL, false}, + {IS_5G_FABRIC_CONFIGURATION_MODEL, false}, + {Transport, true}, + {SERVICE_WITH_COLLECTION_RESOURCE, true}, + {INFRASTRUCTURE_VPN, true}, + {OTHER, false}, + }; + } + + @BeforeClass + public void initMocks() { + MockitoAnnotations.initMocks(this); + } + + @Test(dataProvider = "modelCategoryPre1806DataProvider") + public void testShouldUsePre1806Request(VidNotions.ModelCategory modelCategory, boolean expectedResult) { + ServiceInstantiation serviceInstantiation = mock(ServiceInstantiation.class); + VidNotions vidNotions = mock(VidNotions.class); + when(serviceInstantiation.getVidNotions()).thenReturn(vidNotions); + when(vidNotions.getModelCategory()).thenReturn(modelCategory); + assertEquals(macroServiceCommand.shouldUsePre1806Request(serviceInstantiation), expectedResult); + } + + @DataProvider + public static Object[][] MsoFilteredRequestsDataProvider() { + return new Object[][]{ + {Collections.EMPTY_LIST}, + {ImmutableList.of(new AsyncRequestStatus.Request())} + }; + } + + @Test(dataProvider = "MsoFilteredRequestsDataProvider") + public void givenResumeAction_whenCantRetrieveRequestIdFromMSO_thenJobIsFailed(List requests) { + String instanceId = UUID.randomUUID().toString(); + BaseResource baseResource = mock(BaseResource.class); + when(baseResource.getInstanceId()).thenReturn(instanceId); + when(baseResource.getAction()).thenReturn(Action.Resume); + macroServiceCommand.init(new JobSharedData(null, null, baseResource, null)); + when(auditService.retrieveRequestsFromMsoByServiceIdAndRequestTypeAndScope(eq(instanceId), any(), any())) + .thenReturn(requests); + assertEquals(macroServiceCommand.resumeMyself(), Job.JobStatus.FAILED); + } + +} diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/MsoResultHandlerServiceTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/MsoResultHandlerServiceTest.java new file mode 100644 index 000000000..5f958016b --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/MsoResultHandlerServiceTest.java @@ -0,0 +1,95 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.vid.job.command; + +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.onap.vid.job.impl.AsyncInstantiationIntegrationTest.createResponse; +import static org.testng.AssertJUnit.assertEquals; + +import java.util.UUID; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.vid.job.Job; +import org.onap.vid.job.impl.JobSharedData; +import org.onap.vid.model.RequestReferencesContainer; +import org.onap.vid.mso.RestObject; +import org.onap.vid.services.AsyncInstantiationBusinessLogic; +import org.onap.vid.services.AuditService; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +public class MsoResultHandlerServiceTest { + + @Mock + private AsyncInstantiationBusinessLogic asyncInstantiationBusinessLogic; + + @Mock + private AuditService auditService; + + @InjectMocks + private MsoResultHandlerService underTest; + + @BeforeClass + public void initMocks() { + MockitoAnnotations.initMocks(this); + } + + @DataProvider + public static Object[][] okStatusCodes() { + return new Object[][]{ + {200}, {202} , {300}, {399} + }; + } + + @Test(dataProvider = "okStatusCodes") + public void whenOkResponseFromMso_getResultsWithIdsAndCompleteWithNoAction(int statusCode) { + String instanceId = UUID.randomUUID().toString(); + String requestId = UUID.randomUUID().toString(); + JobSharedData sharedData = new JobSharedData(); + RestObject msoResponse = createResponse(statusCode, instanceId, requestId); + MsoResult expectedResult = new MsoResult(Job.JobStatus.COMPLETED_WITH_NO_ACTION, new MsoResourceIds(requestId, instanceId)); + MsoResult actualMsoResult = underTest.handleResponse(sharedData, msoResponse, "test desc"); + assertEquals(expectedResult, actualMsoResult); + verify(asyncInstantiationBusinessLogic).addResourceInfo(eq(sharedData), eq(Job.JobStatus.IN_PROGRESS), eq(instanceId)); + } + + @DataProvider + public static Object[][] notOkStatusCodes() { + return new Object[][]{ + {199}, {400} , {404}, {500} + }; + } + + @Test(dataProvider = "notOkStatusCodes") + public void whenNotOkFromMso_getResultsWithFailedStatus(int statusCode) { + Mockito.reset(asyncInstantiationBusinessLogic); + JobSharedData sharedData = new JobSharedData(); + RestObject msoResponse = createResponse(statusCode); + MsoResult expectedResult = new MsoResult(Job.JobStatus.FAILED); + MsoResult actualMsoResult = underTest.handleResponse(new JobSharedData(), msoResponse, "test desc"); + assertEquals(expectedResult, actualMsoResult); + verify(asyncInstantiationBusinessLogic).addFailedResourceInfo(eq(sharedData), eq(msoResponse)); + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceCommandTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceCommandTest.java index 9f252c5e8..2780e1515 100644 --- a/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceCommandTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceCommandTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,29 +20,38 @@ package org.onap.vid.job.command; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.jetbrains.annotations.NotNull; +import org.onap.vid.exceptions.AbortingException; import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.exceptions.TryAgainException; import org.onap.vid.job.Job; import org.onap.vid.job.JobAdapter; +import org.onap.vid.job.JobsBrokerService; import org.onap.vid.job.NextCommand; import org.onap.vid.job.impl.JobSharedData; import org.onap.vid.model.Action; -import org.onap.vid.model.serviceInstantiation.BaseResource; +import org.onap.vid.model.serviceInstantiation.*; import org.onap.vid.mso.RestMsoImplementation; +import org.onap.vid.mso.model.ModelInfo; import org.springframework.http.HttpMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import javax.ws.rs.ProcessingException; -import java.util.Collections; -import java.util.Optional; +import java.util.*; +import java.util.stream.Collectors; import java.util.stream.Stream; +import static java.util.Collections.emptyList; +import static org.mockito.AdditionalAnswers.returnsFirstArg; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import static org.onap.vid.job.command.ResourceCommandKt.ACTION_PHASE; import static org.onap.vid.job.command.ResourceCommandKt.INTERNAL_STATE; +import static org.onap.vid.job.command.ResourceCommandTest.FakeResourceCreator.*; +import static org.onap.vid.model.Action.*; import static org.onap.vid.utils.Logging.getMethodCallerName; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; @@ -54,18 +63,32 @@ public class ResourceCommandTest { public static class MockCommand extends ResourceCommand { public MockCommand(InternalState mockState, Action mockPhase, Job.JobStatus mockedJobStatus) { - super(mock(RestMsoImplementation.class, RETURNS_MOCKS), mock(InProgressStatusService.class), mock(MsoResultHandlerService.class, RETURNS_MOCKS), mock(WatchChildrenJobsBL.class)); + this(mockState, mockPhase, mockedJobStatus, false); + } + public MockCommand(InternalState mockState, Action mockPhase, Job.JobStatus mockedJobStatus, boolean lateInit) { + super( + mock(RestMsoImplementation.class, RETURNS_MOCKS), + mock(InProgressStatusService.class), + mock(MsoResultHandlerService.class, RETURNS_MOCKS), + mock(WatchChildrenJobsBL.class), + mock(JobsBrokerService.class, RETURNS_MOCKS), + mock(JobAdapter.class, RETURNS_MOCKS)); this.mockedJobStatus = mockedJobStatus; this.mockState = mockState; this.mockPhase = mockPhase; - if (mockState==InternalState.INITIAL) { - init(mock(JobSharedData.class), Collections.emptyMap()); + if (!lateInit) { + init(); } - else { + when(this.getWatchChildrenJobsBL().cumulateJobStatus(any(), any())).thenReturn(mockedJobStatus); + } + + protected void init() { + if (mockState == InternalState.INITIAL) { + init(mock(JobSharedData.class), Collections.emptyMap()); + } else { init(mock(JobSharedData.class), ImmutableMap.of(INTERNAL_STATE, mockState.name(), ACTION_PHASE, mockPhase.name())); } - when(this.getWatchChildrenJobsBL().cumulateJobStatus(any(), any())).thenReturn(mockedJobStatus); } private final Job.JobStatus mockedJobStatus; @@ -76,7 +99,7 @@ public class ResourceCommandTest { @NotNull @Override public Job.JobStatus createChildren() { - if (mockState == InternalState.CREATING_CHILDREN || (mockState == InternalState.INITIAL && mockPhase== Action.Delete)) + if (mockState == InternalState.CREATING_CHILDREN || (mockState == InternalState.INITIAL && mockPhase== Delete)) return mockedJobStatus; throw (new RuntimeException("Not expected to call "+getMethodCallerName())); } @@ -95,7 +118,7 @@ public class ResourceCommandTest { @NotNull @Override - public MsoRestCallPlan planCreateMyselfRestCall(@NotNull CommandParentData commandParentData, @NotNull JobAdapter.AsyncJobRequest request, @NotNull String userId) { + public MsoRestCallPlan planCreateMyselfRestCall(@NotNull CommandParentData commandParentData, @NotNull JobAdapter.AsyncJobRequest request, @NotNull String userId, String testApi) { return mockedPlanOrThrow(InternalState.CREATE_MYSELF); } @@ -109,16 +132,19 @@ public class ResourceCommandTest { public static class MockCommandTestingStateMachine extends MockCommand { private final JobSharedData sharedData; + private final boolean isDescendantHasAction; public MockCommandTestingStateMachine(InternalState mockState, Action mockPhase, Job.JobStatus mockedJobStatus, boolean mockedNeedToDeleteMySelf) { - this(mockState, mockPhase, mockedJobStatus, mockedNeedToDeleteMySelf, false); + this(mockState, mockPhase, mockedJobStatus, mockedNeedToDeleteMySelf, false, true); } - public MockCommandTestingStateMachine(InternalState mockState, Action mockPhase, Job.JobStatus mockedJobStatus, boolean mockedNeedToDeleteMySelf, boolean isService) { - super(mockState, mockPhase, mockedJobStatus); + public MockCommandTestingStateMachine(InternalState mockState, Action mockPhase, Job.JobStatus mockedJobStatus, boolean mockedNeedToDeleteMySelf, boolean isService, boolean isDescendantHasAction) { + super(mockState, mockPhase, mockedJobStatus, true); this.mockedNeedToDeleteMySelf = mockedNeedToDeleteMySelf; this.isService = isService; this.sharedData = mock(JobSharedData.class, RETURNS_MOCKS); + this.isDescendantHasAction = isDescendantHasAction; + init(); } protected final boolean mockedNeedToDeleteMySelf; @@ -150,6 +176,11 @@ public class ResourceCommandTest { public JobSharedData getSharedData() { return sharedData; } + + @Override + protected boolean isDescendantHasAction(@NotNull Action phase) { + return isDescendantHasAction; + } } @DataProvider @@ -171,28 +202,28 @@ public class ResourceCommandTest { InternalState internalState, Job.JobStatus jobStatus, InternalState expectedState) { //there is no meaning to the constructor inputs here - MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(InternalState.TERMINAL, Action.Delete, Job.JobStatus.FAILED, true); + MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(InternalState.TERMINAL, Delete, Job.JobStatus.FAILED, true); assertEquals(expectedState, underTest.calcNextStateDeletePhase(jobStatus, internalState)); } @Test public void whenNoNeedToDeleteMyself_internalStateMovesFromWatchingToTerminal() { - MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(InternalState.WATCHING, Action.Delete, Job.JobStatus.COMPLETED, false); + MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(InternalState.WATCHING, Delete, Job.JobStatus.COMPLETED, false); assertEquals(InternalState.TERMINAL, underTest.calcNextStateDeletePhase(Job.JobStatus.COMPLETED, InternalState.WATCHING)); } @DataProvider public static Object[][] testShallStopJobDataProvider() { return new Object[][]{ - {Job.JobStatus.IN_PROGRESS, Action.None, false, false}, - {Job.JobStatus.COMPLETED_WITH_NO_ACTION, Action.None, false, false}, - {Job.JobStatus.COMPLETED, Action.None, false, false}, - {Job.JobStatus.FAILED, Action.None, false, true}, - {Job.JobStatus.COMPLETED_WITH_ERRORS, Action.None, false, true}, - {Job.JobStatus.COMPLETED_WITH_ERRORS, Action.None, true, false}, - {Job.JobStatus.FAILED, Action.None, true, false}, - {Job.JobStatus.FAILED, Action.Delete, true, true}, - {Job.JobStatus.FAILED, Action.Create, true, true}, + {Job.JobStatus.IN_PROGRESS, None, false, false}, + {Job.JobStatus.COMPLETED_WITH_NO_ACTION, None, false, false}, + {Job.JobStatus.COMPLETED, None, false, false}, + {Job.JobStatus.FAILED, None, false, true}, + {Job.JobStatus.COMPLETED_WITH_ERRORS, None, false, true}, + {Job.JobStatus.COMPLETED_WITH_ERRORS, None, true, false}, + {Job.JobStatus.FAILED, None, true, false}, + {Job.JobStatus.FAILED, Delete, true, true}, + {Job.JobStatus.FAILED, Create, true, true}, }; } @@ -200,7 +231,7 @@ public class ResourceCommandTest { @Test(dataProvider = "testShallStopJobDataProvider") public void testShallStopJob(Job.JobStatus jobStatus, Action action, boolean isService, boolean expectedResult) { //in this test, there is no meaning to constructor parameters besides isService - MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(InternalState.WATCHING, Action.Delete, Job.JobStatus.COMPLETED, false, isService); + MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(InternalState.WATCHING, Delete, Job.JobStatus.COMPLETED, false, isService, true); BaseResource mockedRequest = mock(BaseResource.class); when(underTest.getSharedData().getRequest()).thenReturn(mockedRequest); @@ -209,6 +240,94 @@ public class ResourceCommandTest { assertEquals(expectedResult, underTest.shallStopJob(jobStatus)); } + public static class FakeResourceCreator { + + public static Map convertToMap(List list) { + if (list==null) { + return null; + } + return list.stream().collect(Collectors.toMap(x-> UUID.randomUUID().toString(), x->x)); + } + + static ServiceInstantiation createService(List vnfs, List networks, List vnfGroups) { + return new ServiceInstantiation(mock(ModelInfo.class), null, null, null, null, null, null, null, null, null, null, null, null, null, null, + convertToMap(vnfs), + convertToMap(networks), + convertToMap(vnfGroups), + null, + null, false, 1, false,false,null, null, null, null, null, null, null); + } + + public static ServiceInstantiation createServiceWith2InstancesInEachLevel(Action action) { + return createService( + ImmutableList.of( + createVnf(ImmutableList.of(createVfModule(action), createVfModule(action)), action), + createVnf(ImmutableList.of(createVfModule(action), createVfModule(action)), action)), + ImmutableList.of( + createNetwork(action), + createNetwork(action)), + ImmutableList.of( + createGroup(ImmutableList.of(createMember(action), createMember(action)), action), + createGroup(ImmutableList.of(createMember(action), createMember(action)), action)) + ); + } + + static InstanceGroup createGroup(List groupMembers, Action action) { + return new InstanceGroup(mock(ModelInfo.class), null, action.name(), false, null, convertToMap(groupMembers), null, null, null); + } + + static InstanceGroupMember createMember(Action action) { + return new InstanceGroupMember(null, action.toString(), null, null, null); + } + + static Vnf createVnf(List vfModules, Action action) { + Map> vfModulesMap = new HashMap<>(); + vfModulesMap.put("abc",convertToMap(vfModules)); + + return new Vnf(mock(ModelInfo.class), null, null, action.toString(), null, null, null, null, null, null, false, null, vfModulesMap, null, null, null); + } + + static Vnf createVnf(Action action) { + return new Vnf(mock(ModelInfo.class), null, null, action.toString(), null, null, null, null, null, null, false, null,null, null, null, null); + } + + static VfModule createVfModule(Action action) { + return new VfModule(mock(ModelInfo.class), null, null, action.toString(), null, null, null, null, null, false, false, null, null, null, null); + } + + static Network createNetwork(Action action) { + return new Network(mock(ModelInfo.class), null, null, action.toString(), null, null, null, null, null, null, false, null, null, null, null); + } + } + + @DataProvider + public static Object[][] testIsDescendantHasActionDataProvider() { + return new Object[][]{ + {"empty service", Create, false, createService(emptyList(), emptyList(), emptyList())}, + {"instance group with None", Create, false, createService(emptyList(), emptyList(), ImmutableList.of(createGroup(emptyList(), None)))}, + {"instance group with Create", Create, true, createService(emptyList(), emptyList(), ImmutableList.of(createGroup(emptyList(), Create)))}, + {"instance group None + member Delete", Delete, true, createService(emptyList(), emptyList(), ImmutableList.of(createGroup(ImmutableList.of(createMember(Delete)), None)))}, + {"instance group None + member Create", Delete, false, createService(emptyList(), emptyList(), ImmutableList.of(createGroup(ImmutableList.of(createMember(Create)), None)))}, + {"instance group None + member Create + member Delete", Delete, true, + createService(emptyList(), emptyList(), ImmutableList.of(createGroup(ImmutableList.of(createMember(Create), createMember(Delete)), None)))}, + {"vnf Create", Delete, false, createService(ImmutableList.of(createVnf(emptyList(), Create)), emptyList(),emptyList())}, + {"vnf Create", Create, true, createService(ImmutableList.of(createVnf(emptyList(), Create)), emptyList(),emptyList())}, + {"vnf Create null VfModules internal map", Create, false, createService(ImmutableList.of(createVnf(null, Delete)), emptyList(),emptyList())}, + {"vnf Delete with null VfModules", Create, false, createService(ImmutableList.of(createVnf(Delete)), emptyList(),emptyList())}, + {"vnf None + VfModule Create", Create, true, createService(ImmutableList.of(createVnf(ImmutableList.of(createVfModule(Create)), None)), emptyList(),emptyList())}, + {"vnf None + VfModule None", Create, false, createService(ImmutableList.of(createVnf(ImmutableList.of(createVfModule(None)), None)), emptyList(),emptyList())}, + {"network Create", Create, true, createService(emptyList(), ImmutableList.of(createNetwork(Create)), emptyList())}, + {"network Delete", Create, false, createService(emptyList(), ImmutableList.of(createNetwork(Delete)), emptyList())}, + }; + } + + @Test(dataProvider = "testIsDescendantHasActionDataProvider") + public void testIsDescendantHasAction(String desc, Action action, boolean expectedResult, BaseResource request) { + //in this test, there is no meaning to constructor parameters + MockCommand underTest = new MockCommand(InternalState.WATCHING, Delete, Job.JobStatus.COMPLETED); + assertEquals(expectedResult, underTest.isDescendantHasAction(request, action)); + } + @DataProvider public static Object[][] testCallDataProvider() { return new Object[][]{ @@ -235,7 +354,7 @@ public class ResourceCommandTest { String description, InternalState internalState, Job.JobStatus currentStateResult, InternalState expectedNextState, Job.JobStatus expectedNextStatus) { - MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(internalState, Action.Delete, currentStateResult, true); + MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(internalState, Delete, currentStateResult, true); NextCommand nextCommand = underTest.call(); assertEquals(expectedNextStatus, nextCommand.getStatus()); @@ -250,12 +369,6 @@ public class ResourceCommandTest { } } - @Test(expectedExceptions = IllegalStateException.class) - public void whenCommandInUnMappedState_exceptionIsThrown() { - MockCommandTestingStateMachine underTest = new MockCommandTestingStateMachine(InternalState.TERMINAL, Action.Delete, Job.JobStatus.COMPLETED, true); - underTest.call(); - } - @DataProvider public static Object[][] InProgressDataProvider() { return Stream.of(Job.JobStatus.values()) @@ -266,7 +379,7 @@ public class ResourceCommandTest { @Test(dataProvider = "InProgressDataProvider") public void whenGetResultFromMso_InProgressReturnThem(Job.JobStatus mockedJobStatus) { Job.JobStatus expectedJobStatus = (mockedJobStatus== Job.JobStatus.PAUSE) ? Job.JobStatus.IN_PROGRESS : mockedJobStatus; - MockCommand underTest = new MockCommand(InternalState.IN_PROGRESS, Action.Delete, mockedJobStatus); + MockCommand underTest = new MockCommand(InternalState.IN_PROGRESS, Delete, mockedJobStatus); when(underTest.getInProgressStatusService().call(any(), any(), any())).thenReturn(mockedJobStatus); assertEquals(expectedJobStatus, underTest.inProgress()); } @@ -282,22 +395,22 @@ public class ResourceCommandTest { @Test(dataProvider = "InProgressExceptionsDataProvider") public void whenInProgressStatusServiceThrowException_InProgressReturnStatus(Exception exception, Job.JobStatus expectedJobStatus) { - MockCommand underTest = new MockCommand(InternalState.IN_PROGRESS, Action.Delete, expectedJobStatus); + MockCommand underTest = new MockCommand(InternalState.IN_PROGRESS, Delete, expectedJobStatus); when(underTest.getInProgressStatusService().call(any(), any(), any())).thenThrow(exception); assertEquals(expectedJobStatus, underTest.inProgress()); } @DataProvider public static Object[][] testIsNeedToDeleteMySelfDataProvider() { - return Stream.of(Action.values()) + return Stream.of(values()) .map(status -> new Object[] { status }) .toArray(Object[][]::new); } @Test(dataProvider = "testIsNeedToDeleteMySelfDataProvider") public void testIsNeedToDeleteMySelf(Action action) { - boolean expectedResult = (action== Action.Delete); - MockCommand underTest = new MockCommand(InternalState.DELETE_MYSELF, Action.Delete, Job.JobStatus.IN_PROGRESS); + boolean expectedResult = (action== Delete); + MockCommand underTest = new MockCommand(InternalState.DELETE_MYSELF, Delete, Job.JobStatus.IN_PROGRESS); BaseResource mockedBaseResource = mock(BaseResource.class); when(underTest.getSharedData().getRequest()).thenReturn(mockedBaseResource); when(mockedBaseResource.getAction()).thenReturn(action); @@ -315,9 +428,74 @@ public class ResourceCommandTest { @Test(dataProvider = "testWatchingDataProvider") public void testWatching(String desc, Job.JobStatus childrenJobsStatus, Job.JobStatus expectedJobStatus) { - MockCommand underTest = new MockCommand(InternalState.WATCHING, Action.Delete, Job.JobStatus.IN_PROGRESS); + MockCommand underTest = new MockCommand(InternalState.WATCHING, Delete, Job.JobStatus.IN_PROGRESS); when(underTest.getWatchChildrenJobsBL().retrieveChildrenJobsStatus(any())).thenReturn(childrenJobsStatus); assertEquals(expectedJobStatus, underTest.watchChildren()); } + @DataProvider + public static Object[][] testCalcInitialStateDataProvider() { + return new Object[][]{ + {Delete, true, Delete, InternalState.CREATING_CHILDREN}, + {Delete, false, Delete, InternalState.DELETE_MYSELF}, + {Delete, false, Create, InternalState.TERMINAL}, + {Delete, true, Create, InternalState.CREATING_CHILDREN}, + {Create, true, Create, InternalState.CREATE_MYSELF}, + {Create, false, Create, InternalState.CREATE_MYSELF}, + {Create, false, Delete, InternalState.TERMINAL}, + {Create, true, Delete, InternalState.CREATING_CHILDREN}, + {Create, true, Resume, InternalState.RESUME_MYSELF}, + {Delete, false, Resume, InternalState.TERMINAL}, + }; + } + + @Test(dataProvider = "testCalcInitialStateDataProvider") + public void testCalcInitialState(Action phase, boolean isDescendantHasAction, Action action, InternalState expectedState) { + ResourceCommand underTest = mock(ResourceCommand.class); + when(underTest.calcInitialState(any(), any())).thenCallRealMethod(); + when(underTest.isDescendantHasAction(eq(phase))).thenReturn(isDescendantHasAction); + when(underTest.getActionType()).thenReturn(action); + when(underTest.isNeedToDeleteMyself()).thenCallRealMethod(); + when(underTest.isNeedToCreateMyself()).thenCallRealMethod(); + when(underTest.isNeedToResumeMySelf()).thenCallRealMethod(); + + Map commandData = ImmutableMap.of(INTERNAL_STATE, InternalState.INITIAL.name()); + assertEquals(expectedState, underTest.calcInitialState(commandData, phase)); + } + + + //throw exception when call to create children + //create children is just example, it could be any other method that called by ResourceCommand.invokeCommand + public static class MockCommandThrowExceptionOnCreateChildren extends MockCommandTestingStateMachine { + + private final RuntimeException exceptionToThrow; + + public MockCommandThrowExceptionOnCreateChildren(RuntimeException exceptionToThrow) { + super(InternalState.CREATING_CHILDREN, Delete, Job.JobStatus.COMPLETED, true); + this.exceptionToThrow = exceptionToThrow; + doAnswer(returnsFirstArg()).when(this.getWatchChildrenJobsBL()).cumulateJobStatus(any(), any()); + } + + @NotNull + @Override + public Job.JobStatus createChildren() { + throw exceptionToThrow; + } + } + + @DataProvider + public static Object[][] exceptionAndStateProvider() { + return new Object[][]{ + {new TryAgainException(new Exception()), Job.JobStatus.RESOURCE_IN_PROGRESS}, + {new AbortingException(new Exception()), Job.JobStatus.FAILED}, + }; + } + + @Test(dataProvider = "exceptionAndStateProvider") + public void whenKnownExceptionThrownInCommandInvocation_thenStateIsAsExpected(RuntimeException exception, Job.JobStatus expectedNextStatus) { + MockCommandTestingStateMachine underTest = new MockCommandThrowExceptionOnCreateChildren(exception); + NextCommand nextCommand = underTest.call(); + assertEquals(expectedNextStatus, nextCommand.getStatus()); + } + } diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceInProgressStatusCommandTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceInProgressStatusCommandTest.java deleted file mode 100644 index 5b036f587..000000000 --- a/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceInProgressStatusCommandTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.vid.job.command; - -import org.mockito.InjectMocks; -import org.mockito.MockitoAnnotations; -import org.onap.vid.job.Job; -import org.onap.vid.job.NextCommand; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.Is.is; - - -public class ResourceInProgressStatusCommandTest { - - @InjectMocks - private ResourceInProgressStatusCommand commandUnderTest = new ResourceInProgressStatusCommand(); - - @BeforeMethod - public void initMocks() { - MockitoAnnotations.initMocks(this); - } - - @DataProvider - public static Object[][] givenStatusToExpectedStatus() { - return new Object[][]{ - {Job.JobStatus.IN_PROGRESS, Job.JobStatus.IN_PROGRESS}, - {Job.JobStatus.FAILED, Job.JobStatus.FAILED}, - {Job.JobStatus.COMPLETED, Job.JobStatus.COMPLETED} - }; - } - - @Test(dataProvider = "givenStatusToExpectedStatus") - public void whenGetStatusFromMso_returnExpectedNextCommand(Job.JobStatus jobStatus, Job.JobStatus expectedNextStatus) { - NextCommand nextCommand = commandUnderTest.processJobStatus(jobStatus); - assertThat(nextCommand.getStatus(), is(expectedNextStatus)); - assertThat(nextCommand.getCommand(), is(commandUnderTest)); - } -} diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/ServiceInProgressStatusCommandTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/ServiceInProgressStatusCommandTest.java index 31dbc9f6d..787ff608d 100644 --- a/vid-app-common/src/test/java/org/onap/vid/job/command/ServiceInProgressStatusCommandTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/ServiceInProgressStatusCommandTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,22 +20,22 @@ package org.onap.vid.job.command; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.mockito.ArgumentCaptor; -import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.onap.portalsdk.core.util.SystemProperties; import org.onap.vid.job.*; import org.onap.vid.job.impl.JobSharedData; +import org.onap.vid.model.Action; import org.onap.vid.model.serviceInstantiation.Network; import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; import org.onap.vid.model.serviceInstantiation.Vnf; -import org.onap.vid.mso.model.ModelInfo; +import org.onap.vid.mso.RestMsoImplementation; import org.onap.vid.properties.Features; import org.onap.vid.properties.VidProperties; import org.onap.vid.services.AsyncInstantiationBusinessLogic; -import org.springframework.core.env.Environment; +import org.onap.vid.services.AuditService; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; @@ -47,10 +47,9 @@ import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.temporal.ChronoUnit; import java.util.Arrays; -import java.util.Map; -import java.util.TreeMap; import java.util.UUID; +import static java.util.Collections.emptyList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.core.Is.is; @@ -58,7 +57,11 @@ import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.*; import static org.onap.vid.job.Job.JobStatus.*; +import static org.onap.vid.job.command.ResourceCommandKt.*; +import static org.onap.vid.job.command.ResourceCommandTest.FakeResourceCreator.*; +import static org.onap.vid.model.Action.Create; import static org.onap.vid.testUtils.TestUtils.testWithSystemProperty; +import static org.testng.AssertJUnit.assertEquals; public class ServiceInProgressStatusCommandTest { @@ -78,45 +81,29 @@ public class ServiceInProgressStatusCommandTest { @Mock private JobSharedData sharedData; - @Mock - private Environment environment; - @Mock private ServiceInstantiation request; @Mock private InProgressStatusService inProgressStatusService; - @InjectMocks - private ServiceInProgressStatusCommand command = new ServiceInProgressStatusCommand(); + @Mock + private WatchChildrenJobsBL watchChildrenJobsBL; - @DataProvider - public static Object[][] isNeedToCreateChildJobsDataProvider() { - return new Object[][]{ - {new TreeMap() , true, true, false}, - {null , true, true, false}, - {ImmutableMap.of("a",mock(Vnf.class)), false, true, false}, - {ImmutableMap.of("a",mock(Vnf.class)), true, false, false}, - {ImmutableMap.of("a",mock(Vnf.class)), true, true, true}, - }; - } + @Mock + private MsoResultHandlerService msoResultHandlerService; + + @Mock + private MsoRequestBuilder msoRequestBuilder; + + @Mock + private RestMsoImplementation restMsoImplementation; + + @Mock + private AuditService auditService; + + private ALaCarteServiceCommand command; - @DataProvider - public static Object[][] processJobStatusData() { - return new Object[][]{ - /* {MSO jobStatus, jobStartTime, isNeedToCreateChildJobs(), property vid.job.max.hoursInProgress, expected nextCommand.getStatus() } */ - {IN_PROGRESS, false, IN_PROGRESS}, - {FAILED, false, FAILED}, - {PAUSE, false, IN_PROGRESS}, - {COMPLETED, false, COMPLETED}, - {COMPLETED, true, IN_PROGRESS}, - {RESOURCE_IN_PROGRESS, false, RESOURCE_IN_PROGRESS}, - {PENDING, false, PENDING}, - {STOPPED, false, STOPPED}, - {COMPLETED_WITH_ERRORS, false, COMPLETED_WITH_ERRORS}, - {CREATING, false, CREATING} - }; - } @DataProvider public static Object[][] isExpiredJobStatusData() { @@ -138,32 +125,31 @@ public class ServiceInProgressStatusCommandTest { @BeforeMethod public void initMocks() { MockitoAnnotations.initMocks(this); - } - - @Test(dataProvider = "isNeedToCreateChildJobsDataProvider" ) - public void testIsNeedToCreateChildJobs(Map serviceVnfs, boolean isALaCarte, - boolean isFeatureEnabled, boolean expected) { - MockitoAnnotations.initMocks(this); - ServiceInstantiation serviceInstantiation = mock(ServiceInstantiation.class); - when(serviceInstantiation.getVnfs()).thenReturn(serviceVnfs); - when(serviceInstantiation.isALaCarte()).thenReturn(isALaCarte); - when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(isFeatureEnabled); - assertThat(command.isNeedToCreateChildJobs(serviceInstantiation), is(expected)); + command = new ALaCarteServiceCommand( + inProgressStatusService, + watchChildrenJobsBL, + asyncInstantiationBL, + jobsBrokerService, + msoRequestBuilder, + msoResultHandlerService, + jobAdapter, + restMsoImplementation, + auditService + ); } @Test public void whenGetFromMsoCompletedAndALaCarte_generateNewJobsForVnfs() { UUID uuid = UUID.randomUUID(); String userId = "mockedUserID"; - Vnf vnf1 = mock(Vnf.class); - Vnf vnf2 = mock(Vnf.class); - Network network1 = mock(Network.class); - ServiceInstantiation serviceInstantiation = mock(ServiceInstantiation.class); - when(serviceInstantiation.getVnfs()).thenReturn(ImmutableMap.of("a", vnf1, "b", vnf2)); - when(serviceInstantiation.getNetworks()).thenReturn(ImmutableMap.of("c", network1)); - when(serviceInstantiation.isALaCarte()).thenReturn(true); - when(serviceInstantiation.getModelInfo()).thenReturn(new ModelInfo()); - + String testApi = "VNF_API"; + Vnf vnf1 = createVnf(emptyList(), Create); + Vnf vnf2 = createVnf(emptyList(), Create); + Network network = createNetwork(Create); + ServiceInstantiation serviceInstantiation = createService( + ImmutableList.of(vnf1, vnf2), + ImmutableList.of(network), + emptyList()); when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(true); UUID uuid1 = UUID.fromString("12345678-1234-1234-1234-123456789012"); @@ -171,15 +157,25 @@ public class ServiceInProgressStatusCommandTest { UUID uuid3 = UUID.fromString("12345678-1234-1234-1234-123456789014"); when(jobsBrokerService.add(any())).thenReturn(uuid1).thenReturn(uuid2).thenReturn(uuid3); - JobSharedData sharedData = new JobSharedData(uuid, userId, serviceInstantiation); - command.init(sharedData, "", ""); + JobSharedData sharedData = new JobSharedData(uuid, userId, serviceInstantiation, testApi); + command.init(sharedData, ImmutableMap.of( + ACTION_PHASE, Action.Create.name(), + INTERNAL_STATE, InternalState.IN_PROGRESS.name() + )); when(inProgressStatusService.call(any(), eq(sharedData), any())).thenReturn(Job.JobStatus.COMPLETED); + when(watchChildrenJobsBL.cumulateJobStatus(Job.JobStatus.COMPLETED, COMPLETED_WITH_NO_ACTION)).thenReturn(COMPLETED); + when(watchChildrenJobsBL.cumulateJobStatus(Job.JobStatus.COMPLETED_WITH_NO_ACTION, COMPLETED)).thenReturn(COMPLETED); + when(msoResultHandlerService.getRequest(eq(sharedData))).thenReturn(serviceInstantiation); NextCommand nextCommand = command.call(); + assertEquals(IN_PROGRESS, nextCommand.getStatus()); + nextCommand = nextCommand.getCommand().call(); ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(JobAdapter.AsyncJobRequest.class); - verify(jobAdapter, times(2)).createChildJob(eq(JobType.VnfInstantiation), eq(Job.JobStatus.CREATING), argumentCaptor.capture(), eq(sharedData), any()); - verify(jobAdapter, times(1)).createChildJob(eq(JobType.NetworkInstantiation), eq(Job.JobStatus.CREATING), argumentCaptor.capture(), eq(sharedData), any()); - assertThat(argumentCaptor.getAllValues(), containsInAnyOrder(vnf1, vnf2, network1)); + verify(jobAdapter, times(1)).createChildJob(eq(JobType.NetworkInstantiation), argumentCaptor.capture(), eq(sharedData), any(), eq(0)); + verify(jobAdapter, times(1)).createChildJob(eq(JobType.VnfInstantiation), argumentCaptor.capture(), eq(sharedData), any(), eq(1)); + verify(jobAdapter, times(1)).createChildJob(eq(JobType.VnfInstantiation), argumentCaptor.capture(), eq(sharedData), any(), eq(2)); + + assertThat(argumentCaptor.getAllValues(), containsInAnyOrder(vnf1, vnf2, network)); verify(jobsBrokerService, times(3)).add(any()); @@ -187,41 +183,14 @@ public class ServiceInProgressStatusCommandTest { verify(asyncInstantiationBL, never()).updateServiceInfo(any(), any()); assertThat(nextCommand.getStatus(), is(Job.JobStatus.IN_PROGRESS)); - assertThat(nextCommand.getCommand().getType(), is(new WatchingCommand().getType())); - assertThat(nextCommand.getCommand().getData().get("childrenJobs"), is(Arrays.asList(uuid1.toString(), uuid2.toString(), uuid3.toString()))); - assertThat(nextCommand.getCommand().getData().get("isService"), is(true)); - } - - @Test(dataProvider = "processJobStatusData") - public void processJobStatusTest(Job.JobStatus jobStatus, boolean isNeedToCreateChildJobs, Job.JobStatus expectedStatus) { - - when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(true); - // All mocks under are used for isNeedToCreateChildJobs=true case - when(sharedData.getRequest()).thenReturn(request); - when(request.isALaCarte()).thenReturn(true); - Map vnfs = mock(Map.class); - ModelInfo modelInfo = mock(ModelInfo.class); - - // if vnfs.isEmpty -> isNeedToCreateChildJobs will return false - when(vnfs.isEmpty()).thenReturn(!isNeedToCreateChildJobs); - - when(request.getVnfs()).thenReturn(vnfs); - when(request.getModelInfo()).thenReturn(modelInfo); - command.instanceId = "MockInstId"; - - NextCommand nextCommand = command.processJobStatus(jobStatus); - Assert.assertEquals(nextCommand.getStatus(), expectedStatus); - if (isNeedToCreateChildJobs) { - Assert.assertEquals(nextCommand.getCommand().getClass(), WatchingCommand.class); - } else { - Assert.assertEquals(nextCommand.getCommand(), command); - } + assertThat(nextCommand.getCommand().getType(), is(JobType.ALaCarteService)); + assertThat(nextCommand.getCommand().getData().get(CHILD_JOBS), is(Arrays.asList(uuid1.toString(), uuid2.toString(), uuid3.toString()))); } @Test(dataProvider = "isExpiredJobStatusData") public void isExpiredJobStatusTest(ZonedDateTime jobStartTime, String configValue, boolean expectedResult) throws Exception { testWithSystemProperty(VidProperties.VID_JOB_MAX_HOURS_IN_PROGRESS, configValue, ()-> - Assert.assertEquals(command.getExpiryChecker().isExpired(jobStartTime), expectedResult) + Assert.assertEquals(command.getExpiryChecker().isExpired(jobStartTime), expectedResult) ); } } diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/WatchChildrenJobsBLTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/WatchChildrenJobsBLTest.java index 630c46438..a9a961db8 100644 --- a/vid-app-common/src/test/java/org/onap/vid/job/command/WatchChildrenJobsBLTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/job/command/WatchChildrenJobsBLTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -23,10 +23,10 @@ package org.onap.vid.job.command; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.onap.portalsdk.core.service.DataAccessService; import org.onap.vid.job.Job.JobStatus; import org.onap.vid.job.impl.JobDaoImpl; import org.onap.vid.utils.DaoUtils; +import org.onap.portalsdk.core.service.DataAccessService; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/WatchingCommandTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/WatchingCommandTest.java deleted file mode 100644 index cc0e66007..000000000 --- a/vid-app-common/src/test/java/org/onap/vid/job/command/WatchingCommandTest.java +++ /dev/null @@ -1,97 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.vid.job.command; - -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.onap.portalsdk.core.service.DataAccessService; -import org.onap.vid.job.Job; -import org.onap.vid.job.NextCommand; -import org.onap.vid.job.impl.JobSharedData; -import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; -import org.onap.vid.services.AsyncInstantiationBusinessLogic; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; - -import java.util.List; -import java.util.UUID; - -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.Is.is; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.*; - -public class WatchingCommandTest { - - @Mock - private AsyncInstantiationBusinessLogic asyncInstantiationBL; - - @Mock - private DataAccessService dataAccessService; - - @Mock - private WatchChildrenJobsBL watchChildrenJobsBL; - - @InjectMocks - private WatchingCommand watchingCommand = new WatchingCommand(); - - - - @BeforeClass - public void initMocks() { - MockitoAnnotations.initMocks(this); - } - - @DataProvider - public static Object[][] testWatchingDataProvider() { - return new Object[][]{ - {"all children final, no failed child, is service", Job.JobStatus.COMPLETED, true, Job.JobStatus.COMPLETED}, - {"all children final, there is failed child, is service", Job.JobStatus.COMPLETED_WITH_ERRORS, true, Job.JobStatus.COMPLETED_WITH_ERRORS}, - {"not all children final, is service", Job.JobStatus.IN_PROGRESS, true, Job.JobStatus.IN_PROGRESS}, - {"all children final, no failed child, not service", Job.JobStatus.COMPLETED, false, Job.JobStatus.COMPLETED}, - {"all children final, there is failed child, not service", Job.JobStatus.COMPLETED_WITH_ERRORS, false, Job.JobStatus.COMPLETED_WITH_ERRORS}, - {"not all children final, not service", Job.JobStatus.IN_PROGRESS, false, Job.JobStatus.RESOURCE_IN_PROGRESS}, - }; - } - - - - @Test(dataProvider = "testWatchingDataProvider") - public void whenGetChildrenStatus_thenJobStatusAsExpected(String desc, Job.JobStatus childrenComulativeStatus, boolean isService, Job.JobStatus expectedCommandStatus) { - UUID jobUUID = UUID.randomUUID(); - JobSharedData sharedData = new JobSharedData(jobUUID, "mockedUserID", mock(ServiceInstantiation.class)); - List uuids = mock(List.class); - watchingCommand.init(sharedData, uuids, isService); - when(watchChildrenJobsBL.retrieveChildrenJobsStatus(eq(uuids))).thenReturn(childrenComulativeStatus); - when(watchChildrenJobsBL.cumulateJobStatus(eq(childrenComulativeStatus),eq(Job.JobStatus.COMPLETED))).thenReturn(childrenComulativeStatus); - - //execute command and verify - NextCommand nextCommand = watchingCommand.call(); - assertThat(nextCommand.getStatus(), is(expectedCommandStatus)); - if (!expectedCommandStatus.equals(Job.JobStatus.IN_PROGRESS) && isService) { - verify(asyncInstantiationBL).updateServiceInfoAndAuditStatus(jobUUID, expectedCommandStatus); - } else { - verify(asyncInstantiationBL, never()).updateServiceInfoAndAuditStatus(jobUUID, expectedCommandStatus); - } - } -} diff --git a/vid-app-common/src/test/java/org/onap/vid/job/impl/AsyncInstantiationIntegrationTest.java b/vid-app-common/src/test/java/org/onap/vid/job/impl/AsyncInstantiationIntegrationTest.java index 0b1fff3b2..498708d06 100644 --- a/vid-app-common/src/test/java/org/onap/vid/job/impl/AsyncInstantiationIntegrationTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/job/impl/AsyncInstantiationIntegrationTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,43 +20,55 @@ package org.onap.vid.job.impl; +import com.fasterxml.jackson.databind.JsonNode; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.mutable.MutableInt; +import org.jetbrains.annotations.NotNull; +import org.mockito.ArgumentCaptor; import org.mockito.Mockito; +import org.mockito.hamcrest.MockitoHamcrest; import org.onap.portalsdk.core.service.DataAccessService; import org.onap.portalsdk.core.util.SystemProperties; import org.onap.vid.asdc.AsdcCatalogException; -import org.onap.vid.config.DataSourceConfig; -import org.onap.vid.config.JobCommandsConfigWithMockedMso; -import org.onap.vid.config.MockedAaiClientAndFeatureManagerConfig; +import org.onap.vid.changeManagement.RequestDetailsWrapper; 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.Action; -import org.onap.vid.model.NameCounter; -import org.onap.vid.model.RequestReferencesContainer; -import org.onap.vid.model.ServiceInfo; +import org.onap.vid.model.*; +import org.onap.vid.model.serviceInstantiation.BaseResource; +import org.onap.vid.model.serviceInstantiation.InstanceGroup; import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; import org.onap.vid.mso.RestMsoImplementation; import org.onap.vid.mso.RestObject; 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.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.springframework.http.HttpMethod; import org.springframework.test.context.ContextConfiguration; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; 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; @@ -66,7 +78,8 @@ import java.util.stream.IntStream; import java.util.stream.Stream; import static java.util.stream.Collectors.*; -import static net.javacrumbs.jsonunit.JsonMatchers.jsonPartEquals; +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; @@ -77,7 +90,7 @@ 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.model.JobAuditStatus.SourceStatus.MSO; +import static org.onap.vid.job.impl.JobSchedulerInitializer.WORKERS_TOPICS; import static org.onap.vid.model.JobAuditStatus.SourceStatus.VID; import static org.testng.AssertJUnit.*; @@ -96,6 +109,9 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes public static String REQUEST_ID = UUID.randomUUID().toString(); public static String SERVICE_INSTANCE_ID = UUID.randomUUID().toString(); + @Inject + private VersionService versionService; + @Inject private JobsBrokerService jobsBrokerService; @@ -108,6 +124,9 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes @Inject private AsyncInstantiationBusinessLogic asyncInstantiationBL; + @Inject + private AuditService auditService; + @Inject private RestMsoImplementation restMso; @@ -120,6 +139,7 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes @BeforeClass void initServicesInfoService() { createInstanceParamsMaps(); + when(versionService.retrieveBuildNumber()).thenReturn("fakeBuild"); } @BeforeMethod @@ -131,10 +151,12 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes @BeforeMethod void defineMocks() { + Mockito.reset(restMso); + Mockito.reset(aaiClient); mockAaiClientAnyNameFree(); } - //@Test + @Test public void whenPushNewBulk_thenAllServicesAreInPending() { pushMacroBulk(); @@ -144,8 +166,8 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes private List pushMacroBulk() { ServiceInstantiation serviceInstantiation = generateMockMacroServiceInstantiationPayload(false, - createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true), - 3, true,PROJECT_NAME, true); + createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true), + 3, true,PROJECT_NAME, true); return asyncInstantiationBL.pushBulkJob(serviceInstantiation, USER_ID); } @@ -167,6 +189,10 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes return createResponse(statusCode, SERVICE_INSTANCE_ID, REQUEST_ID); } + public static RestObject createResponseRandomIds(int statusCode) { + return createResponse(statusCode, UUID.randomUUID().toString(), UUID.randomUUID().toString()); + } + public static RestObject createResponse(int statusCode, String instanceId, String requestId) { RequestReferences requestReferences = new RequestReferences(); requestReferences.setRequestId(requestId); @@ -180,7 +206,7 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes ImmutableList statusesToStrings(JobStatus... jobStatuses) { return Stream.of(jobStatuses).map( - Enum::toString).collect(ImmutableList.toImmutableList()); + Enum::toString).collect(ImmutableList.toImmutableList()); } /* @@ -190,81 +216,85 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes Make sure service state is Completed successfully once we got from MSO complete, and that next job is peeked. Once a service in the bulk is failed, other services moved to Stopped, and no other jobs from the bulk are peeked. */ - //@Test + @Test public void testStatusesOfMacroServiceInBulkDuringBulkLifeCycle() { - when(restMso.PostForObject(any(), any(), eq(RequestReferencesContainer.class))).thenReturn(createResponse(200)); + + final String SERVICE_REQUEST_ID = UUID.randomUUID().toString(); + final String SERVICE_INSTANCE_ID = UUID.randomUUID().toString(); + final String SERVICE2_REQUEST_ID = UUID.randomUUID().toString(); + final String SERVICE2_INSTANCE_ID = UUID.randomUUID().toString(); + + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), any(), eq(Optional.empty()))) + .thenReturn(createResponse(200, SERVICE_INSTANCE_ID, SERVICE_REQUEST_ID)); + ImmutableList> expectedStatusesForVid = ImmutableList.of( - statusesToStrings(PENDING, IN_PROGRESS, COMPLETED), - statusesToStrings(PENDING, IN_PROGRESS, FAILED), - statusesToStrings(PENDING, STOPPED) + statusesToStrings(PENDING, IN_PROGRESS, COMPLETED), + statusesToStrings(PENDING, IN_PROGRESS, FAILED), + statusesToStrings(PENDING, STOPPED) ); ImmutableList> expectedStatusesForMso = ImmutableList.of( - ImmutableList.of(REQUESTED, IN_PROGRESS_STR, "not a state", FAILED_STR ,COMPLETE_STR), - ImmutableList.of(REQUESTED, FAILED_STR), - ImmutableList.of() + ImmutableList.of(REQUESTED, IN_PROGRESS_STR, "not a state", FAILED_STR ,COMPLETE_STR), + ImmutableList.of(REQUESTED, FAILED_STR), + ImmutableList.of() ); List uuids = pushMacroBulk(); - pullPendingJobAndAssertJobStatus(JobStatus.IN_PROGRESS, PENDING); - + UUID firstJobUuid = uuids.get(0); + UUID secondJobUuid = uuids.get(1); //assert that when get ProcessingException from restMso, status remain the same - when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))).thenThrow(new ProcessingException("fake message")); - Job job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS); - UUID firstHandledJobUUID = job.getUuid(); - listServicesAndAssertStatus(JobStatus.IN_PROGRESS, PENDING, job); + when(restMso.GetForObject(endsWith(SERVICE_REQUEST_ID), eq(AsyncRequestStatus.class))).thenThrow(new ProcessingException("fake message")); + processJobsCountTimesAndAssertStatus(firstJobUuid, 10, IN_PROGRESS, PENDING); //assert that when get IN_PROGRESS status from restMso, status remain IN_PROGRESS - when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))).thenReturn(asyncRequestStatusResponseAsRestObject(IN_PROGRESS_STR)); - job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS); - listServicesAndAssertStatus(JobStatus.IN_PROGRESS, PENDING, job); + when(restMso.GetForObject(endsWith(SERVICE_REQUEST_ID), eq(AsyncRequestStatus.class))).thenReturn(asyncRequestStatusResponseAsRestObject(IN_PROGRESS_STR)); + processJobsCountTimesAndAssertStatus(firstJobUuid, 10, IN_PROGRESS, PENDING); //assert that when get unrecognized status from restMso, status remain IN_PROGRESS - when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))).thenReturn(asyncRequestStatusResponseAsRestObject("not a state")); - job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS); - listServicesAndAssertStatus(JobStatus.IN_PROGRESS, PENDING, job); + when(restMso.GetForObject(endsWith(SERVICE_REQUEST_ID), eq(AsyncRequestStatus.class))).thenReturn(asyncRequestStatusResponseAsRestObject("not a state")); + processJobsCountTimesAndAssertStatus(firstJobUuid, 10, IN_PROGRESS, PENDING); //assert that when get non 200 status code during IN_PROGRESS, status remain IN_PROGRESS - when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))).thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR, 404)); - job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS); - listServicesAndAssertStatus(JobStatus.IN_PROGRESS, PENDING, job); + when(restMso.GetForObject(endsWith(SERVICE_REQUEST_ID), eq(AsyncRequestStatus.class))).thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR, 404)); + processJobsCountTimesAndAssertStatus(firstJobUuid, 10, IN_PROGRESS, PENDING); //when get job COMPLETE from MSO, service status become COMPLETED - when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))). - thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); - job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, COMPLETED); - List serviceInfoList = listServicesAndAssertStatus(COMPLETED, PENDING, job); - - + when(restMso.GetForObject(endsWith(SERVICE_REQUEST_ID), eq(AsyncRequestStatus.class))).thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, COMPLETED); + List serviceInfoList = listServicesAndAssertStatus(COMPLETED, PENDING, firstJobUuid); + + //for use later in the test Map expectedJobStatusMap = serviceInfoList.stream().collect( - Collectors.toMap(ServiceInfo::getJobId, x-> PENDING)); - expectedJobStatusMap.put(job.getUuid(), COMPLETED); + Collectors.toMap(ServiceInfo::getJobId, x-> PENDING)); + expectedJobStatusMap.put(firstJobUuid, COMPLETED); //when handling another PENDING job, statuses are : COMPLETED, IN_PROGRESS, PENDING - job = pullJobProcessAndPushBack(PENDING, JobStatus.IN_PROGRESS); - assertThat(job.getUuid(), not(equalTo(firstHandledJobUUID))); //assert different job was handled now - expectedJobStatusMap.put(job.getUuid(), JobStatus.IN_PROGRESS); + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), any(), eq(Optional.empty()))) + .thenReturn(createResponse(200, SERVICE2_INSTANCE_ID, SERVICE2_REQUEST_ID)); + when(restMso.GetForObject(endsWith(SERVICE2_REQUEST_ID), eq(AsyncRequestStatus.class))).thenReturn(asyncRequestStatusResponseAsRestObject(IN_PROGRESS_STR)); + processJobsCountTimes(10); + + expectedJobStatusMap.put(secondJobUuid, JobStatus.IN_PROGRESS); listServicesAndAssertStatus(expectedJobStatusMap); + //when get FAILED status from MSO statuses are : COMPLETED, FAILED, STOPPED - when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))). - thenReturn(asyncRequestStatusResponseAsRestObject(FAILED_STR)); - job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.FAILED); - expectedJobStatusMap.put(job.getUuid(), JobStatus.FAILED); + when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))).thenReturn(asyncRequestStatusResponseAsRestObject(FAILED_STR)); + pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.FAILED); + expectedJobStatusMap.put(secondJobUuid, JobStatus.FAILED); expectedJobStatusMap = expectedJobStatusMap.entrySet().stream().collect(Collectors.toMap( - e -> e.getKey(), e -> e.getValue() == PENDING ? JobStatus.STOPPED : e.getValue() + e -> e.getKey(), e -> e.getValue() == PENDING ? JobStatus.STOPPED : e.getValue() )); listServicesAndAssertStatus(expectedJobStatusMap); IntStream.range(0, uuids.size()).forEach(i -> { UUID uuid = uuids.get(i); - List msoStatuses = asyncInstantiationBL.getAuditStatuses(uuid, MSO).stream().map(x -> x.getJobStatus()).collect(Collectors.toList()); - List vidStatuses = asyncInstantiationBL.getAuditStatuses(uuid, VID).stream().map(x -> x.getJobStatus()).collect(Collectors.toList()); - assertThat(msoStatuses, is(expectedStatusesForMso.get(i))); + List vidStatuses = auditService.getAuditStatuses(uuid, VID).stream().map(x -> x.getJobStatus()).collect(Collectors.toList()); assertThat(vidStatuses, is(expectedStatusesForVid.get(i))); }); - // + + //assert no more jobs to pull assertFalse(jobsBrokerService.pull(PENDING, randomUuid()).isPresent()); assertFalse(jobsBrokerService.pull(JobStatus.IN_PROGRESS, randomUuid()).isPresent()); } @@ -273,8 +303,8 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes @DataProvider public static Object[][] AlaCarteStatuses(Method test) { return new Object[][]{ - {COMPLETE_STR, JobStatus.COMPLETED, JobStatus.COMPLETED}, - {FAILED_STR, JobStatus.COMPLETED_WITH_ERRORS, JobStatus.FAILED}, + {COMPLETE_STR, JobStatus.COMPLETED}, + {FAILED_STR, JobStatus.COMPLETED_WITH_ERRORS}, }; } @@ -285,8 +315,8 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes Make sure service state is Completed successfully once we got from MSO complete for the vnf job. status Creating */ - //@Test(dataProvider = "AlaCarteStatuses") - public void testStatusesOfServiceDuringALaCarteLifeCycleIgnoringVfModules(String msoVnfStatus, JobStatus expectedServiceStatus, JobStatus expectedVnfStatus) { + @Test(dataProvider = "AlaCarteStatuses") + public void testStatusesOfServiceDuringALaCarteLifeCycleIgnoringVfModules(String msoVnfStatus, JobStatus expectedServiceStatus) { /* [v] + push alacarte with 1 vnf [v] verify STATUS pending @@ -305,6 +335,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); final String SERVICE_REQUEST_ID = UUID.randomUUID().toString(); @@ -315,39 +346,22 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes //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.PostForObject(any(), endsWith("serviceInstances"), eq(RequestReferencesContainer.class))).thenReturn( - createResponse(200, SERVICE_INSTANCE_ID, SERVICE_REQUEST_ID)); - pullJobProcessAndPushBackWithTypeAssertion(JobStatus.PENDING, JobStatus.IN_PROGRESS, JobType.InProgressStatus); - singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid); - + 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 COMPLETE for service instance create, job status shall remain IN_PROGRESS and type shall be Watching - reset(restMso); when(restMso.GetForObject(endsWith(SERVICE_REQUEST_ID), eq(AsyncRequestStatus.class))). - thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); - pullJobProcessAndPushBackWithTypeAssertion(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS, JobType.Watching); - singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid); - + thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); //mock mso to answer 200 of create vnf instance request, pull+execute vnf job, STATUS resource in progress - reset(restMso); - when(restMso.PostForObject(any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs"), eq(RequestReferencesContainer.class))).thenReturn( - createResponse(200, UUID.randomUUID().toString(), VNF_REQUEST_ID)); - pullJobProcessAndPushBackWithTypeAssertion(JobStatus.CREATING, JobStatus.RESOURCE_IN_PROGRESS, JobType.VnfInProgressStatus); - - //verify service job STATUS in progress - pullJobProcessAndPushBackWithTypeAssertion(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS, JobType.Watching); - singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid); - - //mock mso to answer msoVnfStatus (COMPLETE/FAILED) for vnf creation status, - //job status shall be final (COMPLETE/COMPLETE_WITH_ERRORS) - reset(restMso); + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs"), any())).thenReturn( + createResponse(200, UUID.randomUUID().toString(), VNF_REQUEST_ID)); when(restMso.GetForObject(endsWith(VNF_REQUEST_ID), eq(AsyncRequestStatus.class))).thenReturn( - asyncRequestStatusResponseAsRestObject(msoVnfStatus)); - pullJobProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, expectedVnfStatus, false); - singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid); - pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, expectedServiceStatus, true); - singleServicesAndAssertStatus(expectedServiceStatus, uuid); + asyncRequestStatusResponseAsRestObject(msoVnfStatus)); + + processJobsCountTimesAndAssertStatus(uuid, 100, expectedServiceStatus); + verify(restMso, times(1)).restCall(eq(HttpMethod.POST), any(), any(), eq("/serviceInstantiation/v7/serviceInstances"), any()); + verify(restMso, times(1)).restCall(eq(HttpMethod.POST), any(), any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs"), any()); + verify(restMso, times(2)).GetForObject(any(), any()); } @@ -361,13 +375,11 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes And union these tests to single one. */ - //@Test + @Test public void testALaCarteLifeCycle1Vnf2VfModules() { String msoVnfStatus = COMPLETE_STR; - JobStatus expectedServiceStatus = IN_PROGRESS; - JobStatus expectedVnfStatus = RESOURCE_IN_PROGRESS; 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(); @@ -383,39 +395,27 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes //push alacarte with 1 vnf, verify STATUS pending UUID uuid = pushALaCarteWithVnf(); singleServicesAndAssertStatus(JobStatus.PENDING, uuid); + reset(restMso); /*---------- service -----------*/ //mock mso to answer 200 of create service instance request, verify STATUS in progress - when(restMso.PostForObject(any(), endsWith("serviceInstances"), eq(RequestReferencesContainer.class))).thenReturn( - createResponse(200, SERVICE_INSTANCE_ID, SERVICE_REQUEST_ID)); - pullJobProcessAndPushBackWithTypeAssertion(JobStatus.PENDING, JobStatus.IN_PROGRESS, JobType.InProgressStatus); - singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid); + 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 COMPLETE for service instance create, job status shall remain IN_PROGRESS and type shall be Watching - reset(restMso); + //mock mso to answer COMPLETE for service instance create when(restMso.GetForObject(endsWith(SERVICE_REQUEST_ID), eq(AsyncRequestStatus.class))). - thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); - pullJobProcessAndPushBackWithTypeAssertion(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS, JobType.Watching); - singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid); + thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); /*---------- vnf -----------*/ - //mock mso to answer 200 of create vnf instance request, pull+execute vnf job, STATUS resource in progress - reset(restMso); - when(restMso.PostForObject(any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs"), eq(RequestReferencesContainer.class))).thenReturn( - createResponse(200, VNF_INSTANCE_ID, VNF_REQUEST_ID)); - pullJobProcessAndPushBackWithTypeAssertion(JobStatus.CREATING, JobStatus.RESOURCE_IN_PROGRESS, JobType.VnfInProgressStatus); - - //verify service job STATUS in progress - pullJobProcessAndPushBackWithTypeAssertion(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS, JobType.Watching); - singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid); + //mock mso to answer 200 of create vnf instance request + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs"), any())).thenReturn( + createResponse(200, VNF_INSTANCE_ID, VNF_REQUEST_ID)); //mock mso to answer msoVnfStatus (COMPLETE/FAILED) for vnf creation status, - //job status shall be final (COMPLETE/COMPLETE_WITH_ERRORS) - reset(restMso); when(restMso.GetForObject(endsWith(VNF_REQUEST_ID), eq(AsyncRequestStatus.class))). - thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); try { reset(commandUtils); @@ -425,113 +425,164 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes } - pullJobProcessAndPushBackWithTypeAssertion(JobStatus.RESOURCE_IN_PROGRESS, JobStatus.RESOURCE_IN_PROGRESS, JobType.WatchingBaseModule); - singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid); - pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS, true); - singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid); - /*---------- vf Module without volume group name (base) -----------*/ - //vg name not exist, so vf module created immediately - pullJobProcessAndPushBackWithTypeAssertion(JobStatus.CREATING, JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching); + //mock mso to answer 200 of create vfModule instance request, pull+execute volumeGroup job, STATUS resource in progress + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs/" + VNF_INSTANCE_ID + "/vfModules"), any())).thenReturn( + createResponse(200, UUID.randomUUID().toString(), VG_REQUEST_ID)); + //mock mso to answer for vf module orchestration request + when(restMso.GetForObject(endsWith(VF_MODULE_REQUEST_ID), eq(AsyncRequestStatus.class))).thenReturn( + asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs/" + VNF_INSTANCE_ID + "/volumeGroups"), any())).thenReturn( + createResponse(200, VG_INSTANCE_ID, VG_REQUEST_ID)); + //mock mso to answer for volume group orchestration request + when(restMso.GetForObject(endsWith(VG_REQUEST_ID), eq(AsyncRequestStatus.class))).thenReturn( + asyncRequestStatusResponseAsRestObject(msoVnfStatus)); - //verify vnf/volumeGroup job STATUS still watching with resource in progress - pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching, JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching); + /*---------- vfModule -----------*/ //mock mso to answer 200 of create vfModule instance request, pull+execute volumeGroup job, STATUS resource in progress - reset(restMso); - when(restMso.PostForObject(any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs/" + VNF_INSTANCE_ID + "/vfModules"), eq(RequestReferencesContainer.class))).thenReturn( - createResponse(200, UUID.randomUUID().toString(), VF_MODULE_REQUEST_ID)); - pullJobProcessAndPushBackWithTypeAssertion(JobStatus.CREATING, JobStatus.RESOURCE_IN_PROGRESS, JobType.ResourceInProgressStatus); + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs/" + VNF_INSTANCE_ID + "/vfModules"), any())).thenReturn( + createResponse(200, UUID.randomUUID().toString(), VF_MODULE_REQUEST_ID2)); //mock mso to answer for vf module orchestration request - reset(restMso); - when(restMso.GetForObject(endsWith(VF_MODULE_REQUEST_ID), eq(AsyncRequestStatus.class))).thenReturn( - asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); - pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, JobType.ResourceInProgressStatus, JobStatus.COMPLETED, JobType.ResourceInProgressStatus); - - //verify volume group become completed - pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching, JobStatus.COMPLETED, JobType.Watching); + when(restMso.GetForObject(endsWith(VF_MODULE_REQUEST_ID2), eq(AsyncRequestStatus.class))).thenReturn( + asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + + processJobsCountTimesAndAssertStatus(uuid, 200, COMPLETED); + verify(restMso, times(1)).restCall(eq(HttpMethod.POST), any(), any(), eq("/serviceInstantiation/v7/serviceInstances"), any()); + verify(restMso, times(1)).restCall(eq(HttpMethod.POST), any(), any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs"), any()); + verify(restMso, times(1)).restCall(eq(HttpMethod.POST), any(), any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs/" + VNF_INSTANCE_ID + "/volumeGroups"), any()); + verify(restMso, times(2)).restCall(eq(HttpMethod.POST), any(), any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs/" + VNF_INSTANCE_ID + "/vfModules"), any()); + verify(restMso, times(5)).GetForObject(any(), any()); + } - //vnf become watching after volume group completed, and new volume group created - pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, JobType.WatchingBaseModule, JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching); + @Test + public void testALaCarteLifeCycle2Networks() { - /*---------- volume group & vf module (non base) -----------*/ + //Create Service with 2 networks, and make sure they created in sequence (and not in parallel) + //Config MSO to response 200 only to first network creation. And answer 500 for second one. + //Then MSO return in_progress some times (like 10 times), and then return COMPLETE. + //Only when MSO return COMPLETE for first network, config MSO to return 200 for second network creation - /*---------- volume group -----------*/ + final String SERVICE_REQUEST_ID = UUID.randomUUID().toString(); + final String SERVICE_INSTANCE_ID = UUID.randomUUID().toString(); + final String NETWORK_REQUEST_ID1 = UUID.randomUUID().toString(); + final String NETWORK_INSTANCE_ID1 = UUID.randomUUID().toString(); + //TODO use them later for different networks + final String NETWORK_REQUEST_ID2 = UUID.randomUUID().toString(); + final String NETWORK_INSTANCE_ID2 = UUID.randomUUID().toString(); - //mock mso to answer 200 of create volumeGroup instance request, pull+execute volumeGroup job, STATUS resource in progress - reset(restMso); - when(restMso.PostForObject(any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs/" + VNF_INSTANCE_ID + "/volumeGroups"), eq(RequestReferencesContainer.class))).thenReturn( - createResponse(200, VG_INSTANCE_ID, VG_REQUEST_ID)); - pullJobProcessAndPushBackWithTypeAssertion(JobStatus.CREATING, JobStatus.RESOURCE_IN_PROGRESS, JobType.VolumeGroupInProgressStatus); - //verify vnf job STATUS still watching with resource in progress - pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching, JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching); + NetworkDetails networkDetails1 = new NetworkDetails("LukaDoncic", "1"); + NetworkDetails networkDetails2 = new NetworkDetails("KevinDurant", "2"); - //mock mso to answer for volume group orchestration request reset(restMso); - when(restMso.GetForObject(endsWith(VG_REQUEST_ID), eq(AsyncRequestStatus.class))).thenReturn( - asyncRequestStatusResponseAsRestObject(msoVnfStatus)); - pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, JobType.VolumeGroupInProgressStatus, JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching); - /*---------- vfModule -----------*/ + /*---------- service -----------*/ - //mock mso to answer 200 of create vfModule instance request, pull+execute volumeGroup job, STATUS resource in progress - reset(restMso); - when(restMso.PostForObject(any(), endsWith(SERVICE_INSTANCE_ID + "/vnfs/" + VNF_INSTANCE_ID + "/vfModules"), eq(RequestReferencesContainer.class))).thenReturn( - createResponse(200, UUID.randomUUID().toString(), VF_MODULE_REQUEST_ID2)); - pullJobProcessAndPushBackWithTypeAssertion(JobStatus.CREATING, JobStatus.RESOURCE_IN_PROGRESS, JobType.ResourceInProgressStatus); + //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 for vf module orchestration request - reset(restMso); - when(restMso.GetForObject(endsWith(VF_MODULE_REQUEST_ID2), eq(AsyncRequestStatus.class))).thenReturn( - asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); - pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus.RESOURCE_IN_PROGRESS, JobType.ResourceInProgressStatus, JobStatus.COMPLETED, JobType.ResourceInProgressStatus); + //mock mso to answer COMPLETE for service instance create + when(restMso.GetForObject(endsWith(SERVICE_REQUEST_ID), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + + final MutableInt secondNetworkCode = new MutableInt(500); + final MutableInt inProgressCount = new MutableInt(0); + + /*---------- network 1-----------*/ + + //mock mso to answer 200 of first create network instance request + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), + MockitoHamcrest.argThat(jsonPartMatches("requestDetails.requestInfo.instanceName", equalTo(networkDetails1.name))) , + endsWith(SERVICE_INSTANCE_ID + "/networks"), any())).thenReturn( + createResponse(200, NETWORK_INSTANCE_ID1, NETWORK_REQUEST_ID1)); + + //mock mso to answer IN_PROGRESS 10 times, and only then COMPLETE for first network + //Once COMPLETE, second network creation will return 200 + when(restMso.GetForObject(endsWith(NETWORK_REQUEST_ID1), eq(AsyncRequestStatus.class))). + thenAnswer(x->{ + String status; + if (inProgressCount.getValue()<10) { + status = IN_PROGRESS_STR; + } else { + secondNetworkCode.setValue(200); + status = COMPLETE_STR; + } + inProgressCount.add(1); + return asyncRequestStatusResponseAsRestObject(status); + }); + + /*---------- network 2-----------*/ + + //mock MSO to return status code of secondNetworkCode (500 and 200 after first one COMPLETED) + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), + MockitoHamcrest.argThat(jsonPartMatches("requestDetails.requestInfo.instanceName", equalTo(networkDetails2.name))) , + endsWith(SERVICE_INSTANCE_ID + "/networks"), any())).thenAnswer(x-> + createResponse(secondNetworkCode.intValue(), NETWORK_INSTANCE_ID2, NETWORK_REQUEST_ID2)); + +// when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any() , endsWith(SERVICE_INSTANCE_ID + "/networks"), any())).thenReturn( +// createResponse(200, NETWORK_INSTANCE_ID1, NETWORK_REQUEST_ID1)); + //mock mso to answer COMPLETE for network creation status, + + when(restMso.GetForObject(endsWith(NETWORK_REQUEST_ID2), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + + + /*---------- Create request and process it -----------*/ + //push alacarte with 2 networks, verify STATUS pending + when(featureManager.isActive(Features.FLAG_EXP_CREATE_RESOURCES_IN_PARALLEL)).thenReturn(false); + ServiceInstantiation serviceInstantiation = generateALaCarteWithNetworksPayload(ImmutableList.of(networkDetails1, networkDetails2)); + UUID uuid = asyncInstantiationBL.pushBulkJob(serviceInstantiation, USER_ID).get(0); + singleServicesAndAssertStatus(JobStatus.PENDING, uuid); - //execute twice - 1 for parent volume group, 1 for parent vnf - pullAllJobProcessAndPushBackByType(JobStatus.RESOURCE_IN_PROGRESS, JobType.Watching , JobStatus.COMPLETED); + processJobsCountTimesAndAssertStatus(uuid, 200, COMPLETED); - singleServicesAndAssertStatus(JobStatus.IN_PROGRESS, uuid); - pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.COMPLETED, true); - singleServicesAndAssertStatus(JobStatus.COMPLETED, uuid); + //validate the mso request id is the right one + List serviceInfoList = asyncInstantiationBL.getAllServicesInfo(); + ServiceInfo serviceInfo = serviceInfoList.get(0); + assertThat(serviceInfo.getMsoRequestId(), is(UUID.fromString(SERVICE_REQUEST_ID))); + + /*---------- verify -----------*/ + verify(restMso, times(1)).restCall(eq(HttpMethod.POST), any(), any(), eq("/serviceInstantiation/v7/serviceInstances"), any()); + verify(restMso, times(2)).restCall(eq(HttpMethod.POST), any(), any(), endsWith(SERVICE_INSTANCE_ID + "/networks"), any()); + //get status + verify(restMso, times(1)).GetForObject(endsWith(SERVICE_REQUEST_ID), any()); + verify(restMso, times(11)).GetForObject(endsWith(NETWORK_REQUEST_ID1), any()); + verify(restMso, times(1)).GetForObject(endsWith(NETWORK_REQUEST_ID2), any()); } - //@Test + @Test public void testBadAaiResponseForSearchNamesAndBackToNormal() { when(aaiClient.isNodeTypeExistsByName(any(), any())).thenThrow(aaiNodeQueryBadResponseException()); - pushMacroBulk(); //JOB shall become IN_PROGRESS but service info is still pending - Job job = pullJobProcessAndPushBack(PENDING, JobStatus.IN_PROGRESS, true); - listServicesAndAssertStatus(PENDING, PENDING, job); + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), any(), eq(Optional.empty()))).thenReturn(createResponse(200)); + when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); - //JOB shall remain in IN_PROGRESS - job = pullJobProcessAndPushBack( JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS, true); - //make sure the job command is still ServiceInstantiation - assertThat(job.getType(), is(JobType.MacroServiceInstantiation)); - listServicesAndAssertStatus(PENDING, PENDING, job); + List uuids = pushMacroBulk(); + processJobsCountTimesAndAssertStatus(uuids.get(0), 5, IN_PROGRESS, PENDING); //JOB shall become IN_PROGRESS but service info is still pending //simulate AAI back to normal, AAI return name is free, and MSO return good response Mockito.reset(aaiClient); // must forget the "thenThrow" when(aaiClient.isNodeTypeExistsByName(any(), any())).thenReturn(false); - when(restMso.PostForObject(any(),any(), eq(RequestReferencesContainer.class))).thenReturn(createResponse(200)); - job = pullJobProcessAndPushBack( JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS, true); - listServicesAndAssertStatus(JobStatus.IN_PROGRESS, PENDING, job); + processJobsCountTimesAndAssertStatus(uuids.get(0), 30, COMPLETED, COMPLETED); - //when get job COMPLETE from MSO, service status become COMPLETED - when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))). - thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); - job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, COMPLETED); - listServicesAndAssertStatus(COMPLETED, PENDING, job); } - //@Test + @Test public void testAaiResponseNameUsedTillMaxRetries() { when(aaiClient.isNodeTypeExistsByName(any(), any())).thenReturn(true); + //simulate MSO to return good result, for making sure we failed because of AAI error + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), any(), eq(Optional.empty()))).thenReturn(createResponse(200)); + when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + asyncInstantiationBL.setMaxRetriesGettingFreeNameFromAai(10); - pushMacroBulk(); - //JOB shall become IN_PROGRESS but service info is still pending - Job job = pullJobProcessAndPushBack(PENDING, JobStatus.FAILED, true); - listServicesAndAssertStatus(JobStatus.FAILED, JobStatus.STOPPED, job); + List uuids = pushMacroBulk(); + processJobsCountTimesAndAssertStatus(uuids.get(0), 20, FAILED, STOPPED); } private Job pullJobProcessAndPushBack(JobStatus topic, JobStatus expectedNextJobStatus) { @@ -559,22 +610,23 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes return job.get(); } + private void simplePullJobProcessAndPushBack(JobStatus topic) { + Optional optionalJob = jobsBrokerService.pull(topic, randomUuid()); + optionalJob.ifPresent(job->{ + Job nextJob = jobWorker.executeJobAndGetNext(job); + jobsBrokerService.pushBack(nextJob); + }); + } + private Job pullJobProcessAndPushBackWithTypeAssertion(JobStatus topic, JobStatus expectedNextJobStatus, - JobType expectedNextJobType) { + JobType expectedNextJobType) { Job job = pullJobProcessAndPushBack(topic, expectedNextJobStatus, false); assertThat("job not ok: " + job.getData(), job.getType(), is(expectedNextJobType)); return job; } private Job pullJobProcessAndPushBackWithTypeAssertion(JobStatus topic, JobStatus expectedNextJobStatus, - JobType expectedNextJobType, int retries) { - return retryWithAssertionsLimit(retries, () -> { - return pullJobProcessAndPushBackWithTypeAssertion(topic, expectedNextJobStatus, expectedNextJobType); - }); - } - - private Job pullJobProcessAndPushBackWithTypeAssertion(JobStatus topic, JobStatus expectedNextJobStatus, - JobType expectedNextJobType, Action actionPhase, InternalState internalState, int retries) { + JobType expectedNextJobType, Action actionPhase, InternalState internalState, int retries) { return retryWithAssertionsLimit(retries, () -> { Job job = pullJobProcessAndPushBackWithTypeAssertion(topic, expectedNextJobStatus, expectedNextJobType); assertThat("job not ok: " + job.getData(), job.getData(), is(jsonPartEquals("actionPhase", actionPhase.name()))); @@ -598,49 +650,11 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes // No success: throw new AssertionError("No luck while all of these assertion errors: " + history.stream() - .map(Throwable::getMessage) - .map(s -> s.replace('\n', ' ')) - .map(s -> s.replaceAll("\\s{2,}"," ")) - .distinct() - .collect(joining("\n ", "\n ", "")), history.peek()); - } - - private Job pullMultipleJobsFindExpectedProcessAndPushBack(JobStatus topic, JobType expectedCurrentJobType, JobStatus expectedNextJobStatus, - JobType expectedNextJobType) { - List pulledJobs = new ArrayList<>(); - Job lastJob = null; - while (lastJob == null || lastJob.getType() != expectedCurrentJobType) { - lastJob = pullJob(topic, false).get(); - if (lastJob.getType() != expectedCurrentJobType) { - pulledJobs.add(lastJob); - } - } - - Job nextJob = jobWorker.executeJobAndGetNext(lastJob); - assertThat(nextJob.getStatus(), is(expectedNextJobStatus)); - assertThat(nextJob.getType(), is(expectedNextJobType)); - - jobsBrokerService.pushBack(nextJob); - assertThat(jobsBrokerService.peek(nextJob.getUuid()).getStatus(), is(expectedNextJobStatus)); - - pulledJobs.forEach(job -> - jobsBrokerService.pushBack(job) - ); - - return nextJob; - } - - private void pullAllJobProcessAndPushBackByType(JobStatus topic, JobType commandType, JobStatus expectedFinalStatus) { - Map jobStatusMap = new HashMap<>(); - Optional job = pullJob(topic, false); - for (int i=0; i<1000 && job.isPresent() && job.get().getType() == commandType; i++) { - Job nextJob = jobWorker.executeJobAndGetNext(job.get()); - jobStatusMap.put(nextJob.getUuid(), nextJob.getStatus()); - jobsBrokerService.pushBack(nextJob); - job = jobsBrokerService.pull(topic, UUID.randomUUID().toString()); - } - assertThat(jobStatusMap.values(), everyItem(is(expectedFinalStatus))); - + .map(Throwable::getMessage) + .map(s -> s.replace('\n', ' ')) + .map(s -> s.replaceAll("\\s{2,}"," ")) + .distinct() + .collect(joining("\n ", "\n ", "")), history.peek()); } private Optional pullJob(JobStatus topic, boolean pullingAssertion) { @@ -665,49 +679,37 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes } - //@Test + @Test public void whenPushNewBulk_andGetNoResponseFromMsoOnCreation_thenServiceMoveToFailedAndOtherToStopped() { - when(restMso.PostForObject(any(), any(), eq(RequestReferencesContainer.class))).thenReturn(createResponse(500)); - pushBulkPullPendingJobAndAssertJobStatus(JobStatus.FAILED, JobStatus.STOPPED); + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), any(), eq(Optional.empty()))).thenReturn(createResponse(500)); + //assert that when get ProcessingException from restMso, status remain the same + List uuids = pushMacroBulk(); + processJobsCountTimesAndAssertStatus(uuids.get(0), 30, JobStatus.FAILED, JobStatus.STOPPED); } - //@Test + @Test public void whenMsoStatusIsPendingManualTask_ThenJobStatusIsPaused() { - when(restMso.PostForObject(any(), any(), eq(RequestReferencesContainer.class))).thenReturn(createResponse(200)); - - Job firstJob = pushBulkPullPendingJobAndAssertJobStatus(JobStatus.IN_PROGRESS, PENDING); + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), any(), eq(Optional.empty()))).thenReturn(createResponse(200)); + when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(PENDING_MANUAL_TASK)); //assert that when get ProcessingException from restMso, status remain the same - when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))). - thenReturn(asyncRequestStatusResponseAsRestObject(PENDING_MANUAL_TASK)); - Job job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS); - listServicesAndAssertStatus(PAUSE, PENDING, job); + List uuids = pushMacroBulk(); + processJobsCountTimesAndAssertStatus(uuids.get(0), 30, PAUSE, PENDING); - //The paused job is pulled and remain in pause state. Other jobs from bulk remain pending - job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS); - listServicesAndAssertStatus(PAUSE, PENDING, job); //the job get IN_PROGRESS response (simulate activate operation) and status changed to IN_PROGRESS when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))). - thenReturn(asyncRequestStatusResponseAsRestObject(IN_PROGRESS_STR)); - job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.IN_PROGRESS); - listServicesAndAssertStatus(JobStatus.IN_PROGRESS, PENDING, job); + thenReturn(asyncRequestStatusResponseAsRestObject(IN_PROGRESS_STR)); + processJobsCountTimesAndAssertStatus(uuids.get(0), 30, IN_PROGRESS, PENDING); + //the job get COMPLETE response this job is copmpleted and then also other jobs when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))). - thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); - job = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, COMPLETED); - listServicesAndAssertStatus(COMPLETED, PENDING, job); - - //Pulling PENDING job return another job - assertThat(jobsBrokerService.pull(PENDING, randomUuid()).get().getUuid(), not(equalTo(job.getUuid()))); - - - ImmutableList expectedStatusesForMso = ImmutableList.of(REQUESTED, PENDING_MANUAL_TASK, IN_PROGRESS_STR, COMPLETE_STR); - List msoStatuses = asyncInstantiationBL.getAuditStatuses(firstJob.getUuid(), MSO).stream().map(x -> x.getJobStatus()).collect(Collectors.toList()); - assertThat(msoStatuses, is(expectedStatusesForMso)); + thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + processJobsCountTimesAndAssertStatus(uuids.get(0), 200, COMPLETED, COMPLETED); ImmutableList expectedStatusesForVid = statusesToStrings(PENDING, IN_PROGRESS, PAUSE, IN_PROGRESS, COMPLETED); - List vidStatuses = asyncInstantiationBL.getAuditStatuses(firstJob.getUuid(), VID).stream().map(x -> x.getJobStatus()).collect(Collectors.toList()); + List vidStatuses = auditService.getAuditStatuses(uuids.get(0), VID).stream().map(x -> x.getJobStatus()).collect(Collectors.toList()); assertThat(vidStatuses, is(expectedStatusesForVid)); } @@ -718,65 +720,76 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes private Job pullPendingJobAndAssertJobStatus(JobStatus pulledJobStatus, JobStatus otherJobsStatus) { Job job = pullJobProcessAndPushBack(PENDING, pulledJobStatus, false); - listServicesAndAssertStatus(pulledJobStatus, otherJobsStatus, job); + listServicesAndAssertStatus(pulledJobStatus, otherJobsStatus, job.getUuid()); return job; } - //@Test + @Test public void test2BulksLifeCyclesAreIndependent() { - pushMacroBulk(); - when(restMso.PostForObject(any(), any(), eq(RequestReferencesContainer.class))).thenReturn(createResponse(200)); - //push 2nd job, then when pulling first job the job become in_progress, other jobs (from 2 bulks) remain pending - Job firstJob = pushBulkPullPendingJobAndAssertJobStatus(JobStatus.IN_PROGRESS, PENDING); - //assert we can pull another job from pending from other template id - Job secondJob = pullJobProcessAndPushBack(PENDING, JobStatus.IN_PROGRESS, false); - assertThat(firstJob.getTemplateId(), not(equalTo(secondJob.getTemplateId()))); - - //assert no more PENDING jobs to pull - assertFalse(jobsBrokerService.pull(PENDING, randomUuid()).isPresent()); - - //when get FAILED status from MSO statuses for failed bulk are: FAILED, STOPPED, for other bulk: IN_PROGRESS, 2 pending - when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))). - thenReturn(asyncRequestStatusResponseAsRestObject(FAILED_STR)); - Job failedJob = pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, JobStatus.FAILED, false); + final String SERVICE1_REQUEST_ID = UUID.randomUUID().toString(); + final String SERVICE1_INSTANCE_ID = UUID.randomUUID().toString(); + final String SERVICE2_REQUEST_ID = UUID.randomUUID().toString(); + final String SERVICE2_INSTANCE_ID = UUID.randomUUID().toString(); + final String SERVICE3_4_REQUEST_ID = UUID.randomUUID().toString(); + final String SERVICE3_4_INSTANCE_ID = UUID.randomUUID().toString(); + + + //create first bulk and make one job in progress + List firstBulksIDs = pushMacroBulk(); + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), any(), eq(Optional.empty()))) + .thenReturn(createResponse(200, SERVICE1_INSTANCE_ID, SERVICE1_REQUEST_ID)); + when(restMso.GetForObject(endsWith(SERVICE1_REQUEST_ID), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(IN_PROGRESS_STR)); + processJobsCountTimesAndAssertStatus(firstBulksIDs.get(0), 30, IN_PROGRESS, PENDING); + + //create 2nd bulk, then when pulling first job the job become in_progress, other jobs (from 2 bulks) remain pending + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), any(), eq(Optional.empty()))) + .thenReturn(createResponse(200, SERVICE2_INSTANCE_ID, SERVICE2_REQUEST_ID)); + when(restMso.GetForObject(endsWith(SERVICE2_REQUEST_ID), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(IN_PROGRESS_STR)); + List secondBulksIDs = pushMacroBulk(); + processJobsCountTimes(30); + Map statusCount = getJobStatusesCount(); + assertThat(statusCount.get(IN_PROGRESS), is(2L)); + assertThat(statusCount.get(PENDING), is(4L)); + + //return failed to first job + //first bulk statuses shall be: FAILED, STOPPED, STOPPED + //second bulk statuses shall be: IN_PROGRESS, PENDING, PENDING + when(restMso.GetForObject(endsWith(SERVICE1_REQUEST_ID), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(FAILED_STR)); + processJobsCountTimes(30); Map> servicesByTemplateId = - asyncInstantiationBL.getAllServicesInfo() - .stream().collect(groupingBy(ServiceInfo::getTemplateId)); - assertServicesStatus(servicesByTemplateId.get(failedJob.getTemplateId()), JobStatus.FAILED, JobStatus.STOPPED, failedJob); - Job successJob = failedJob.getUuid().equals(firstJob.getUuid()) ? secondJob : firstJob; - assertServicesStatus(servicesByTemplateId.get(successJob.getTemplateId()), JobStatus.IN_PROGRESS, PENDING, successJob); - - //yet no more PENDING jobs to pull - assertFalse(jobsBrokerService.pull(PENDING, randomUuid()).isPresent()); - - //assert that job from non failed bulk can progress. - //When completed, failed bulk statuses: FAILED, STOPPED. Succeeded bulk statuses are : COMPLETED, 2 pending - when(restMso.GetForObject(any(), eq(AsyncRequestStatus.class))). - thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); - pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, COMPLETED, false); - servicesByTemplateId = - asyncInstantiationBL.getAllServicesInfo() - .stream().collect(groupingBy(ServiceInfo::getTemplateId)); - assertServicesStatus(servicesByTemplateId.get(failedJob.getTemplateId()), JobStatus.FAILED, JobStatus.STOPPED, failedJob); - assertServicesStatus(servicesByTemplateId.get(successJob.getTemplateId()), COMPLETED, PENDING, successJob); - - //advance other jobs of succeeded bulk till al of them reach to COMPLETED - pullJobProcessAndPushBack(PENDING, JobStatus.IN_PROGRESS, false); - pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, COMPLETED, false); - pullJobProcessAndPushBack(PENDING, JobStatus.IN_PROGRESS, false); - pullJobProcessAndPushBack(JobStatus.IN_PROGRESS, COMPLETED, false); - servicesByTemplateId = - asyncInstantiationBL.getAllServicesInfo() - .stream().collect(groupingBy(ServiceInfo::getTemplateId)); - assertServicesStatus(servicesByTemplateId.get(failedJob.getTemplateId()), JobStatus.FAILED, JobStatus.STOPPED, failedJob); - assertServicesStatus(servicesByTemplateId.get(successJob.getTemplateId()), COMPLETED, COMPLETED, successJob); - + asyncInstantiationBL.getAllServicesInfo() + .stream().collect(groupingBy(ServiceInfo::getTemplateId)); + ServiceInfo failedJob = asyncInstantiationBL.getAllServicesInfo().stream().filter(x->x.getJobId().equals(firstBulksIDs.get(0))).findFirst().get(); + assertServicesStatus(servicesByTemplateId.get(failedJob.getTemplateId()), JobStatus.FAILED, JobStatus.STOPPED, failedJob.getJobId()); + ServiceInfo successJob = asyncInstantiationBL.getAllServicesInfo().stream().filter(x->x.getJobId().equals(secondBulksIDs.get(0))).findFirst().get(); + assertServicesStatus(servicesByTemplateId.get(successJob.getTemplateId()), JobStatus.IN_PROGRESS, PENDING, successJob.getJobId()); + + //return completed to all other jobs + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), any(), eq(Optional.empty()))) + .thenReturn(createResponse(200, SERVICE3_4_INSTANCE_ID, SERVICE3_4_REQUEST_ID)); + when(restMso.GetForObject(endsWith(SERVICE2_REQUEST_ID), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + when(restMso.GetForObject(endsWith(SERVICE3_4_REQUEST_ID), eq(AsyncRequestStatus.class))). + thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + + processJobsCountTimes(30); + servicesByTemplateId = asyncInstantiationBL.getAllServicesInfo().stream().collect(groupingBy(ServiceInfo::getTemplateId)); + assertServicesStatus(servicesByTemplateId.get(failedJob.getTemplateId()), JobStatus.FAILED, JobStatus.STOPPED, failedJob.getJobId()); + assertServicesStatus(servicesByTemplateId.get(successJob.getTemplateId()), COMPLETED, COMPLETED, successJob.getJobId()); //assert no more PENDING jobs nor IN_PROGRESS jobs to pull assertFalse(jobsBrokerService.pull(PENDING, randomUuid()).isPresent()); assertFalse(jobsBrokerService.pull(JobStatus.IN_PROGRESS, randomUuid()).isPresent()); } + protected Map getJobStatusesCount() { + return asyncInstantiationBL.getAllServicesInfo().stream().collect(groupingBy(ServiceInfo::getJobStatus, counting())); + } + + @Test public void deploy2NewGroupsToServiceWith1ExistingGroup() { /* @@ -795,18 +808,7 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes [v] + pull+execute (should NOT post to MSO) [v] verify STATUS in progress; TYPE watching ... - [v] verify job#2 *new* GROUP job STATUS completed with no action TYPE group INTERNAL STATE terminal PHASE delete - [v] verify job#3 *new* GROUP job STATUS completed with no action TYPE group INTERNAL STATE terminal PHASE delete - [v] verify job#4 *new* GROUP job STATUS completed with no action TYPE group INTERNAL STATE terminal PHASE delete - [v] + pull+execute job#1 (should NOT post to MSO) - [v] verify STATUS in progress; TYPE watching - [v] verify job#5 *new* GROUP job STATUS creating TYPE group INTERNAL STATE initial PHASE create - [v] verify job#6 *new* GROUP job STATUS creating TYPE group INTERNAL STATE initial PHASE create - [v] verify job#7 *new* GROUP job STATUS creating TYPE group INTERNAL STATE initial PHASE create - - [v] + pull+execute job#5 (should NOT post to MSO) - [v] verify job#5 STATUS completed with no action TYPE group INTERNAL STATE terminal PHASE create [v] + pull+execute job#1 [v] verify job#1 STATUS in progress; TYPE watching @@ -845,70 +847,265 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes singleServicesAndAssertStatus(PENDING, uuid); // take from pending, put in-progress -> 3 delete-child were born - pullJobProcessAndPushBackWithTypeAssertion(PENDING, IN_PROGRESS, JobType.ALaCarteService, Action.Delete, InternalState.WATCHING, 1); - verifyQueueSizes(ImmutableMap.of( - IN_PROGRESS, 1, CREATING, 3 - )); - - Stream.of(1, 2, 3).forEach(i -> { - // take each child creating, put in-progress - verify_Job1InProgress.accept(Action.Delete, IN_PROGRESS); - pullJobProcessAndPushBackWithTypeAssertion(CREATING, RESOURCE_IN_PROGRESS, JobType.InstanceGroup, Action.Delete, null, 1); - - // execute each in-progress -> job is completed - verify_Job1InProgress.accept(Action.Delete, IN_PROGRESS); - pullJobProcessAndPushBackWithTypeAssertion(RESOURCE_IN_PROGRESS, COMPLETED/*_WITH_NO_ACTION*/, JobType.InstanceGroup,1); - }); + pullJobProcessAndPushBackWithTypeAssertion(PENDING, IN_PROGRESS, JobType.ALaCarteService, Action.Create, InternalState.INITIAL, 1); verifyQueueSizes(ImmutableMap.of( - IN_PROGRESS, 1, COMPLETED, 3 + IN_PROGRESS, 1 )); // take job #1 from phase delete to phase create -> 3 create-child were born verify_Job1InProgress.accept(Action.Create, IN_PROGRESS); verifyQueueSizes(ImmutableMap.of( - IN_PROGRESS, 1, CREATING, 3, COMPLETED, 3 + IN_PROGRESS, 1, PENDING_RESOURCE, 3 )); // prepare MSO mock - when(restMso.PostForObject(any(), endsWith("instanceGroups"), eq(RequestReferencesContainer.class))) - .thenReturn(createResponse(200, GROUP1_INSTANCE_ID, GROUP1_REQUEST_ID)) - .thenReturn(createResponse(200, GROUP2_INSTANCE_ID, GROUP2_REQUEST_ID)) - .thenReturn(null); + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), endsWith("instanceGroups"), eq(Optional.empty()))) + .thenReturn(createResponse(200, GROUP1_INSTANCE_ID, GROUP1_REQUEST_ID)) + .thenReturn(createResponse(200, GROUP2_INSTANCE_ID, GROUP2_REQUEST_ID)) + .thenReturn(null); when(restMso.GetForObject(argThat(uri -> StringUtils.endsWithAny(uri, GROUP1_REQUEST_ID, GROUP2_REQUEST_ID)), eq(AsyncRequestStatus.class))). - thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); - // take first "none" child from creating to completed + // take first "none" child from creating to COMPLETED_WITH_NO_ACTION // note there's no concrete mechanism that makes the first child be - // the "action=None" case, but that's what happens, and following line + // the "action=None" case, but that's what happens, and following lines // relies on that fact. - pullJobProcessAndPushBackWithTypeAssertion(CREATING, COMPLETED_WITH_NO_ACTION, JobType.InstanceGroupInstantiation, 1); + pullJobProcessAndPushBackWithTypeAssertion(PENDING_RESOURCE, COMPLETED_WITH_NO_ACTION, JobType.InstanceGroup, Action.Create, null, 1); // take each of next two children from creating to in-progress, then to completed // verify job #1 is watching, and MSO is getting requests Stream.of(1, 2).forEach(i -> { verify_Job1InProgress.accept(Action.Create, IN_PROGRESS); - pullJobProcessAndPushBackWithTypeAssertion(CREATING, RESOURCE_IN_PROGRESS, JobType.ResourceInProgressStatus); - verify(restMso, times(i)).PostForObject(any(), any(), any()); + pullJobProcessAndPushBackWithTypeAssertion(PENDING_RESOURCE, RESOURCE_IN_PROGRESS, JobType.InstanceGroup, Action.Create, InternalState.IN_PROGRESS, 1); + verify(restMso, times(i)).restCall(any(), any(), any(), any(), any()); verify_Job1InProgress.accept(Action.Create, IN_PROGRESS); - pullJobProcessAndPushBackWithTypeAssertion(RESOURCE_IN_PROGRESS, COMPLETED, JobType.ResourceInProgressStatus); + pullJobProcessAndPushBackWithTypeAssertion(RESOURCE_IN_PROGRESS, COMPLETED, JobType.InstanceGroup, Action.Create, null, 3); verify(restMso, times(i)).GetForObject(any(), any()); }); // job #1 is done as all children are done verify_Job1InProgress.accept(Action.Create, COMPLETED); - verifyQueueSizes(ImmutableMap.of(COMPLETED, 7)); + verifyQueueSizes(ImmutableMap.of(COMPLETED, 3, COMPLETED_WITH_NO_ACTION, 1)); + } + + @DataProvider + public static Object[][] createAndDeleteIntegrationTestDataProvider(Method test) { + return new Object[][]{ + {"create and delete both bad http code", createResponse(400), createResponse(500), null, null, FAILED, 0}, + {"create and delete success and status is success ", createResponseRandomIds(202), createResponseRandomIds(202), + asyncRequestStatusResponseAsRestObject(COMPLETE_STR), asyncRequestStatusResponseAsRestObject(COMPLETE_STR), COMPLETED, 2}, + {"create and delete success, create status FAILED, delete status COMPLETED", createResponseRandomIds(202), createResponseRandomIds(202), + asyncRequestStatusResponseAsRestObject(FAILED_STR), asyncRequestStatusResponseAsRestObject(COMPLETE_STR), COMPLETED_WITH_ERRORS, 2}, + {"create and delete success, create status FAILED, delete status FAILED", createResponseRandomIds(202), createResponseRandomIds(202), + asyncRequestStatusResponseAsRestObject(FAILED_STR), asyncRequestStatusResponseAsRestObject(FAILED_STR), FAILED, 2}, + {"create success but delete failed and status is success ", createResponseRandomIds(202), createResponseRandomIds(400), + asyncRequestStatusResponseAsRestObject(COMPLETE_STR), null, COMPLETED_WITH_ERRORS, 1}, + {"delete success but create failed and status is success ", createResponseRandomIds(400), createResponseRandomIds(202), + null, asyncRequestStatusResponseAsRestObject(COMPLETE_STR), COMPLETED_WITH_ERRORS, 1}, + {"delete success but create failed and status of delete is FAILED ", createResponseRandomIds(400), createResponseRandomIds(202), + null, asyncRequestStatusResponseAsRestObject(FAILED_STR), FAILED, 1} + }; + } + + //this test is going along with AsyncInstantiationALaCarteApiTest.viewEditVnfGroup__verifyStatusAndAudit 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") + public void vnfGropingIntegrationTest( + String desc, + RestObject createGroupResponse, + RestObject deleteGroupResponse, + RestObject createStatusResponse, + RestObject deleteStatusResponse, + JobStatus expectedJobStatus, + int getStatusCounter) throws IOException { + + UUID jobUUID = createAndDeleteIntegrationTest("/payload_jsons/VnfGroupCreate1Delete1None1Request.json", + "/serviceInstantiation/v7/instanceGroups", + createGroupResponse, + "/serviceInstantiation/v7/instanceGroups/VNF_GROUP1_INSTANCE_ID", + deleteGroupResponse, + createStatusResponse, + deleteStatusResponse, + expectedJobStatus, + getStatusCounter); + + ServiceInstantiation bulkForRetry = asyncInstantiationBL.getBulkForRetry(jobUUID); + InstanceGroup vnfGroupShouldBeDeleted = bulkForRetry.getVnfGroups().get("groupingservicefortest..ResourceInstanceGroup..0:001"); + InstanceGroup vnfGroupShouldBeCreated = bulkForRetry.getVnfGroups().get("groupingservicefortest..ResourceInstanceGroup..0"); + + if (deleteStatusResponse == null || deleteStatusResponse.get().request.requestStatus.getRequestState().equals(FAILED_STR)) { + assertThat(vnfGroupShouldBeDeleted.getAction(), equalTo(Action.Delete)); + assertErrorForResource(vnfGroupShouldBeDeleted, deleteGroupResponse, deleteStatusResponse); + } + + if (createStatusResponse == null || createStatusResponse.get().request.requestStatus.getRequestState().equals(FAILED_STR)) { + assertThat(vnfGroupShouldBeCreated.getAction(), equalTo(Action.Create)); + assertErrorForResource(vnfGroupShouldBeCreated, createGroupResponse, createStatusResponse); + } + } + + //this test is going along with AsyncInstantiationALaCarteApiTest3.delete1Create1VnfFromService 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") + public void vnfsIntegrationTest( + String desc, + RestObject createVnfResponse, + RestObject deleteVnfResponse, + RestObject createStatusResponse, + RestObject deleteStatusResponse, + JobStatus expectedJobStatus, + int getStatusCounter) throws IOException { + + createAndDeleteIntegrationTest("/payload_jsons/vnfDelete1Create1Request.json", + "/serviceInstantiation/v7/serviceInstances/f8791436-8d55-4fde-b4d5-72dd2cf13cfb/vnfs", + createVnfResponse, + "/serviceInstantiation/v7/serviceInstances/f8791436-8d55-4fde-b4d5-72dd2cf13cfb/vnfs/VNF_INSTANCE_ID", + deleteVnfResponse, + createStatusResponse, + deleteStatusResponse, + expectedJobStatus, + getStatusCounter); + } + + @Test(dataProvider="createAndDeleteIntegrationTestDataProvider") + public void vfModulesIntegrationTest( + String desc, + RestObject createVfModuleResponse, + RestObject deleteVfModuleResponse, + RestObject createStatusResponse, + RestObject deleteStatusResponse, + JobStatus expectedJobStatus, + int getStatusCounter) throws IOException, AsdcCatalogException { + + 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); + + createAndDeleteIntegrationTest("/payload_jsons/vfModuleDelete1Create1None1Request.json", + "/serviceInstantiation/v7/serviceInstances/f8791436-8d55-4fde-b4d5-72dd2cf13cfb/vnfs/VNF_INSTANCE_ID/vfModules", + createVfModuleResponse, + "/serviceInstantiation/v7/serviceInstances/f8791436-8d55-4fde-b4d5-72dd2cf13cfb/vnfs/VNF_INSTANCE_ID/vfModules/VF_MODULE_INSTANCE_ID", + deleteVfModuleResponse, + createStatusResponse, + deleteStatusResponse, + expectedJobStatus, + getStatusCounter); + } + + //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") + public void networksIntegrationTest( + String desc, + RestObject createNetworkResponse, + RestObject deleteNetworkResponse, + RestObject createStatusResponse, + RestObject deleteStatusResponse, + JobStatus expectedJobStatus, + int getStatusCounter) throws IOException { + + createAndDeleteIntegrationTest("/payload_jsons/networkDelete1Create1Request.json", + "/serviceInstantiation/v7/serviceInstances/f8791436-8d55-4fde-b4d5-72dd2cf13cfb/networks", + createNetworkResponse, + "/serviceInstantiation/v7/serviceInstances/f8791436-8d55-4fde-b4d5-72dd2cf13cfb/networks/NETWORK_INSTANCE_ID", + deleteNetworkResponse, + createStatusResponse, + deleteStatusResponse, + expectedJobStatus, + getStatusCounter); } + private UUID createAndDeleteIntegrationTest(String payload, + String createPath, + RestObject createResponse, + String deletePath, + RestObject deleteResponse, + RestObject createStatusResponse, + RestObject deleteStatusResponse, + JobStatus expectedJobStatus, + int getStatusCounter) throws IOException { + UUID jobUUID = asyncInstantiationBL.pushBulkJob( + TestUtils.readJsonResourceFileAsObject(payload, ServiceInstantiation.class), "userId") + .get(0); + + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), eq(createPath), any())).thenReturn(createResponse); + when(restMso.restCall(eq(HttpMethod.DELETE), eq(RequestReferencesContainer.class), any(), eq(deletePath), any())).thenReturn(deleteResponse); + if (createStatusResponse!=null) { + when(restMso.GetForObject(endsWith(createResponse.get().getRequestReferences().getRequestId()), eq(AsyncRequestStatus.class))).thenReturn(createStatusResponse); + } + if (deleteStatusResponse!=null) { + when(restMso.GetForObject(endsWith(deleteResponse.get().getRequestReferences().getRequestId()), eq(AsyncRequestStatus.class))).thenReturn(deleteStatusResponse); + } + + processJobsCountTimesAndAssertStatus(jobUUID, 40, expectedJobStatus); + + verify(restMso, times(1)).restCall(eq(HttpMethod.POST), any(), any(), eq(createPath), any()); + verify(restMso, times(1)).restCall(eq(HttpMethod.DELETE), any(), any(), eq(deletePath), any()); + verify(restMso, times(getStatusCounter)).GetForObject(any(), any()); + + return jobUUID; + } + + @Test + public void whenCreateTransportService_thanExpectedPre1806MacroRequestSent() throws IOException { + UUID jobUUID = asyncInstantiationBL.pushBulkJob(generatePre1806MacroTransportServiceInstantiationPayload(null, null),"az2016").get(0); + RestObject createResponse = createResponseRandomIds(202); + + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), eq("/serviceInstantiation/v7/serviceInstances"), any())) + .thenReturn(createResponse); + when(restMso.GetForObject(endsWith(createResponse.get().getRequestReferences().getRequestId()), eq(AsyncRequestStatus.class))) + .thenReturn(asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + processJobsCountTimesAndAssertStatus(jobUUID, 20, COMPLETED); + + JsonNode expectedJson = TestUtils.readJsonResourceFileAsObject("/payload_jsons/pre_1806_macro_without_cloudConfiguration.json", JsonNode.class); + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(RequestDetailsWrapper.class); + verify(restMso).restCall(any(), any(), requestCaptor.capture(), any(), any()); + requestCaptor.getAllValues().forEach(x->assertJsonEquals(expectedJson, x)); + } + + private void assertErrorForResource(BaseResource resource, + RestObject deleteOrCreateResponse, + RestObject statusResponse) { + JobAuditStatus auditStatus = auditService.getResourceAuditStatus(resource.getTrackById()); + assertThat(auditStatus, is(notNullValue())); + assertThat(auditStatus.getJobStatus(), equalTo(FAILED_STR)); + if (statusResponse == null) { + String errorMessage = "Http Code:" + deleteOrCreateResponse.getStatusCode() + ", " + RAW_DATA_FROM_MSO; + assertThat(auditStatus.getAdditionalInfo(), equalTo(errorMessage)); + assertThat(auditStatus.getRequestId(), is(nullValue())); + } else { + assertThat(auditStatus.getRequestId().toString(), equalTo(statusResponse.get().request.requestId)); + } + } + + protected void processJobsCountTimesAndAssertStatus(UUID serviceJobId, int times, JobStatus expectedStatus) { + processJobsCountTimes(times); + singleServicesAndAssertStatus(expectedStatus, serviceJobId); + } + + private void processJobsCountTimes(int times) { + for (int i = 0; i < times; i++) { + WORKERS_TOPICS.forEach(this::simplePullJobProcessAndPushBack); + } + } + + protected void processJobsCountTimesAndAssertStatus(UUID serviceJobId, int times, JobStatus expectedStatus, JobStatus otherJobsStatus) { + processJobsCountTimes(times); + listServicesAndAssertStatus(expectedStatus, otherJobsStatus, serviceJobId); + } + + private void verifyQueueSizes(ImmutableMap expected) { final Collection peek = jobsBrokerService.peek(); final Map jobTypes = peek.stream().collect(groupingBy(Job::getStatus, counting())); - assertThat(jobTypes, is(expected)); + assertThat(jobTypes, jsonEquals(expected)); } - private List listServicesAndAssertStatus(JobStatus pulledJobStatus, JobStatus otherJobsStatus, Job job) { + private List listServicesAndAssertStatus(JobStatus pulledJobStatus, JobStatus otherJobsStatus, UUID jobUUID) { List serviceInfoList = asyncInstantiationBL.getAllServicesInfo(); - assertServicesStatus(serviceInfoList, pulledJobStatus, otherJobsStatus, job); + assertServicesStatus(serviceInfoList, pulledJobStatus, otherJobsStatus, jobUUID); return serviceInfoList; } @@ -922,9 +1119,15 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes return serviceInfo; } - private void assertServicesStatus(List serviceInfoList, JobStatus pulledJobStatus, JobStatus otherJobsStatus, Job job) { + private boolean isServiceOnStatus(JobStatus expectedStatus) { + List serviceInfoList = asyncInstantiationBL.getAllServicesInfo(); + assertEquals(1, serviceInfoList.size()); + return serviceInfoList.get(0).getJobStatus()==expectedStatus; + } + + private void assertServicesStatus(List serviceInfoList, JobStatus pulledJobStatus, JobStatus otherJobsStatus, UUID jobUUID) { serviceInfoList.forEach(si->{ - if (si.getJobId().equals(job.getUuid())) { + if (si.getJobId().equals(jobUUID)) { assertThat(si.getJobStatus(), is(pulledJobStatus)); } else { @@ -935,11 +1138,104 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes private void listServicesAndAssertStatus(Map expectedJobStatusMap) { Map actualStatuses = asyncInstantiationBL.getAllServicesInfo() - .stream().collect(Collectors.toMap(ServiceInfo::getJobId, ServiceInfo::getJobStatus)); + .stream().collect(Collectors.toMap(ServiceInfo::getJobId, ServiceInfo::getJobStatus)); assertThat(actualStatuses.entrySet(), equalTo(expectedJobStatusMap.entrySet())); } private String randomUuid() { return UUID.randomUUID().toString(); } + + @Test + public void whenResumeService_thanExpectedResumeRequestSent() throws IOException { + String instanceId = "a565e6ad-75d1-4493-98f1-33234b5c17e2"; //from feRequestResumeMacroService.json + String originalRequestId = "894089b8-f7f4-418d-81da-34186fd32670"; //from msoResponseGetRequestsOfServiceInstance.json + String resumeRequestId = randomUuid(); + String userId = TestUtils.generateRandomAlphaNumeric(6); + + //prepare mocks for get all requests for instance id + RestObject getRequestByIdResponse = createAsyncRequestStatusListByInstanceId(); + when(restMso.GetForObject( + eq("/orchestrationRequests/v7?filter=serviceInstanceId:EQUALS:" + instanceId), + eq(AsyncRequestStatusList.class))) + .thenReturn(getRequestByIdResponse); + + //prepare mocks resume request + when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), isNull(), eq(String.format("/orchestrationRequests/v7/%s/resume", originalRequestId)), eq(Optional.of(userId)))) + .thenReturn(createResponse(202, instanceId, resumeRequestId)); + + //prepare mocks for get resume status + when(restMso.GetForObject(eq("/orchestrationRequests/v7/" + resumeRequestId), eq(AsyncRequestStatus.class))) + .thenReturn(asyncRequestStatusResponseAsRestObject(IN_PROGRESS_STR), + asyncRequestStatusResponseAsRestObject(IN_PROGRESS_STR), + asyncRequestStatusResponseAsRestObject(COMPLETE_STR)); + + + UUID jobUUID = asyncInstantiationBL.pushBulkJob(generateResumeMacroPayload(), userId).get(0); + processJobsCountTimesAndAssertStatus(jobUUID, 20, COMPLETED); + verify(restMso).GetForObject( + eq("/orchestrationRequests/v7?filter=serviceInstanceId:EQUALS:" + instanceId), + eq(AsyncRequestStatusList.class)); + verify(restMso).restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), isNull(), eq(String.format("/orchestrationRequests/v7/%s/resume", originalRequestId)), eq(Optional.of(userId))); + verify(restMso, times(3)).GetForObject(eq("/orchestrationRequests/v7/" + resumeRequestId), eq(AsyncRequestStatus.class)); + } + + @Test + public void givenResumeRequest_whenMsoReturnBadResponse_thanJobIsFailed() throws IOException { + //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 createAsyncRequestStatusListByInstanceId() throws IOException { + AsyncRequestStatusList asyncRequestStatusList = TestUtils.readJsonResourceFileAsObject( + "/payload_jsons/resume/msoResponseGetRequestsOfServiceInstance.json", + AsyncRequestStatusList.class); + RestObject getRequestByIdResponse = new RestObject<>(); + getRequestByIdResponse.set(asyncRequestStatusList); + getRequestByIdResponse.setStatusCode(200); + return getRequestByIdResponse; + } + + private ServiceInstantiation generateResumeMacroPayload() throws IOException { + return TestUtils.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 + String replaceRequestId = randomUuid(); + String userId = "az2016"; + + + //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)); + + + 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); + processJobsCountTimesAndAssertStatus(jobUUID, 20, COMPLETED); + + + + JsonNode expectedJson = TestUtils.readJsonResourceFileAsObject("/payload_jsons/vfmodule/replace_vfmodule.json", JsonNode.class); + ArgumentCaptor 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)); + } + + private ServiceInstantiation generateReplaceVfModulePayload() throws IOException { + return TestUtils.readJsonResourceFileAsObject("/payload_jsons/vfmodule/replace_vfmodule_fe_input.json", ServiceInstantiation.class); + } } diff --git a/vid-app-common/src/test/java/org/onap/vid/job/impl/DeleteOldJobsSchedulerInitializerTest.java b/vid-app-common/src/test/java/org/onap/vid/job/impl/DeleteOldJobsSchedulerInitializerTest.java new file mode 100644 index 000000000..4944efa69 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/job/impl/DeleteOldJobsSchedulerInitializerTest.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.vid.job.impl; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.matchesPattern; +import static org.mockito.Mockito.mock; +import static org.onap.vid.testUtils.TestUtils.testWithSystemProperty; +import static org.testng.Assert.assertEquals; + +import org.onap.vid.job.JobsBrokerService; +import org.quartz.JobDetail; +import org.quartz.impl.triggers.CronTriggerImpl; +import org.testng.annotations.Test; + +public class DeleteOldJobsSchedulerInitializerTest { + + @Test + public void testCreateJobDetail() throws Exception { + testWithSystemProperty("vid.asyncJob.howLongToKeepOldJobsInDays", "7", ()-> { + JobsBrokerService mockBroker = mock(JobsBrokerService.class); + DeleteOldJobsSchedulerInitializer underTest = new DeleteOldJobsSchedulerInitializer(mockBroker, null); + JobDetail jobDetail = underTest.createJobDetail(); + assertEquals(DeleteOldJobsWorker.class, jobDetail.getJobClass()); + assertEquals(mockBroker, jobDetail.getJobDataMap().get("jobsBrokerService")); + assertEquals(604800L, jobDetail.getJobDataMap().get("secondsAgo")); + }); + } + + @Test + public void testCreateTrigger() { + DeleteOldJobsSchedulerInitializer underTest = new DeleteOldJobsSchedulerInitializer(null, null); + CronTriggerImpl trigger = (CronTriggerImpl) underTest.createTrigger(); + assertThat(trigger.getCronExpression(), matchesPattern("0 [1-5]?[0-9] 6 \\? \\* \\*")); + } + +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/job/impl/DeleteOldJobsWorkerTest.java b/vid-app-common/src/test/java/org/onap/vid/job/impl/DeleteOldJobsWorkerTest.java new file mode 100644 index 000000000..229e0cab1 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/job/impl/DeleteOldJobsWorkerTest.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * VID + * ================================================================================ + * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.vid.job.impl; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import org.onap.vid.job.JobsBrokerService; +import org.quartz.JobExecutionException; +import org.testng.annotations.Test; + +public class DeleteOldJobsWorkerTest { + + @Test + public void whenExecuteInternal_thenCallToDeleteOldFinalJobs() throws JobExecutionException { + JobsBrokerService mockBroker = mock(JobsBrokerService.class); + long secondsAgo = 42L; + DeleteOldJobsWorker underTest = new DeleteOldJobsWorker(); + underTest.setJobsBrokerService(mockBroker); + underTest.setSecondsAgo(secondsAgo); + underTest.executeInternal(null); + verify(mockBroker).deleteOldFinalJobs(secondsAgo); + } + +} diff --git a/vid-app-common/src/test/java/org/onap/vid/job/impl/JobAdapterTest.java b/vid-app-common/src/test/java/org/onap/vid/job/impl/JobAdapterTest.java index f6785c37d..4e11b7e8b 100644 --- a/vid-app-common/src/test/java/org/onap/vid/job/impl/JobAdapterTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/job/impl/JobAdapterTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -26,10 +26,15 @@ import org.onap.vid.job.Job; import org.onap.vid.job.JobAdapter; import org.onap.vid.job.JobType; import org.onap.vid.job.command.JobCommandFactoryTest; +import org.onap.vid.properties.Features; +import org.onap.vid.testUtils.TestUtils; import org.testng.annotations.Test; +import org.togglz.core.manager.FeatureManager; import java.util.UUID; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotEquals; import static org.testng.AssertJUnit.assertNotNull; @@ -38,12 +43,14 @@ public class JobAdapterTest { @Test public void testCreateServiceInstantiationJob() { - JobAdapter jobAdapter = new JobAdapterImpl(); + FeatureManager featureManager = mock(FeatureManager.class); + JobAdapter jobAdapter = new JobAdapterImpl(featureManager); JobType jobType = JobType.NoOp; JobAdapter.AsyncJobRequest request = new JobCommandFactoryTest.MockedRequest(42,"nothing"); UUID templateId = UUID.randomUUID(); String userId = "ou012t"; + String testApi = "VNF_API"; String optimisticUniqueServiceInstanceName = "optimisticUniqueServiceInstanceName"; int indexInBulk = RandomUtils.nextInt(); Job job = jobAdapter.createServiceInstantiationJob( @@ -51,6 +58,7 @@ public class JobAdapterTest { request, templateId, userId, + testApi, optimisticUniqueServiceInstanceName, indexInBulk ); @@ -59,6 +67,7 @@ public class JobAdapterTest { assertEquals(job.getSharedData().getRequest(), request); assertEquals(job.getSharedData().getRequestType(), request.getClass()); assertEquals(job.getSharedData().getUserId(), userId); + assertEquals(job.getSharedData().getTestApi(), testApi); assertEquals(job.getSharedData().getJobUuid(), job.getUuid()); assertEquals(job.getSharedData().getRootJobId(), job.getUuid()); assertNotNull(job.getUuid()); @@ -68,13 +77,16 @@ public class JobAdapterTest { assertEquals(job.getStatus(), Job.JobStatus.PENDING); } - @Test - public void testCreateChildJob() { - - JobAdapter jobAdapter = new JobAdapterImpl(); + @Test(dataProvider = "trueAndFalse", dataProviderClass = TestUtils.class) + public void testCreateChildJob(boolean isFlagExpCreateResourcesInParallel) { + FeatureManager featureManager = mock(FeatureManager.class); + when(featureManager.isActive(Features.FLAG_EXP_CREATE_RESOURCES_IN_PARALLEL)).thenReturn(isFlagExpCreateResourcesInParallel); + Job.JobStatus expectedJobStatus = isFlagExpCreateResourcesInParallel ? Job.JobStatus.CREATING : Job.JobStatus.PENDING_RESOURCE; + JobAdapter jobAdapter = new JobAdapterImpl(featureManager); UUID templateId = UUID.randomUUID(); String userId = "ou012t"; + String testApi = "VNF_API"; String optimisticUniqueServiceInstanceName = "optimisticUniqueServiceInstanceName"; int indexInBulk = RandomUtils.nextInt(); Job grandJob = jobAdapter.createServiceInstantiationJob( @@ -82,39 +94,44 @@ public class JobAdapterTest { new JobCommandFactoryTest.MockedRequest(99, "anything"), templateId, userId, + testApi, optimisticUniqueServiceInstanceName, indexInBulk ); - Job.JobStatus jobStatus = Job.JobStatus.PAUSE; JobType jobType = JobType.NoOp; JobAdapter.AsyncJobRequest request = new JobCommandFactoryTest.MockedRequest(42,"nothing"); - Job parentJob = jobAdapter.createChildJob(jobType, jobStatus, request, grandJob.getSharedData(), ImmutableMap.of()); + Job parentJob = jobAdapter.createChildJob(jobType, request, grandJob.getSharedData(), ImmutableMap.of(), 1); assertEquals(parentJob.getType(), jobType); assertEquals(parentJob.getSharedData().getRequest(), request); assertEquals(parentJob.getSharedData().getRequestType(), request.getClass()); assertEquals(parentJob.getSharedData().getUserId(), userId); + assertEquals(parentJob.getSharedData().getTestApi(), testApi); assertEquals(parentJob.getSharedData().getJobUuid(), parentJob.getUuid()); assertNotNull(parentJob.getUuid()); assertNotEquals(parentJob.getUuid(), grandJob.getUuid()); - assertEquals(parentJob.getStatus(), jobStatus); + assertEquals(parentJob.getStatus(), expectedJobStatus); + assertEquals(parentJob.getTemplateId(), grandJob.getUuid()); + assertEquals(parentJob.getIndexInBulk().intValue(), 1); assertEquals(parentJob.getSharedData().getRootJobId(), grandJob.getUuid()); - Job.JobStatus jobStatus2 = Job.JobStatus.IN_PROGRESS; JobType jobType2 = JobType.AggregateState; JobAdapter.AsyncJobRequest request2 = new JobCommandFactoryTest.MockedRequest(66,"abc"); - Job job = jobAdapter.createChildJob(jobType2, jobStatus2, request2, parentJob.getSharedData(), ImmutableMap.of()); + Job job = jobAdapter.createChildJob(jobType2, request2, parentJob.getSharedData(), ImmutableMap.of(), 0); assertEquals(job.getType(), jobType2); assertEquals(job.getSharedData().getRequest(), request2); assertEquals(job.getSharedData().getRequestType(), request2.getClass()); assertEquals(job.getSharedData().getUserId(), userId); + assertEquals(job.getSharedData().getTestApi(), testApi); assertEquals(job.getSharedData().getJobUuid(), job.getUuid()); assertNotNull(job.getUuid()); assertNotEquals(job.getUuid(), parentJob.getUuid()); - assertEquals(job.getStatus(), jobStatus2); + assertEquals(job.getStatus(), expectedJobStatus); assertEquals(job.getSharedData().getRootJobId(), grandJob.getUuid()); + assertEquals(job.getTemplateId(), parentJob.getUuid()); + assertEquals(job.getIndexInBulk().intValue(), 0); } } diff --git a/vid-app-common/src/test/java/org/onap/vid/job/impl/JobWorkerTest.java b/vid-app-common/src/test/java/org/onap/vid/job/impl/JobWorkerTest.java index dc44d1520..e234ee969 100644 --- a/vid-app-common/src/test/java/org/onap/vid/job/impl/JobWorkerTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/job/impl/JobWorkerTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -33,6 +33,7 @@ import org.onap.vid.job.command.HttpCallCommand; import org.onap.vid.job.command.JobCommandFactory; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import org.togglz.core.manager.FeatureManager; import java.util.Map; import java.util.UUID; @@ -51,6 +52,9 @@ public class JobWorkerTest { @Mock private JobCommandFactory jobCommandFactory; + @Mock + private FeatureManager featureManager; + private final JobCommand jobCommand = mock(JobCommand.class); private Job jobUnderTest; private JobAdapter.AsyncJobRequest originalData; @@ -68,11 +72,12 @@ public class JobWorkerTest { }; originalType = JobType.MacroServiceInstantiation; - jobUnderTest = new JobAdapterImpl().createServiceInstantiationJob( + jobUnderTest = new JobAdapterImpl(featureManager).createServiceInstantiationJob( originalType, originalData, UUID.randomUUID(), "my user id", + "VNF_API", "optimisticUniqueServiceInstanceName", RandomUtils.nextInt() ); @@ -119,4 +124,4 @@ public class JobWorkerTest { assertThat(nextJob, jobMatcher); assertThat(jobAfter, equalTo(jobBefore)); } -} +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/model/JobAuditStatusTest.java b/vid-app-common/src/test/java/org/onap/vid/model/JobAuditStatusTest.java index 2c41120ad..2f9e31ea6 100644 --- a/vid-app-common/src/test/java/org/onap/vid/model/JobAuditStatusTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/model/JobAuditStatusTest.java @@ -35,11 +35,11 @@ public class JobAuditStatusTest { @DataProvider public static Object[][] AdditionalInfoSizes() { return new Object[][]{ - {5, 5}, - {1999,1999}, - {2000, 2000}, - {2001, 2000}, - {10000, 2000} + {5, 5}, + {1999,1999}, + {2000, 2000}, + {2001, 2000}, + {10000, 2000} }; } @@ -53,7 +53,7 @@ public class JobAuditStatusTest { @Test(dataProvider = "AdditionalInfoSizes") public void testAdditionalInfoMaxLengthInConstructor(int originalSize, int finalSize) { final String additionalInfo = StringUtils.repeat("a", originalSize); - JobAuditStatus jobAuditStatus = new JobAuditStatus(UUID.randomUUID(), "myJobStatus", JobAuditStatus.SourceStatus.MSO, UUID.randomUUID(), additionalInfo, new Date()); + JobAuditStatus jobAuditStatus = JobAuditStatus.createForTest(UUID.randomUUID(), "myJobStatus", JobAuditStatus.SourceStatus.MSO, UUID.randomUUID(), additionalInfo, new Date()); assertThat(jobAuditStatus.getAdditionalInfo().length(), is(finalSize)); } diff --git a/vid-app-common/src/test/java/org/onap/vid/model/aaiTree/VpnBindingKtTest.kt b/vid-app-common/src/test/java/org/onap/vid/model/aaiTree/VpnBindingKtTest.kt new file mode 100644 index 000000000..90c61d759 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/model/aaiTree/VpnBindingKtTest.kt @@ -0,0 +1,16 @@ +package org.onap.vid.model.aaiTree + +import org.testng.Assert.assertEquals +import org.testng.annotations.Test + +class VpnBindingKtTest { + + @Test + fun whenFailedToParseRouteTarget_DefaultValuesAreReturned() { + val aaiTreeNode = AAITreeNode(); + aaiTreeNode.type = NodeType.VPN_BINDING + aaiTreeNode.additionalProperties["route-targets"] = 3 //just an object that can't be parsed into list of route targets + val vpnBinding = from(aaiTreeNode); + assertEquals(vpnBinding.routeTargets, listOf(RouteTarget("ParsingFailure", "ParsingFailure"))) + } +} \ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java index 207e63579..4ddbc0f41 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java @@ -21,91 +21,83 @@ package org.onap.vid.mso; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.tuple; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.hasEntry; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.endsWith; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isA; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.onap.vid.controller.MsoController.CONFIGURATION_ID; +import static org.onap.vid.controller.MsoController.REQUEST_TYPE; +import static org.onap.vid.controller.MsoController.SVC_INSTANCE_ID; +import static org.onap.vid.controller.MsoController.VNF_INSTANCE_ID; +import static org.onap.vid.mso.MsoBusinessLogicImpl.validateEndpointPath; + import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; import com.google.gson.Gson; import io.joshworks.restclient.http.HttpResponse; +import java.io.IOException; +import java.net.URL; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Collectors; +import javax.ws.rs.BadRequestException; import org.apache.commons.io.IOUtils; import org.jetbrains.annotations.NotNull; -import org.mockito.hamcrest.MockitoHamcrest; -import org.onap.vid.changeManagement.WorkflowRequestDetail; -import org.onap.vid.model.SOWorkflowList; -import org.onap.vid.model.probes.ExternalComponentStatus; -import org.onap.vid.mso.rest.RequestList; -import org.onap.vid.mso.rest.RequestWrapper; -import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; import org.mockito.ArgumentMatcher; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.mockito.hamcrest.MockitoHamcrest; import org.onap.portalsdk.core.util.SystemProperties; import org.onap.vid.changeManagement.ChangeManagementRequest; +import org.onap.vid.changeManagement.WorkflowRequestDetail; import org.onap.vid.controller.OperationalEnvironmentController; import org.onap.vid.exceptions.GenericUncheckedException; -import org.onap.vid.model.RequestReferencesContainer; +import org.onap.vid.model.SOWorkflowList; import org.onap.vid.model.SoftDeleteRequest; +import org.onap.vid.model.probes.ExternalComponentStatus; import org.onap.vid.mso.model.CloudConfiguration; import org.onap.vid.mso.model.ModelInfo; import org.onap.vid.mso.model.OperationalEnvironmentActivateInfo; import org.onap.vid.mso.model.OperationalEnvironmentDeactivateInfo; import org.onap.vid.mso.model.RequestInfo; import org.onap.vid.mso.model.RequestParameters; -import org.onap.vid.mso.model.RequestReferences; import org.onap.vid.mso.rest.OperationalEnvironment.OperationEnvironmentRequestDetails; import org.onap.vid.mso.rest.Request; import org.onap.vid.mso.rest.RequestDetails; import org.onap.vid.mso.rest.RequestDetailsWrapper; +import org.onap.vid.mso.rest.RequestList; +import org.onap.vid.mso.rest.RequestWrapper; import org.onap.vid.mso.rest.Task; -import org.onap.vid.properties.Features; import org.springframework.http.HttpStatus; import org.springframework.test.context.ContextConfiguration; -import org.togglz.core.manager.FeatureManager; - -import javax.ws.rs.BadRequestException; -import java.io.IOException; -import java.net.URL; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.tuple; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.hamcrest.Matchers.allOf; -import static org.hamcrest.Matchers.hasEntry; -import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.argThat; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.isA; -import static org.mockito.ArgumentMatchers.endsWith; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.onap.vid.controller.MsoController.CONFIGURATION_ID; -import static org.onap.vid.controller.MsoController.REQUEST_TYPE; -import static org.onap.vid.controller.MsoController.SVC_INSTANCE_ID; -import static org.onap.vid.controller.MsoController.VNF_INSTANCE_ID; -import static org.onap.vid.mso.MsoBusinessLogicImpl.validateEndpointPath; +import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; @ContextConfiguration(classes = {SystemProperties.class}) public class MsoBusinessLogicImplTest extends AbstractTestNGSpringContextTests { private static final ObjectMapper objectMapper = new ObjectMapper(); - @Mock - private FeatureManager featureManager; - @Mock private MsoInterface msoInterface; @@ -126,7 +118,7 @@ public class MsoBusinessLogicImplTest extends AbstractTestNGSpringContextTests { @BeforeClass public void setUp() { MockitoAnnotations.initMocks(this); - msoBusinessLogic = new MsoBusinessLogicImpl(msoInterface, featureManager); + msoBusinessLogic = new MsoBusinessLogicImpl(msoInterface); } @Test @@ -282,39 +274,48 @@ public class MsoBusinessLogicImplTest extends AbstractTestNGSpringContextTests { assertThat(response).isEqualToComparingFieldByField(expectedResponse); } - @Test - public void shouldProperlyDeleteSvcInstanceWithProperParametersAndFalseFeatureFlag() { + @DataProvider + public Object[][] deleteSvcInstanceShouldDelete() { + return new Object[][]{{"Active"}, {"unexpected-status"}}; + } + + @DataProvider + public Object[][] deleteSvcInstanceShouldUnassign() { + return new Object[][]{{"Created"}, {"Pendingdelete"}, {"pending-Delete"}, {"Assigned"}}; + } + + + @Test(dataProvider = "deleteSvcInstanceShouldDelete") + public void shouldProperlyDeleteSvcInstanceWithProperParametersShouldDelete(String status) { // given - String endpointTemplate = "/serviceInstances/v5/%s"; + String endpointTemplate = "/serviceInstantiation/v7/serviceInstances/%s"; String serviceInstanceId = "3f93c7cb-2fd0-4557-9514-e189b7b04f9d"; String svcEndpoint = String.format(endpointTemplate, serviceInstanceId); RequestDetails requestDetails = new RequestDetails(); MsoResponseWrapper expectedResponse = createOkResponse(); given(msoInterface.deleteSvcInstance(requestDetails, svcEndpoint)).willReturn(expectedResponse); - given(featureManager.isActive(Features.FLAG_UNASSIGN_SERVICE)).willReturn(false); // when MsoResponseWrapper msoResponseWrapper = msoBusinessLogic - .deleteSvcInstance(requestDetails, serviceInstanceId, "unAssignOrDeleteParams"); + .deleteSvcInstance(requestDetails, serviceInstanceId, status); // then assertThat(msoResponseWrapper).isEqualToComparingFieldByField(expectedResponse); } - @Test - public void shouldProperlyDeleteSvcInstanceWithProperParametersAndTrueFeatureFlag() { + @Test(dataProvider = "deleteSvcInstanceShouldUnassign") + public void shouldProperlyDeleteSvcInstanceWithProperParametersShouldUnassign(String status) { // given - String endpointTemplate = "/serviceInstantiation/v5/serviceInstances/%s/unassign"; + String endpointTemplate = "/serviceInstantiation/v7/serviceInstances/%s/unassign"; String serviceInstanceId = "3f93c7cb-2fd0-4557-9514-e189b7b04f9d"; String svcEndpoint = String.format(endpointTemplate, serviceInstanceId); RequestDetails requestDetails = new RequestDetails(); MsoResponseWrapper expectedResponse = createOkResponse(); given(msoInterface.unassignSvcInstance(requestDetails, svcEndpoint)).willReturn(expectedResponse); - given(featureManager.isActive(Features.FLAG_UNASSIGN_SERVICE)).willReturn(true); // when MsoResponseWrapper msoResponseWrapper = msoBusinessLogic - .deleteSvcInstance(requestDetails, serviceInstanceId, "assigned"); + .deleteSvcInstance(requestDetails, serviceInstanceId, status); // then assertThat(msoResponseWrapper).isEqualToComparingFieldByField(expectedResponse); @@ -323,7 +324,7 @@ public class MsoBusinessLogicImplTest extends AbstractTestNGSpringContextTests { @Test public void shouldProperlyDeleteVnfWithProperParameters() { // when - String endpointTemplate = "/serviceInstances/v5/%s/vnfs/%s"; + String endpointTemplate = "/serviceInstantiation/v7/serviceInstances/%s/vnfs/%s"; String serviceInstanceId = "3f93c7cb-2fd0-4557-9514-e189b7b04f9d"; String vnfInstanceId = "testVnfInstanceTempId"; String vnfEndpoint = String.format(endpointTemplate, serviceInstanceId, vnfInstanceId); @@ -342,7 +343,7 @@ public class MsoBusinessLogicImplTest extends AbstractTestNGSpringContextTests { @Test public void shouldProperlyDeleteVfModuleWithProperParameters() { // when - String endpointTemplate = "/serviceInstances/v7/%s/vnfs/%s/vfModules/%s"; + String endpointTemplate = "/serviceInstantiation/v7/serviceInstances/%s/vnfs/%s/vfModules/%s"; String serviceInstanceId = "3f93c7cb-2fd0-4557-9514-e189b7b04f9d"; String vnfInstanceId = "testVnfInstanceTempId"; String vfModuleId = "testVfModuleId"; @@ -905,58 +906,6 @@ public class MsoBusinessLogicImplTest extends AbstractTestNGSpringContextTests { requestDetails.setModelInfo(modelInfo); } - @Test - public void shouldProperlyDeactivateAndCloudDeleteWithProperParameters() { - // given - String serviceInstanceId = "testServiceId"; - String vnfInstanceId = "testVnfInstanceId"; - String vfModuleInstanceId = "testVfModuleInstanceId"; - RequestDetails requestDetails = new RequestDetails(); - - String path = msoBusinessLogic.getDeactivateAndCloudDeletePath(serviceInstanceId, vnfInstanceId, vfModuleInstanceId); - - RequestReferences requestReferences = new RequestReferences(); - requestReferences.setInstanceId("testInstance"); - requestReferences.setRequestId("testRequest"); - - HttpResponse expectedResponse = HttpResponse.fallback(new RequestReferencesContainer(requestReferences)); - - MsoResponseWrapper2 responseWrapped = new MsoResponseWrapper2<>(expectedResponse); - - given(msoInterface.post(eq(path), any(RequestDetails.class), eq(RequestReferencesContainer.class))).willReturn(expectedResponse); - - // when - MsoResponseWrapper2 response = msoBusinessLogic.deactivateAndCloudDelete(serviceInstanceId, vnfInstanceId, vfModuleInstanceId, requestDetails); - - // then - assertThat(response).isEqualToComparingFieldByField(responseWrapped); - } - - @Test - public void shouldProperlyActivateFabricConfigurationWithProperParameters() { - // given - String serviceInstanceId = "testServiceId"; - RequestDetails requestDetails = new RequestDetails(); - - String path = msoBusinessLogic.getActivateFabricConfigurationPath(serviceInstanceId); - - RequestReferences requestReferences = new RequestReferences(); - requestReferences.setInstanceId("testInstance"); - requestReferences.setRequestId("testRequest"); - - HttpResponse expectedResponse = HttpResponse.fallback(new RequestReferencesContainer(requestReferences)); - - MsoResponseWrapper2 responseWrapped = new MsoResponseWrapper2<>(expectedResponse); - - given(msoInterface.post(eq(path), any(RequestDetails.class), eq(RequestReferencesContainer.class))).willReturn(expectedResponse); - - // when - MsoResponseWrapper2 response = msoBusinessLogic.activateFabricConfiguration(serviceInstanceId, requestDetails); - - // then - assertThat(response).isEqualToComparingFieldByField(responseWrapped); - } - @Test public void shouldProperlyUpdateVnfSoftwareWithProperParameters() { // given diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/MsoOperationalEnvironmentTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/MsoOperationalEnvironmentTest.java index 891192c75..0ea5f2947 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/MsoOperationalEnvironmentTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/MsoOperationalEnvironmentTest.java @@ -25,6 +25,13 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableListMultimap; +import java.io.IOException; +import java.net.URL; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; import org.apache.commons.io.IOUtils; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; @@ -40,17 +47,9 @@ import org.skyscreamer.jsonassert.JSONCompareMode; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import java.io.IOException; -import java.net.URL; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - public class MsoOperationalEnvironmentTest { - private MsoBusinessLogic msoBusinessLogic = new MsoBusinessLogicImpl(null,null); + private MsoBusinessLogic msoBusinessLogic = new MsoBusinessLogicImpl(null); private static final Logger logger = LogManager.getLogger(MsoOperationalEnvironmentTest.class); @Test(dataProvider = "getOperationalEnvironmentActivationPermutations") diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java index d4abfae38..6cf7d487e 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java @@ -38,8 +38,8 @@ import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.Properties; import java.util.UUID; +import org.apache.commons.configuration.PropertiesConfiguration; import org.glassfish.grizzly.http.util.HttpStatus; import org.junit.AfterClass; import org.junit.BeforeClass; @@ -61,7 +61,7 @@ public class MsoRestClientNewTest { private static StubServer server; private static StubServer securedServer; - private static Properties props = new Properties(); + private static PropertiesConfiguration props = new PropertiesConfiguration(); private static String msoCreateServiceInstanceJson; private static String msoScaleOutVfModule; private final static String CREATE_INSTANCE_RESPONSE_STR = @@ -76,7 +76,7 @@ public class MsoRestClientNewTest { @BeforeClass - public static void start() throws IOException { + public static void start() throws Exception { server = new StubServer().run(); securedServer = new StubServer().secured().run(); @@ -109,7 +109,7 @@ public class MsoRestClientNewTest { @Test public void testCreateSvcInstance() throws Exception { - String endpoint = props.getProperty(MsoProperties.MSO_REST_API_CONFIGURATIONS); + String endpoint = props.getString(MsoProperties.MSO_REST_API_CONFIGURATIONS); endpoint = endpoint.replace(MsoController.SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); try (MsoRestClientTestUtil closure = new MsoRestClientTestUtil( server, @@ -122,7 +122,7 @@ public class MsoRestClientNewTest { @Test public void testCreateVnf() throws Exception { - String endpoint = props.getProperty(MsoProperties.MSO_REST_API_VNF_INSTANCE); + String endpoint = props.getString(MsoProperties.MSO_REST_API_VNF_INSTANCE); endpoint = endpoint.replace(MsoController.SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); try (MsoRestClientTestUtil closure = new MsoRestClientTestUtil( server, @@ -136,7 +136,7 @@ public class MsoRestClientNewTest { @Test public void testCreateNwInstance() throws Exception { - String endpoint = props.getProperty(MsoProperties.MSO_REST_API_NETWORK_INSTANCE); + String endpoint = props.getString(MsoProperties.MSO_REST_API_NETWORK_INSTANCE); String nw_endpoint = endpoint.replaceFirst(MsoController.SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); try (MsoRestClientTestUtil closure = new MsoRestClientTestUtil( server, @@ -149,7 +149,7 @@ public class MsoRestClientNewTest { @Test public void testCreateVolumeGroupInstance() throws Exception { - String endpoint = props.getProperty(MsoProperties.MSO_REST_API_VOLUME_GROUP_INSTANCE); + String endpoint = props.getString(MsoProperties.MSO_REST_API_VOLUME_GROUP_INSTANCE); String vnf_endpoint = endpoint.replaceFirst(MsoController.SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); vnf_endpoint = vnf_endpoint.replaceFirst(MsoController.VNF_INSTANCE_ID, SAMPLE_VNF_INSTANCE_ID); try (MsoRestClientTestUtil closure = new MsoRestClientTestUtil( @@ -163,7 +163,7 @@ public class MsoRestClientNewTest { @Test public void testCreateVfModuleInstance() throws Exception { - String endpoint = props.getProperty(MsoProperties.MSO_REST_API_VF_MODULE_INSTANCE); + String endpoint = props.getString(MsoProperties.MSO_REST_API_VF_MODULE_INSTANCE); String partial_endpoint = endpoint.replaceFirst(MsoController.SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); String vf_module_endpoint = partial_endpoint.replaceFirst(MsoController.VNF_INSTANCE_ID, SAMPLE_VNF_INSTANCE_ID); @@ -195,7 +195,7 @@ public class MsoRestClientNewTest { @Ignore @Test public void testDeleteSvcInstance() throws Exception { - String endpoint = props.getProperty(MsoProperties.MSO_REST_API_SVC_INSTANCE); + String endpoint = props.getString(MsoProperties.MSO_REST_API_SVC_INSTANCE); endpoint = endpoint.replaceFirst(MsoController.SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); @@ -211,7 +211,7 @@ public class MsoRestClientNewTest { @Ignore @Test public void testDeleteVnf() throws Exception { - String endpoint = props.getProperty(MsoProperties.MSO_REST_API_VNF_INSTANCE); + String endpoint = props.getString(MsoProperties.MSO_REST_API_VNF_INSTANCE); endpoint = endpoint.replaceFirst(MsoController.SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); try (MsoRestClientTestUtil closure = new MsoRestClientTestUtil( @@ -226,7 +226,7 @@ public class MsoRestClientNewTest { @Ignore @Test public void testDeleteVfModule() throws Exception { - String endpoint = props.getProperty(MsoProperties.MSO_REST_API_VF_MODULE_INSTANCE); + String endpoint = props.getString(MsoProperties.MSO_REST_API_VF_MODULE_INSTANCE); String part_endpoint = endpoint.replaceFirst(MsoController.SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); String vf_modules_endpoint = part_endpoint.replaceFirst(MsoController.VNF_INSTANCE_ID, SAMPLE_VNF_INSTANCE_ID); String delete_vf_endpoint = vf_modules_endpoint + '/' + SAMPLE_VNF_MODULE_ID; @@ -243,7 +243,7 @@ public class MsoRestClientNewTest { @Ignore @Test public void testDeleteVolumeGroupInstance() throws Exception { - String endpoint = props.getProperty(MsoProperties.MSO_REST_API_VOLUME_GROUP_INSTANCE); + String endpoint = props.getString(MsoProperties.MSO_REST_API_VOLUME_GROUP_INSTANCE); String svc_endpoint = endpoint.replaceFirst(MsoController.SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); String vnf_endpoint = svc_endpoint.replaceFirst(MsoController.VNF_INSTANCE_ID, SAMPLE_VNF_INSTANCE_ID); String delete_volume_group_endpoint = vnf_endpoint + "/" + SAMPLE_VNF_MODULE_ID; @@ -260,7 +260,7 @@ public class MsoRestClientNewTest { @Ignore @Test public void testDeleteNwInstance() throws Exception { - String endpoint = props.getProperty(MsoProperties.MSO_REST_API_NETWORK_INSTANCE); + String endpoint = props.getString(MsoProperties.MSO_REST_API_NETWORK_INSTANCE); String svc_endpoint = endpoint.replaceFirst(MsoController.SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); String delete_nw_endpoint = svc_endpoint + "/" + SAMPLE_NETWORK_INSTANCE_ID; @@ -275,7 +275,7 @@ public class MsoRestClientNewTest { @Test public void testGetOrchestrationRequest() { - String p = props.getProperty(MsoProperties.MSO_REST_API_GET_ORC_REQ); + String p = props.getString(MsoProperties.MSO_REST_API_GET_ORC_REQ); String path = p + "/" + SAMPLE_REQUEST_ID; try(MsoRestClientTestUtil closure = new MsoRestClientTestUtil( @@ -289,7 +289,7 @@ public class MsoRestClientNewTest { @Test public void testGetManualTasksByRequestId() { - String p = props.getProperty(MsoProperties.MSO_REST_API_GET_ORC_REQ); + String p = props.getString(MsoProperties.MSO_REST_API_GET_ORC_REQ); String path = p + "/" + UUID.randomUUID(); String validResponse = "" + "{ " @@ -376,7 +376,7 @@ public class MsoRestClientNewTest { @Test public void testSetConfigurationActiveStatus() throws Exception { - String endpoint = "/serviceInstances/v5//configurations/"; + String endpoint = "/serviceInstances/v7//configurations/"; endpoint = endpoint.replace(MsoController.SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); endpoint = endpoint.replace(MsoController.CONFIGURATION_ID, SAMPLE_CONFIGURATION_ID); endpoint = endpoint + "/activate"; @@ -448,7 +448,7 @@ public class MsoRestClientNewTest { @Test public void testRemoveRelationshipFromServiceInstance() throws Exception { - String serviceEndpoint = props.getProperty(MsoProperties.MSO_REST_API_SVC_INSTANCE); + String serviceEndpoint = props.getString(MsoProperties.MSO_REST_API_SVC_INSTANCE); String removeRelationshipsPath = serviceEndpoint + "/" + SERVICE_INSTANCE_ID + "/removeRelationships"; try (MsoRestClientTestUtil closure = new MsoRestClientTestUtil( @@ -476,7 +476,7 @@ public class MsoRestClientNewTest { } @Test public void testScaleOutVfModule() throws IOException { - String serviceEndpoint = props.getProperty(MsoProperties.MSO_REST_API_VF_MODULE_SCALE_OUT); + String serviceEndpoint = props.getString(MsoProperties.MSO_REST_API_VF_MODULE_SCALE_OUT); String partial_endpoint = serviceEndpoint.replaceFirst(SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); String vf_module_endpoint = partial_endpoint.replaceFirst(VNF_INSTANCE_ID, SAMPLE_VNF_INSTANCE_ID); try (MsoRestClientTestUtil closure = new MsoRestClientTestUtil( diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/RequestDetailsTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/RequestDetailsTest.java index 575ceab7c..7f30b0f2d 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/RequestDetailsTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/RequestDetailsTest.java @@ -20,23 +20,24 @@ package org.onap.vid.mso.rest; +import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanEqualsExcluding; +import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSettersExcluding; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.testng.AssertJUnit.assertEquals; + import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; +import java.util.Collections; +import java.util.List; +import java.util.Map; import org.assertj.core.api.AssertionsForClassTypes; import org.onap.vid.exceptions.NotFoundException; +import org.onap.vid.testUtils.TestUtils; +import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanEqualsExcluding; -import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSettersExcluding; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.testng.AssertJUnit.assertEquals; - public class RequestDetailsTest { @@ -48,6 +49,10 @@ public class RequestDetailsTest { private static final ImmutableList LCP_CLOUD_REGION_ID_PATH = ImmutableList.of("requestDetails", "cloudConfiguration", "lcpCloudRegionId"); + @BeforeClass + public static void registerValueGenerator() { + TestUtils.registerCloudConfigurationValueGenerator(); + } @BeforeMethod public void setUp() { diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AAITreeNodeBuilderTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AAITreeNodeBuilderTest.java index 9cd9ebae8..c2a3f5d61 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/AAITreeNodeBuilderTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/AAITreeNodeBuilderTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,77 +20,100 @@ package org.onap.vid.services; +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.util.concurrent.MoreExecutors; + +import org.apache.commons.lang3.tuple.Pair; +import org.jetbrains.annotations.NotNull; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.mockito.stubbing.Answer; import org.onap.vid.aai.AaiClientInterface; +import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Relationship; +import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.RelationshipList; +import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.model.aaiTree.AAITreeNode; +import org.onap.vid.model.aaiTree.NodeType; +import org.onap.vid.mso.model.CloudConfiguration; +import org.onap.vid.utils.Tree; import org.onap.vid.utils.Unchecked; -import org.testng.Assert; -import org.testng.annotations.BeforeTest; +import org.onap.vid.testUtils.TestUtils; +import org.springframework.http.HttpMethod; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.io.IOException; import java.util.HashMap; -import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.List; +import java.util.Map; +import java.util.Optional; import java.util.concurrent.ConcurrentSkipListSet; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import static java.util.Comparator.comparing; +import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals; +import static net.javacrumbs.jsonunit.core.Option.IGNORING_ARRAY_ORDER; +import static net.javacrumbs.jsonunit.core.Option.IGNORING_EXTRA_FIELDS; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; import static org.onap.vid.services.AAIServiceTree.AAI_TREE_PATHS; +import static org.onap.vid.utils.KotlinUtilsKt.JACKSON_OBJECT_MAPPER; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; public class AAITreeNodeBuilderTest { - AAITreeNodeBuilder aaiTreeNodeBuilder; + private AAITreeNodeBuilder aaiTreeNodeBuilder; @Mock - AaiClientInterface aaiClientMock; + private AaiClientInterface aaiClientMock; - @Mock - ThreadPoolExecutor threadPoolMock; + private ExecutorService executorService; + private static final ObjectMapper mapper = new ObjectMapper(); - @BeforeTest + @BeforeClass public void initMocks() { MockitoAnnotations.initMocks(this); aaiTreeNodeBuilder = new AAITreeNodeBuilder(aaiClientMock); + executorService = MoreExecutors.newDirectExecutorService(); } - @Test - public void buildNode_buildGroupNode_NodeIsAsExpected(){ + private void buildNodeAndAssert(JsonNode inputNode, AAITreeNode expectedNode, NodeType nodeType){ ConcurrentSkipListSet nodesAccumulator = new ConcurrentSkipListSet<>(comparing(AAITreeNode::getUniqueNodeKey)); - ConcurrentLinkedQueue visitedNodes = new ConcurrentLinkedQueue<>(); - when(aaiClientMock.typedAaiGet(Unchecked.toURI("anyUrl"), JsonNode.class)).thenReturn(createGroupJson()); - - AAITreeNode groupNode = aaiTreeNodeBuilder.buildNode("instance-group", + when(aaiClientMock.typedAaiRest(Unchecked.toURI("anyUrl"), JsonNode.class, null, HttpMethod.GET, false)).thenReturn(inputNode); + AAITreeNode actualNode = aaiTreeNodeBuilder.buildNode( + nodeType, "anyUrl", + null, + HttpMethod.GET, nodesAccumulator, - threadPoolMock, - visitedNodes, - new AtomicInteger(0), - AAI_TREE_PATHS).get(0); - - AAITreeNode expectedGroupNode = createExpectedGroupNode(); - assertNodeIsAsExpected(expectedGroupNode,groupNode); + executorService, + AAI_TREE_PATHS.getSubTree(new AAIServiceTree.AaiRelationship(nodeType)) + ).get(0); + assertThat(actualNode, jsonEquals(expectedNode).when(IGNORING_ARRAY_ORDER, IGNORING_EXTRA_FIELDS).whenIgnoringPaths("relationshipList","children[0].relationshipList")); } - private void assertNodeIsAsExpected(AAITreeNode expectedGroupNode, AAITreeNode groupNode) { - Assert.assertEquals(groupNode.getId(), expectedGroupNode.getId()); - Assert.assertEquals(groupNode.getType(), expectedGroupNode.getType()); - Assert.assertEquals(groupNode.getName(), expectedGroupNode.getName()); - Assert.assertEquals(groupNode.getModelVersionId(), expectedGroupNode.getModelVersionId()); - Assert.assertEquals(groupNode.getModelInvariantId(), expectedGroupNode.getModelInvariantId()); - Assert.assertEquals(groupNode.getInMaint(), expectedGroupNode.getInMaint()); - Assert.assertEquals(groupNode.getAdditionalProperties(), expectedGroupNode.getAdditionalProperties()); + @Test + public void buildNode_buildGroupNode_NodeIsAsExpected() { + buildNodeAndAssert(createGroupJson(), createExpectedGroupNode(), NodeType.INSTANCE_GROUP); } private AAITreeNode createExpectedGroupNode() { AAITreeNode expectedNode = new AAITreeNode(); expectedNode.setId("c4fcf022-31a0-470a-b5b8-c18335b7af32"); - expectedNode.setType("instance-group"); + expectedNode.setType(NodeType.INSTANCE_GROUP); expectedNode.setName("Test vE-Flex"); expectedNode.setModelVersionId("Test vE-Flex"); expectedNode.setModelInvariantId("dd182d7d-6949-4b90-b3cc-5befe400742e"); @@ -103,8 +126,6 @@ public class AAITreeNodeBuilderTest { additionalProperties.put("resource-version","1533315433086"); additionalProperties.put("instance-group-function","vTSBC Customer Landing Network Collection"); expectedNode.setAdditionalProperties(additionalProperties); - - return expectedNode; } @@ -125,22 +146,7 @@ public class AAITreeNodeBuilderTest { " \"inMaint\": \"false\"," + " \"instance-group-function\": \"vTSBC Customer Landing Network Collection\"," + " \"relationship-list\": {" + - " \"relationship\": [{" + - " \"related-to\": \"generic-vnf\"," + - " \"relationship-label\": \"org.onap.relationships.inventory.MemberOf\" ," + - " \"related-link\": \"/aai/v14/network/generic-vnfs/generic-vnf/8c54c369-2876-4423-9b33-80f783f29082\" ," + - " \"relationship-data\": [{" + - " \"relationship-key\": \"generic-vnf.vnf-id\"," + - " \"relationship-value\": \"8c54c369-2876-4423-9b33-80f783f29082\"" + - " }" + - " ]," + - " \"related-to-property\": [{" + - " \"property-key\": \"generic-vnf.vnf-name\"," + - " \"property-value\": \"zrdm5bffad01\"" + - " }" + - " ]" + - " }" + - " ]" + + " \"relationship\": []" + " }" + " }"); } catch (IOException e) { @@ -148,4 +154,363 @@ public class AAITreeNodeBuilderTest { } return groupNode; } + + @Test + public void whenReadNetworkNode_thenNodeIsAsExpected() throws IOException { + JsonNode mockedAaiResponse = TestUtils.readJsonResourceFileAsObject("/getTopology/network.json", JsonNode.class); + + AAITreeNode expectedNetworkNode = new AAITreeNode(); + expectedNetworkNode.setId("94c86b39-bbbf-4027-8120-ff37c6d2493a"); + expectedNetworkNode.setName("AUK51a_oam_calea_net_1"); + expectedNetworkNode.setOrchestrationStatus("Assigned"); + expectedNetworkNode.setModelInvariantId("b9a9b549-0ee4-49fc-b4f2-5edc6701da68"); + expectedNetworkNode.setModelVersionId("77010093-df36-4dcb-8428-c3d02bf3f88d"); + expectedNetworkNode.setModelCustomizationId("e5f33853-f84c-4cdd-99f2-93846957aa18"); + expectedNetworkNode.setType(NodeType.NETWORK); + expectedNetworkNode.setCloudConfiguration(new CloudConfiguration("auk51a", "b530fc990b6d4334bd45518bebca6a51", "att-nc")); + + buildNodeAndAssert(mockedAaiResponse, expectedNetworkNode, NodeType.NETWORK); + } + + @Test + public void whenCloudRegionMissing_otherPlacementFieldsReadAsExpected() throws IOException { + + AAITreeNode node = new AAITreeNode(); + Optional tenantRelationShip = Optional.of( + JACKSON_OBJECT_MAPPER.readValue("{" + + " \"related-to\": \"tenant\"," + + " \"relationship-label\": \"org.onap.relationships.inventory.Uses\"," + + " \"related-link\": \"/aai/v14/cloud-infrastructure/cloud-regions/cloud-region/att-nc/auk51a/tenants/tenant/b530fc990b6d4334bd45518bebca6a51\"," + + " \"relationship-data\": [{" + + " \"relationship-key\": \"cloud-region.cloud-owner\"," + + " \"relationship-value\": \"att-nc\"" + + " }, {" + + " \"relationship-key\": \"tenant.tenant-id\"," + + " \"relationship-value\": \"b530fc990b6d4334bd45518bebca6a51\"" + + " }" + + " ]," + + " \"related-to-property\": [{" + + " \"property-key\": \"tenant.tenant-name\"," + + " \"property-value\": \"ecomp_ispt\"" + + " }" + + " ]" + + " }", Relationship.class) + ); + aaiTreeNodeBuilder.enrichPlacementDataUsingTenantInfo(node, tenantRelationShip); + assertEquals(new CloudConfiguration(null, "b530fc990b6d4334bd45518bebca6a51", "att-nc"), node.getCloudConfiguration()); + } + + @Test + public void whenTenantMissing_otherPlacementFieldsReadAsExpected() throws IOException { + + AAITreeNode node = new AAITreeNode(); + Optional tenantRelationShip = Optional.of( + JACKSON_OBJECT_MAPPER.readValue("{" + + " \"related-to\": \"tenant\"," + + " \"relationship-label\": \"org.onap.relationships.inventory.Uses\"," + + " \"related-link\": \"/aai/v14/cloud-infrastructure/cloud-regions/cloud-region/att-nc/auk51a/tenants/tenant/b530fc990b6d4334bd45518bebca6a51\"," + + " \"relationship-data\": [{" + + " \"relationship-key\": \"cloud-region.cloud-owner\"," + + " \"relationship-value\": \"att-nc\"" + + " }, {" + + " \"relationship-key\": \"cloud-region.cloud-region-id\"," + + " \"relationship-value\": \"auk51a\"" + + " }" + + " ]," + + " \"related-to-property\": [{" + + " \"property-key\": \"tenant.tenant-name\"," + + " \"property-value\": \"ecomp_ispt\"" + + " }" + + " ]" + + " }", Relationship.class) + ); + aaiTreeNodeBuilder.enrichPlacementDataUsingTenantInfo(node, tenantRelationShip); + assertEquals(new CloudConfiguration("auk51a", null, "att-nc"), node.getCloudConfiguration()); + } + + @Test + public void whenCloudOwnerMissing_otherPlacementFieldsReadAsExpected() throws IOException { + + AAITreeNode node = new AAITreeNode(); + Optional tenantRelationShip = Optional.of( + JACKSON_OBJECT_MAPPER.readValue("{" + + " \"related-to\": \"tenant\"," + + " \"relationship-label\": \"org.onap.relationships.inventory.Uses\"," + + " \"related-link\": \"/aai/v14/cloud-infrastructure/cloud-regions/cloud-region/att-nc/auk51a/tenants/tenant/b530fc990b6d4334bd45518bebca6a51\"," + + " \"relationship-data\": [{" + + " \"relationship-key\": \"tenant.tenant-id\"," + + " \"relationship-value\": \"b530fc990b6d4334bd45518bebca6a51\"" + + " }, {" + + " \"relationship-key\": \"cloud-region.cloud-region-id\"," + + " \"relationship-value\": \"auk51a\"" + + " }" + + " ]," + + " \"related-to-property\": [{" + + " \"property-key\": \"tenant.tenant-name\"," + + " \"property-value\": \"ecomp_ispt\"" + + " }" + + " ]" + + " }", Relationship.class) + ); + aaiTreeNodeBuilder.enrichPlacementDataUsingTenantInfo(node, tenantRelationShip); + assertEquals(new CloudConfiguration("auk51a", "b530fc990b6d4334bd45518bebca6a51", null), node.getCloudConfiguration()); + } + + @Test + public void whenThereIsNoTenantRelationship_thenPlacementIsNull() throws IOException { + AAITreeNode node = new AAITreeNode(); + aaiTreeNodeBuilder.enrichPlacementData(node); + assertNull(node.getCloudConfiguration()); + } + + + @Test + public void whenReadVnfNodeWithVfModule_thenNodeIsAsExpected() throws IOException { + JsonNode mockedAaiGetVnfResponse = TestUtils.readJsonResourceFileAsObject("/getTopology/vnf.json", JsonNode.class); + + //add mock for vfModule of the VNF + JsonNode mockedAaiGetVfModuleResponse = TestUtils.readJsonResourceFileAsObject("/getTopology/vfModule.json", JsonNode.class); + when(aaiClientMock.typedAaiGet(Unchecked.toURI("anyUrl/vf-modules"), JsonNode.class)).thenReturn(mockedAaiGetVfModuleResponse); + + CloudConfiguration expectedCloudConfiguration = new CloudConfiguration("dyh3b", "c8035f5ee95d4c62bbc8074c044122b9", "irma-aic"); + + AAITreeNode expectedVnfNode = createExpectedVnfTreeNode(expectedCloudConfiguration); + + AAITreeNode expectedVfModule = new AAITreeNode(); + expectedVfModule.setId("2cb6d41e-2bef-4cb2-80ce-c7815bcdcf4e"); + expectedVfModule.setName("dyh3brarf8000v_base"); + expectedVfModule.setOrchestrationStatus("Active"); + expectedVfModule.setModelInvariantId("3ecca473-b0c0-46ae-b0b7-bd2969d8b79f"); + expectedVfModule.setModelVersionId("5c35b764-e266-4498-af87-a88c4ba92dc4"); + expectedVfModule.setModelCustomizationId("06b4ece0-f6f8-4003-b445-653418292101"); + expectedVfModule.setType(NodeType.VF_MODULE); + expectedVfModule.setInMaint(false); + expectedVfModule.setCloudConfiguration(expectedCloudConfiguration); + + expectedVnfNode.addChildren(ImmutableList.of(expectedVfModule)); + + buildNodeAndAssert(mockedAaiGetVnfResponse, expectedVnfNode, NodeType.GENERIC_VNF); + } + + @NotNull + public static AAITreeNode createExpectedVnfTreeNode(CloudConfiguration expectedCloudConfiguration) { + AAITreeNode expectedVnfNode = new AAITreeNode(); + expectedVnfNode.setId("9a7a4dc1-8e5f-43fe-a360-7734c5f51382"); + expectedVnfNode.setName("dyh3brarf8000v"); + expectedVnfNode.setOrchestrationStatus("Active"); + expectedVnfNode.setModelInvariantId("b711997f-36b3-4a9b-8b37-71a0fc2ebd6d"); + expectedVnfNode.setModelVersionId("7f23e4f7-e44c-44df-b066-4cedc6950bfe"); + expectedVnfNode.setModelCustomizationId("401350be-0f56-481c-86d8-f32d573fec26"); + expectedVnfNode.setType(NodeType.GENERIC_VNF); + expectedVnfNode.setInMaint(true); + expectedVnfNode.setProvStatus("PREPROV"); + expectedVnfNode.setCloudConfiguration(expectedCloudConfiguration); + return expectedVnfNode; + } + + @DataProvider + public static Object[][] isArrayDataProvider() { + return new Object[][] { + {"Json Array", buildArrayJson(NodeType.GENERIC_VNF), true}, + {"Json Object", buildOneLevelJson(NodeType.GENERIC_VNF), false}, + {"Json Array with another node type", buildArrayJson(NodeType.SERVICE_INSTANCE), false}, + {"null json", null, false} + }; + } + + @Test(dataProvider = "isArrayDataProvider") + public void IsArrayType(String description, JsonNode jsonNode, boolean expectedResult) { + boolean isArray = aaiTreeNodeBuilder.isArray(jsonNode, NodeType.GENERIC_VNF); + assertEquals(expectedResult, isArray); + } + + @Test + public void jsonToAaiNodeTest() { + NodeType nodeType = NodeType.SERVICE_INSTANCE; + JsonNode node = buildOneLevelJson(nodeType); + ConcurrentSkipListSet nodesAccumulator = new ConcurrentSkipListSet<>(comparing(AAITreeNode::getUniqueNodeKey)); + + AAITreeNode aaiTreeNode = aaiTreeNodeBuilder.createAaiNode(nodeType, node, nodesAccumulator); + + assertEquals("any-instance-id", aaiTreeNode.getId()); + assertEquals("any-instance-name", aaiTreeNode.getName()); + assertTrue(nodesAccumulator.contains(aaiTreeNode)); + } + + @Test + public void getNextLevelInPathsTreeTest() { + Tree firstLevelTree = getPathsTree(); + + Tree secondLevelTree = aaiTreeNodeBuilder.getNextLevelInPathsTree(firstLevelTree, NodeType.GENERIC_VNF.getType()); + assertEquals(NodeType.GENERIC_VNF.getType(), secondLevelTree.getRootValue().type); + + Tree thirdLevelTree = aaiTreeNodeBuilder.getNextLevelInPathsTree(secondLevelTree, NodeType.INSTANCE_GROUP.getType()); + assertEquals(NodeType.INSTANCE_GROUP.getType(), thirdLevelTree.getRootValue().type); + } + + @Test + public void getNextLevelInPathsTreeTest_givenIrrelevantNode_expectedNull() { + Tree pathsTree = getPathsTree(); + + Tree subTree = aaiTreeNodeBuilder.getNextLevelInPathsTree(pathsTree, NodeType.INSTANCE_GROUP.getType()); + + assertNull(subTree); + } + + @Test + public void getRelationships_given2Relationships_expect1filtered() { + NodeType firstRelationship = NodeType.GENERIC_VNF; + NodeType secondRelationship = NodeType.INSTANCE_GROUP; + JsonNode jsonNode = buildOneLevelJson(NodeType.SERVICE_INSTANCE, firstRelationship, secondRelationship); + + List relationships = aaiTreeNodeBuilder.getFilteredRelationships(jsonNode, getPathsTree()); + + assertEquals(1, relationships.size()); + assertEquals(firstRelationship.getType(), relationships.get(0).getRelatedTo()); + } + + @Test + public void getRelationships_givenNoRelationships_expectedEmptyListTest() { + JsonNode jsonNode = buildOneLevelJson(NodeType.SERVICE_INSTANCE); + + List relationships = aaiTreeNodeBuilder.getFilteredRelationships(jsonNode, getPathsTree()); + + assertThat(relationships, is(empty())); + } + + @Test + public void getRelationships_given2RelationshipsNotExistInTreePaths_expectAllFiltered() { + NodeType firstRelationship = NodeType.CONFIGURATION; + NodeType secondRelationship = NodeType.INSTANCE_GROUP; + JsonNode jsonNode = buildOneLevelJson(NodeType.SERVICE_INSTANCE, firstRelationship, secondRelationship); + + List relationships = aaiTreeNodeBuilder.getFilteredRelationships(jsonNode, getPathsTree()); + + assertThat(relationships, is(empty())); + } + + @Test + public void aggregateAllOtherPropertiesTest() { + NodeType nodeType = NodeType.SERVICE_INSTANCE; + JsonNode jsonNode = buildOneLevelJson(nodeType, NodeType.GENERIC_VNF, NodeType.GENERIC_VNF); + ((ObjectNode) jsonNode).put("nf-role", "any-value"); + + Map additionalProps = aaiTreeNodeBuilder.aggregateAllOtherProperties(jsonNode, nodeType); + assertThat(additionalProps, is(ImmutableMap.of( + "nf-role", "any-value"))); + } + + @Test + public void parseNodeAndFilterRelationshipsTest() { + NodeType nodeType = NodeType.SERVICE_INSTANCE; + JsonNode jsonNode = buildOneLevelJson(NodeType.SERVICE_INSTANCE, NodeType.GENERIC_VNF, NodeType.NETWORK, NodeType.VF_MODULE); + ConcurrentSkipListSet nodesAccumulator = new ConcurrentSkipListSet<>(comparing(AAITreeNode::getUniqueNodeKey)); + + Pair> resultNode = aaiTreeNodeBuilder.parseNodeAndFilterRelationships(jsonNode, nodeType, + nodesAccumulator, getPathsTree()); + + assertEquals(nodeType, resultNode.getKey().getType()); + assertEquals(2, resultNode.getValue().size()); + assertEquals(NodeType.GENERIC_VNF.getType(), resultNode.getValue().get(0).getRelatedTo()); + assertEquals(NodeType.NETWORK.getType(), resultNode.getValue().get(1).getRelatedTo()); + } + + @Test(expectedExceptions = GenericUncheckedException.class ,expectedExceptionsMessageRegExp = "AAI node fetching failed.") + public void fetchChildrenAsyncTest_given2children_expected1Ok1Timeout() { + ConcurrentSkipListSet nodesAccumulator = new ConcurrentSkipListSet<>(comparing(AAITreeNode::getUniqueNodeKey)); + ExecutorService threadPool = Executors.newFixedThreadPool(5); + + AAITreeNode rootNode = createExpectedGroupNode(); + JsonNode relationshipJson = getRelationships(NodeType.GENERIC_VNF, NodeType.NETWORK); + List relationships = mapper.convertValue(relationshipJson, RelationshipList.class).getRelationship(); + + when(aaiClientMock.typedAaiRest(Unchecked.toURI(relationships.get(0).getRelatedLink()), JsonNode.class, null, HttpMethod.GET, false)) + .thenReturn(buildOneLevelJson(NodeType.GENERIC_VNF)); + + when(aaiClientMock.typedAaiRest(Unchecked.toURI(relationships.get(1).getRelatedLink()), JsonNode.class, null, HttpMethod.GET, false)) + .thenAnswer((Answer) invocation -> { + Thread.sleep(2000); + return buildOneLevelJson(NodeType.NETWORK); + }); + + aaiTreeNodeBuilder.fetchChildrenAsync(threadPool, nodesAccumulator, rootNode, relationships, getPathsTree(), 1); + + assertEquals(2, rootNode.getChildren().size()); + assertEquals(NodeType.GENERIC_VNF, rootNode.getChildren().get(0).getType()); + assertEquals(NodeType.NETWORK, rootNode.getChildren().get(1).getType()); + } + + @DataProvider + public Object[][] testIsListOfKeyResultsDataProvider() { + return new Object[][]{ + {"Node has results with several values", + "{\"results\":[{\"l3-network\":{}},{\"l3-network\":{}},{\"l3-network\":{}}]}", + true}, + {"Node has results with no values", + "{\"results\":[]}", + true}, + {"Node has results, but it isn't an array", + "{\"results\":{\"some-field\":{}}}", + false}, + {"Node doesn't have results", + "{\"l3-network\":[{},{}]}", + false}, + {"Node is null", + "null", + false}, + }; + } + + @Test(dataProvider = "testIsListOfKeyResultsDataProvider") + public void testIsListOfKeyResults(String testCase, String input, boolean expectedResult) throws IOException { + assertEquals(testCase + ": " + input, + expectedResult, aaiTreeNodeBuilder.isListOfKeyResults(new ObjectMapper().readTree(input))); + } + + private Tree getPathsTree() { + Tree pathsTree = new Tree<>(new AAIServiceTree.AaiRelationship(NodeType.SERVICE_INSTANCE)); + pathsTree.addPath(AAIServiceTree.toAaiRelationshipList(NodeType.GENERIC_VNF, NodeType.INSTANCE_GROUP)); + pathsTree.addPath(AAIServiceTree.toAaiRelationshipList(NodeType.NETWORK)); + + return pathsTree; + } + + private static JsonNode buildOneLevelJson(NodeType nodeType, NodeType...relationships) { + ObjectNode objectNode = mapper.createObjectNode(); + objectNode.put(nodeType.getId(), "any-instance-id"); + objectNode.put(nodeType.getName(), "any-instance-name"); + if (relationships.length > 0 ) { + objectNode.putPOJO("relationship-list", getRelationships(relationships)); + } + return objectNode; + } + + private static JsonNode buildArrayJson(NodeType nodeType) { + ObjectNode objectNode = mapper.createObjectNode(); + ArrayNode arrayNode = objectNode.putArray(nodeType.getType()); + arrayNode.add(buildOneLevelJson(nodeType)); + arrayNode.add(buildOneLevelJson(nodeType)); + + return objectNode; + } + + private static JsonNode getRelationship(String nodeType) { + ObjectNode relationship = mapper.createObjectNode(); + relationship.put("related-to", nodeType); + relationship.put("relationship-label", "org.onap.relationships.inventory.ComposedOf"); + relationship.put("related-link", "/aai/v12/network/" + nodeType + "s/" + nodeType + "/cf6f60cd-808d-44e6-978b-c663e00dba8d"); + return relationship; + } + + private static JsonNode getRelationships(NodeType...nodeTypes) { + ObjectNode relationshipList = mapper.createObjectNode(); + ArrayNode relationships = relationshipList.putArray("relationship"); + + for (NodeType nodeType: nodeTypes) { + relationships.add(getRelationship(nodeType.getType())); + } + + return relationshipList; + } + } diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AaiServiceImplTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AaiServiceImplTest.java index bb47180e4..09a53684f 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/AaiServiceImplTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/AaiServiceImplTest.java @@ -21,16 +21,36 @@ package org.onap.vid.services; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.onap.vid.model.aaiTree.NodeType.SERVICE_INSTANCE; + import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.joshworks.restclient.http.HttpResponse; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import javax.ws.rs.core.Response; import org.apache.http.HttpStatus; import org.jetbrains.annotations.NotNull; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; import org.onap.vid.aai.AaiClientInterface; import org.onap.vid.aai.AaiGetVnfResponse; @@ -70,721 +90,711 @@ import org.onap.vid.model.aaiTree.AAITreeNode; import org.onap.vid.model.aaiTree.RelatedVnf; import org.onap.vid.model.aaiTree.ServiceInstance; import org.onap.vid.roles.RoleValidator; - -import javax.ws.rs.core.Response; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import org.springframework.http.HttpMethod; @RunWith(MockitoJUnitRunner.class) public class AaiServiceImplTest { - private static final String GLOBAL_CUSTOMER_ID = "GLOBAL_CUSTOMER_ID"; - private static final String CLOUD_REGION_ID = "CLOUD_REGION_ID"; - private static final String VNF_TYPE = "VNF_TYPE"; - private static final String TENANT_ID = "TENANT_ID"; - private static final String TENANT_NAME = "TENANT_NAME"; - private static final String SERVICE_TYPE = "SERVICE_TYPE"; - private static final String CORRECT_VALUE = "CORRECT_VALUE"; - private static final String SUBSCRIBER_ID = "SUBSCRIBER_ID_EXPECTED"; - private static final String STATUS_TEXT = "STATUS_TEXT"; - private static final String GLOBAL_SUBSCRIBER_ID = "GLOBAL_SUBSCRIBER_ID"; - private static final String GLOBAL_SUBSCRIBER_ID_NULL_RESPONSE = "ID_NULL"; - private static final String VNF_INSTANCE_ID_OK = "VNF_INSTANCE_ID_OK"; - private static final String VNF_INSTANCE_ID_FAIL = "VNF_INSTANCE_ID_FAIL"; - private static final String PARENT_NAME = "PARENT_NAME"; - private static final String PARENT_ID = "PARENT_ID"; - private static final String INVARIANT_ID = "INVARIANT_ID"; - private static final String GROUP_TYPE_FAILING = "GROUP_TYPE_FAILING"; - private static final String GROUP_ROLE_OK = "GROUP_ROLE_OK"; - private static final String GROUP_ROLE_FAILING = "GROUP_ROLE_FAILING"; - private static final String group_type_ok = "GROUP_TYPE_OK"; - private static final String CLOUD_TYPE = "CLOUD_TYPE"; - - @Mock - private HttpResponse responseAllSubscribers; - @Mock - private AaiResponse aaiResponseOpEnvList; - @Mock - private AaiResponse aaiResponse; - @Mock - private AaiResponse aaiResponseJsonNode; - @Mock - private RoleValidator roleValidator; - - @Mock - private AaiClientInterface aaiClient; - @Mock - private AaiOverTLSClientInterface aaiOverTLSClient; - @Mock - private AaiResponseTranslator aaiResponseTranslator; - @Mock - private AAIServiceTree aaiServiceTree; - - @InjectMocks - private AaiServiceImpl aaiService; - - - @Test - public void shouldGetFullSubscriberListWithoutValidator() { - when(aaiOverTLSClient.getAllSubscribers()).thenReturn(responseAllSubscribers); - - HttpResponse actualResponse = aaiService.getFullSubscriberList(); - - assertThat(actualResponse).isEqualTo(responseAllSubscribers); - } - - @Test - public void shouldGetFullSubscriberListWithValidator() { - Subscriber subscriber = createSubscriber(); - SubscriberList subscriberList = new SubscriberList(Collections.singletonList(subscriber)); - - when(aaiOverTLSClient.getAllSubscribers()).thenReturn(responseAllSubscribers); - when(responseAllSubscribers.getBody()).thenReturn(subscriberList); - when(responseAllSubscribers.getStatusText()).thenReturn(STATUS_TEXT); - when(responseAllSubscribers.getStatus()).thenReturn(HttpStatus.SC_OK); - SubscriberFilteredResults expectedSubscribers = new SubscriberFilteredResults(roleValidator, subscriberList, - STATUS_TEXT, HttpStatus.SC_OK); - - SubscriberFilteredResults actualSubscribers = aaiService.getFullSubscriberList(roleValidator); - - assertThat(actualSubscribers.getHttpCode()).isEqualTo(expectedSubscribers.getHttpCode()); - assertThat(actualSubscribers.getErrorMessage()).isEqualTo(expectedSubscribers.getErrorMessage()); - } - - @Test - public void shouldGetOperationalEnvironments() { - when(aaiClient.getOperationalEnvironments(anyString(), anyString())) - .thenReturn(aaiResponseOpEnvList); - - AaiResponse expectedEnvList = - aaiService.getOperationalEnvironments(anyString(), anyString()); - - assertThat(expectedEnvList).isEqualTo(aaiResponseOpEnvList); - } - - @Test - public void shouldGetSubscriberData() { - Services services = createAaiResponseServices(); - AaiResponse aaiResponseServices = new AaiResponse<>(services, null, HttpStatus.SC_OK); - - when(aaiClient.getSubscriberData(SUBSCRIBER_ID)).thenReturn(aaiResponseServices); - when(roleValidator.isServicePermitted(eq(GLOBAL_CUSTOMER_ID), anyString())).thenReturn(Boolean.TRUE); - - AaiResponse actualResponse = aaiService.getSubscriberData(SUBSCRIBER_ID, roleValidator); - List actualServiceSubscriptions = ((AaiResponse) actualResponse) - .getT().serviceSubscriptions.serviceSubscription; - - assertThat(actualResponse).isEqualTo(aaiResponseServices); - assertThat(actualServiceSubscriptions).allMatch(s -> s.isPermitted); - } - - @Test - public void shouldGetServiceInstanceEmptySearchResults() { - ServiceInstancesSearchResults serviceInstancesSearchResults = new ServiceInstancesSearchResults(); - AaiResponse emptyResponse = new AaiResponse<>(serviceInstancesSearchResults, - null, HttpStatus.SC_OK); - - AaiResponse actualResponse = aaiService.getServiceInstanceSearchResults(null, null, - null, null, null); - - assertThat(actualResponse).isEqualToComparingFieldByFieldRecursively(emptyResponse); - } - - @Test - public void shouldGetVersionByInvariantId() { - Response response = mock(Response.class); - when(aaiClient.getVersionByInvariantId(any())).thenReturn(response); - - Response actualResponse = aaiService.getVersionByInvariantId(any()); - - assertThat(actualResponse).isEqualTo(response); - } - - @Test - public void shouldGetSpecificPnf() { - AaiResponse expectedResponse = new AaiResponse<>(Pnf.builder().build(), null, HttpStatus.SC_OK); - when(aaiClient.getSpecificPnf(anyString())).thenReturn(expectedResponse); - - AaiResponse actualResponse = aaiService.getSpecificPnf(anyString()); - - assertThat(actualResponse).isEqualTo(expectedResponse); - } - - @Test - public void shouldGetPnfData() { - when(aaiClient.getPNFData(anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), - anyString())).thenReturn(aaiResponse); - - AaiResponse actualResponse = aaiService.getPNFData(anyString(), anyString(), anyString(), anyString(), - anyString(), anyString(), anyString()); - - assertThat(actualResponse).isEqualTo(aaiResponse); - } - - @Test - public void shouldGetServices() { - org.onap.vid.aai.model.AaiGetServicesRequestModel.Service s1 = - createService("ID1", "V1", "D1"); - org.onap.vid.aai.model.AaiGetServicesRequestModel.Service s2 = - createService("ID2", "V2", "D2"); - - GetServicesAAIRespone services = new GetServicesAAIRespone(); - services.service = Arrays.asList(s1, s2); - - AaiResponse aaiResponseServices = - new AaiResponse<>(services, null, HttpStatus.SC_OK); - - when(aaiClient.getServices()).thenReturn(aaiResponseServices); - - Object actualObjectOfResponse = aaiService.getServices(roleValidator).getT(); - - assertThat(actualObjectOfResponse).isNotNull(); - assertThat(((GetServicesAAIRespone) actualObjectOfResponse).service).allMatch(s -> s.isPermitted); - } - - @Test - public void shouldGetTenants() { - GetTenantsResponse tenant1 = new GetTenantsResponse("REGION_ID1", "CLOUD_OWNER1", - "TENANT_NAME1", "TENANT_ID1", true); - GetTenantsResponse tenant2 = new GetTenantsResponse("REGION_ID2", "CLOUD_OWNER2", - "TENANT_NAME2", "TENANT_ID2", false); - GetTenantsResponse[] tenants = {tenant1, tenant2}; - AaiResponse aaiGetTenantsResponse = new AaiResponse<>(tenants, - null, HttpStatus.SC_OK); - - when(aaiClient.getTenants(anyString(), anyString())).thenReturn(aaiGetTenantsResponse); - when(roleValidator.isTenantPermitted(anyString(), anyString(), anyString())) - .thenReturn(Boolean.TRUE); - - GetTenantsResponse[] actualResponses = aaiService - .getTenants(anyString(), anyString(), roleValidator).getT(); - - assertThat(actualResponses).isNotNull(); - assertThat(actualResponses.length).isEqualTo(2); - assertThat(actualResponses).allMatch(tenant -> tenant.isPermitted); - } - - @Test - public void shouldGetVNFDataWithoutFiltering() { - when(aaiClient.getVNFData(anyString(), anyString(), anyString())).thenReturn(aaiResponse); - - AaiResponse actualResponse = aaiService.getVNFData(anyString(), anyString(), anyString()); + private static final String GLOBAL_CUSTOMER_ID = "GLOBAL_CUSTOMER_ID"; + private static final String CLOUD_REGION_ID = "CLOUD_REGION_ID"; + private static final String VNF_TYPE = "VNF_TYPE"; + private static final String TENANT_ID = "TENANT_ID"; + private static final String TENANT_NAME = "TENANT_NAME"; + private static final String SERVICE_TYPE = "SERVICE_TYPE"; + private static final String CORRECT_VALUE = "CORRECT_VALUE"; + private static final String SUBSCRIBER_ID = "SUBSCRIBER_ID_EXPECTED"; + private static final String STATUS_TEXT = "STATUS_TEXT"; + private static final String GLOBAL_SUBSCRIBER_ID = "GLOBAL_SUBSCRIBER_ID"; + private static final String GLOBAL_SUBSCRIBER_ID_NULL_RESPONSE = "ID_NULL"; + private static final String VNF_INSTANCE_ID_OK = "VNF_INSTANCE_ID_OK"; + private static final String VNF_INSTANCE_ID_FAIL = "VNF_INSTANCE_ID_FAIL"; + private static final String PARENT_NAME = "PARENT_NAME"; + private static final String PARENT_ID = "PARENT_ID"; + private static final String INVARIANT_ID = "INVARIANT_ID"; + private static final String GROUP_TYPE_FAILING = "GROUP_TYPE_FAILING"; + private static final String GROUP_ROLE_OK = "GROUP_ROLE_OK"; + private static final String GROUP_ROLE_FAILING = "GROUP_ROLE_FAILING"; + private static final String group_type_ok = "GROUP_TYPE_OK"; + private static final String CLOUD_TYPE = "CLOUD_TYPE"; + + @Mock + private HttpResponse responseAllSubscribers; + @Mock + private AaiResponse aaiResponseOpEnvList; + @Mock + private AaiResponse aaiResponse; + @Mock + private AaiResponse aaiResponseJsonNode; + @Mock + private RoleValidator roleValidator; + + @Mock + private AaiClientInterface aaiClient; + @Mock + private AaiOverTLSClientInterface aaiOverTLSClient; + @Mock + private AaiResponseTranslator aaiResponseTranslator; + @Mock + private AAIServiceTree aaiServiceTree; + @Spy + private ExecutorService executorService = Executors.newFixedThreadPool(1); + + @InjectMocks + private AaiServiceImpl aaiService; + + @Test + public void shouldGetFullSubscriberListWithoutValidator() { + when(aaiOverTLSClient.getAllSubscribers()).thenReturn(responseAllSubscribers); + + HttpResponse actualResponse = aaiService.getFullSubscriberList(); + + assertThat(actualResponse).isEqualTo(responseAllSubscribers); + } + + @Test + public void shouldGetFullSubscriberListWithValidator() { + Subscriber subscriber = createSubscriber(); + SubscriberList subscriberList = new SubscriberList(Collections.singletonList(subscriber)); + + when(aaiOverTLSClient.getAllSubscribers()).thenReturn(responseAllSubscribers); + when(responseAllSubscribers.getBody()).thenReturn(subscriberList); + when(responseAllSubscribers.getStatusText()).thenReturn(STATUS_TEXT); + when(responseAllSubscribers.getStatus()).thenReturn(HttpStatus.SC_OK); + SubscriberFilteredResults expectedSubscribers = new SubscriberFilteredResults(roleValidator, subscriberList, + STATUS_TEXT, HttpStatus.SC_OK); + + SubscriberFilteredResults actualSubscribers = aaiService.getFullSubscriberList(roleValidator); + + assertThat(actualSubscribers.getHttpCode()).isEqualTo(expectedSubscribers.getHttpCode()); + assertThat(actualSubscribers.getErrorMessage()).isEqualTo(expectedSubscribers.getErrorMessage()); + } + + @Test + public void shouldGetOperationalEnvironments() { + when(aaiClient.getOperationalEnvironments(anyString(), anyString())) + .thenReturn(aaiResponseOpEnvList); + + AaiResponse expectedEnvList = + aaiService.getOperationalEnvironments(anyString(), anyString()); + + assertThat(expectedEnvList).isEqualTo(aaiResponseOpEnvList); + } + + @Test + public void shouldGetSubscriberData() { + Services services = createAaiResponseServices(); + AaiResponse aaiResponseServices = new AaiResponse<>(services, null, HttpStatus.SC_OK); + + when(aaiClient.getSubscriberData(SUBSCRIBER_ID, false)).thenReturn(aaiResponseServices); + when(roleValidator.isServicePermitted(eq(GLOBAL_CUSTOMER_ID), anyString())).thenReturn(Boolean.TRUE); + + AaiResponse actualResponse = aaiService.getSubscriberData(SUBSCRIBER_ID, roleValidator, false); + List actualServiceSubscriptions = ((AaiResponse) actualResponse) + .getT().serviceSubscriptions.serviceSubscription; + + assertThat(actualResponse).isEqualTo(aaiResponseServices); + assertThat(actualServiceSubscriptions).allMatch(s -> s.isPermitted); + } + + @Test + public void shouldGetServiceInstanceEmptySearchResults() { + ServiceInstancesSearchResults serviceInstancesSearchResults = new ServiceInstancesSearchResults(); + AaiResponse emptyResponse = new AaiResponse<>(serviceInstancesSearchResults, + null, HttpStatus.SC_OK); + + AaiResponse actualResponse = aaiService.getServiceInstanceSearchResults(null, null, + null, null, null); + + assertThat(actualResponse).isEqualToComparingFieldByFieldRecursively(emptyResponse); + } + + @Test + public void shouldGetVersionByInvariantId() { + Response response = mock(Response.class); + when(aaiClient.getVersionByInvariantId(any())).thenReturn(response); + + Response actualResponse = aaiService.getVersionByInvariantId(any()); + + assertThat(actualResponse).isEqualTo(response); + } + + @Test + public void shouldGetSpecificPnf() { + AaiResponse expectedResponse = new AaiResponse<>(Pnf.builder().build(), null, HttpStatus.SC_OK); + when(aaiClient.getSpecificPnf(anyString())).thenReturn(expectedResponse); + + AaiResponse actualResponse = aaiService.getSpecificPnf(anyString()); - assertThat(actualResponse).isEqualTo(aaiResponse); - } + assertThat(actualResponse).isEqualTo(expectedResponse); + } - @Test - public void shouldGetVNFDataWithFiltering() { - VnfResult vnfResult1 = createVnfResult("ID1", "generic-vnf"); - VnfResult vnfResult2 = createVnfResult("ID2", "service-instance"); - VnfResult vnfResult3 = createVnfResult("ID3", "anything-else"); + @Test + public void shouldGetPnfData() { + when(aaiClient.getPNFData(anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), + anyString())).thenReturn(aaiResponse); - List vnfResults = Arrays.asList(vnfResult1, vnfResult2, vnfResult3); - AaiResponse aaiResponseGetVnfResponse = createAaiResponseVnfResponse(vnfResults); + AaiResponse actualResponse = aaiService.getPNFData(anyString(), anyString(), anyString(), anyString(), + anyString(), anyString(), anyString()); - vnfResults = Arrays.asList(vnfResult1, vnfResult2); - AaiResponse expectedResponseWithReturnedVnfs = createAaiResponseVnfResponse(vnfResults); - AaiResponse expectedResponseWithoutReturnedVnfs = new AaiResponse(); + assertThat(actualResponse).isEqualTo(aaiResponse); + } - when(aaiClient.getVNFData(GLOBAL_SUBSCRIBER_ID, SERVICE_TYPE)).thenReturn(aaiResponseGetVnfResponse); - when(aaiClient.getVNFData(GLOBAL_SUBSCRIBER_ID_NULL_RESPONSE, SERVICE_TYPE)).thenReturn(null); + @Test + public void shouldGetServices() { + org.onap.vid.aai.model.AaiGetServicesRequestModel.Service s1 = + createService("ID1", "V1", "D1"); + org.onap.vid.aai.model.AaiGetServicesRequestModel.Service s2 = + createService("ID2", "V2", "D2"); - AaiResponse actualResponseWithReturnedVnfs = - aaiService.getVNFData(GLOBAL_SUBSCRIBER_ID, SERVICE_TYPE); - AaiResponse actualResponseWithoutReturnedVnfs = - aaiService.getVNFData(GLOBAL_SUBSCRIBER_ID_NULL_RESPONSE, SERVICE_TYPE); + GetServicesAAIRespone services = new GetServicesAAIRespone(); + services.service = Arrays.asList(s1, s2); - assertThat(actualResponseWithReturnedVnfs) - .isEqualToComparingFieldByFieldRecursively(expectedResponseWithReturnedVnfs); - assertThat(actualResponseWithoutReturnedVnfs) - .isEqualToComparingFieldByField(expectedResponseWithoutReturnedVnfs); - } + AaiResponse aaiResponseServices = + new AaiResponse<>(services, null, HttpStatus.SC_OK); - @Test - public void shouldGetAaiZones() { - when(aaiClient.getAllAicZones()).thenReturn(aaiResponse); + when(aaiClient.getServices()).thenReturn(aaiResponseServices); - AaiResponse actualResponse = aaiService.getAaiZones(); + Object actualObjectOfResponse = aaiService.getServices(roleValidator).getT(); - assertThat(actualResponse).isEqualTo(aaiResponse); - } - - @Test - public void shouldGetAicZoneForPnf() { - ServiceRelationships relationsService = createServiceRelationships(); - AaiResponse expectedServiceInstanceResp = - new AaiResponse<>(relationsService, null, HttpStatus.SC_OK); - AaiResponse expectedResponse = new AaiResponse<>(CORRECT_VALUE, null, HttpStatus.SC_OK); + assertThat(actualObjectOfResponse).isNotNull(); + assertThat(((GetServicesAAIRespone) actualObjectOfResponse).service).allMatch(s -> s.isPermitted); + } - when(aaiClient.getServiceInstance(anyString(), anyString(), anyString())) - .thenReturn(expectedServiceInstanceResp); + @Test + public void shouldGetTenants() { + GetTenantsResponse tenant1 = new GetTenantsResponse("REGION_ID1", "CLOUD_OWNER1", + "TENANT_NAME1", "TENANT_ID1", true); + GetTenantsResponse tenant2 = new GetTenantsResponse("REGION_ID2", "CLOUD_OWNER2", + "TENANT_NAME2", "TENANT_ID2", false); + GetTenantsResponse[] tenants = {tenant1, tenant2}; + AaiResponse aaiGetTenantsResponse = new AaiResponse<>(tenants, + null, HttpStatus.SC_OK); - AaiResponse actualResponse = aaiService.getAicZoneForPnf(anyString(), anyString(), anyString()); + when(aaiClient.getTenants(anyString(), anyString())).thenReturn(aaiGetTenantsResponse); + when(roleValidator.isTenantPermitted(anyString(), anyString(), anyString())) + .thenReturn(Boolean.TRUE); - assertThat(actualResponse).isEqualToComparingFieldByField(expectedResponse); - } + GetTenantsResponse[] actualResponses = aaiService + .getTenants(anyString(), anyString(), roleValidator).getT(); - @Test - public void shouldGetNodeTemplateInstances() { - when(aaiClient.getNodeTemplateInstances(anyString(), anyString(), anyString(), - anyString(), anyString())).thenReturn(aaiResponse); + assertThat(actualResponses).isNotNull(); + assertThat(actualResponses.length).isEqualTo(2); + assertThat(actualResponses).allMatch(tenant -> tenant.isPermitted); + } - AaiResponse expectedResponse = aaiService.getNodeTemplateInstances(anyString(), anyString(), anyString(), - anyString(), anyString()); + @Test + public void shouldGetVNFDataWithoutFiltering() { + when(aaiClient.getVNFData(anyString(), anyString(), anyString())).thenReturn(aaiResponse); - assertThat(expectedResponse).isEqualTo(aaiResponse); - } + AaiResponse actualResponse = aaiService.getVNFData(anyString(), anyString(), anyString()); - @Test - public void shouldGetNetworkCollectionDetails() { - when(aaiClient.getNetworkCollectionDetails(anyString())).thenReturn(aaiResponse); - - AaiResponse expectedResponse = aaiService.getNetworkCollectionDetails(anyString()); + assertThat(actualResponse).isEqualTo(aaiResponse); + } - assertThat(expectedResponse).isEqualTo(aaiResponse); - } + @Test + public void shouldGetVNFDataWithFiltering() { + VnfResult vnfResult1 = createVnfResult("ID1", "generic-vnf"); + VnfResult vnfResult2 = createVnfResult("ID2", "service-instance"); + VnfResult vnfResult3 = createVnfResult("ID3", "anything-else"); - @Test - public void shouldGetInstanceGroupsByCloudRegion() { - AaiGetInstanceGroupsByCloudRegion aaiGetInstanceGroupsByCloudRegion = - mock(AaiGetInstanceGroupsByCloudRegion.class); - AaiResponse expectedResponse = - new AaiResponse<>(aaiGetInstanceGroupsByCloudRegion, null, HttpStatus.SC_OK); + List vnfResults = Arrays.asList(vnfResult1, vnfResult2, vnfResult3); + AaiResponse aaiResponseGetVnfResponse = createAaiResponseVnfResponse(vnfResults); - when(aaiClient.getInstanceGroupsByCloudRegion(anyString(), anyString(), anyString())) - .thenReturn(expectedResponse); - AaiResponse actualResponse = - aaiService.getInstanceGroupsByCloudRegion(anyString(), anyString(), anyString()); + vnfResults = Arrays.asList(vnfResult1, vnfResult2); + AaiResponse expectedResponseWithReturnedVnfs = createAaiResponseVnfResponse(vnfResults); + AaiResponse expectedResponseWithoutReturnedVnfs = new AaiResponse(); - assertThat(actualResponse).isEqualTo(expectedResponse); - } + when(aaiClient.getVNFData(GLOBAL_SUBSCRIBER_ID, SERVICE_TYPE)).thenReturn(aaiResponseGetVnfResponse); + when(aaiClient.getVNFData(GLOBAL_SUBSCRIBER_ID_NULL_RESPONSE, SERVICE_TYPE)).thenReturn(null); - @Test - public void shouldGetServicesByDistributionStatus() { - Result resultWithModelType = createResult("MODEL_TYPE1", "1"); - Result resultWithEmptyModelType = createResult(null, "2"); - Result resultWithoutModel = new Result(); - resultWithoutModel.setModel(null); - Result resultWithoutValidModel = createResultWithoutValidModel(); - List results = Arrays.asList(resultWithModelType, resultWithEmptyModelType, resultWithoutModel, - resultWithoutValidModel); + AaiResponse actualResponseWithReturnedVnfs = + aaiService.getVNFData(GLOBAL_SUBSCRIBER_ID, SERVICE_TYPE); + AaiResponse actualResponseWithoutReturnedVnfs = + aaiService.getVNFData(GLOBAL_SUBSCRIBER_ID_NULL_RESPONSE, SERVICE_TYPE); - GetServiceModelsByDistributionStatusResponse serviceModels = new GetServiceModelsByDistributionStatusResponse(); - serviceModels.setResults(results); + assertThat(actualResponseWithReturnedVnfs) + .isEqualToComparingFieldByFieldRecursively(expectedResponseWithReturnedVnfs); + assertThat(actualResponseWithoutReturnedVnfs) + .isEqualToComparingFieldByField(expectedResponseWithoutReturnedVnfs); + } - AaiResponse serviceModelsByDistributionStatusResponse - = new AaiResponse<>(serviceModels, null, HttpStatus.SC_OK); + @Test + public void shouldGetAaiZones() { + when(aaiClient.getAllAicZones()).thenReturn(aaiResponse); - Service[] expectedServices = { - createService("MODEL_TYPE1", "1"), - createService("", "2") - }; + AaiResponse actualResponse = aaiService.getAaiZones(); - when(aaiClient.getServiceModelsByDistributionStatus()).thenReturn(serviceModelsByDistributionStatusResponse); - Collection actualServices = aaiService.getServicesByDistributionStatus(); + assertThat(actualResponse).isEqualTo(aaiResponse); + } + + @Test + public void shouldGetAicZoneForPnf() { + ServiceRelationships relationsService = createServiceRelationships(); + AaiResponse expectedServiceInstanceResp = + new AaiResponse<>(relationsService, null, HttpStatus.SC_OK); + AaiResponse expectedResponse = new AaiResponse<>(CORRECT_VALUE, null, HttpStatus.SC_OK); + + when(aaiClient.getServiceInstance(anyString(), anyString(), anyString())) + .thenReturn(expectedServiceInstanceResp); + + AaiResponse actualResponse = aaiService.getAicZoneForPnf(anyString(), anyString(), anyString()); - assertThat(actualServices) - .hasSize(2) - .usingFieldByFieldElementComparator() - .containsExactly(expectedServices); - } + assertThat(actualResponse).isEqualToComparingFieldByField(expectedResponse); + } + + @Test + public void shouldGetNodeTemplateInstances() { + when(aaiClient.getNodeTemplateInstances(anyString(), anyString(), anyString(), + anyString(), anyString())).thenReturn(aaiResponse); + + AaiResponse expectedResponse = aaiService.getNodeTemplateInstances(anyString(), anyString(), anyString(), + anyString(), anyString()); + + assertThat(expectedResponse).isEqualTo(aaiResponse); + } - @Test - public void shouldReturnEmptyListOfServices() { - AaiResponse emptyResponse - = new AaiResponse<>(null, null, HttpStatus.SC_OK); + @Test + public void shouldGetNetworkCollectionDetails() { + when(aaiClient.getNetworkCollectionDetails(anyString())).thenReturn(aaiResponse); + + AaiResponse expectedResponse = aaiService.getNetworkCollectionDetails(anyString()); + + assertThat(expectedResponse).isEqualTo(aaiResponse); + } + + @Test + public void shouldGetInstanceGroupsByCloudRegion() { + AaiGetInstanceGroupsByCloudRegion aaiGetInstanceGroupsByCloudRegion = + mock(AaiGetInstanceGroupsByCloudRegion.class); + AaiResponse expectedResponse = + new AaiResponse<>(aaiGetInstanceGroupsByCloudRegion, null, HttpStatus.SC_OK); - when(aaiClient.getServiceModelsByDistributionStatus()).thenReturn(emptyResponse); - Collection actualServices = aaiService.getServicesByDistributionStatus(); + when(aaiClient.getInstanceGroupsByCloudRegion(anyString(), anyString(), anyString())) + .thenReturn(expectedResponse); + AaiResponse actualResponse = + aaiService.getInstanceGroupsByCloudRegion(anyString(), anyString(), anyString()); - assertThat(actualServices).isEqualTo(Collections.EMPTY_LIST); - } + assertThat(actualResponse).isEqualTo(expectedResponse); + } - @Test - public void shouldGetServiceInstanceAssociatedPnfs() { - ServiceRelationships relationsList = createServiceRelationships(); - LogicalLinkResponse logicalLinkResponse = new LogicalLinkResponse(); - logicalLinkResponse.setRelationshipList(relationsList.getRelationshipList()); + @Test + public void shouldGetServicesByDistributionStatus() { + Result resultWithModelType = createResult("MODEL_TYPE1", "1"); + Result resultWithEmptyModelType = createResult(null, "2"); + Result resultWithoutModel = new Result(); + resultWithoutModel.setModel(null); + Result resultWithoutValidModel = createResultWithoutValidModel(); + List results = Arrays.asList(resultWithModelType, resultWithEmptyModelType, resultWithoutModel, + resultWithoutValidModel); - AaiResponse aaiResponseLogicalLinkResponse = - new AaiResponse<>(logicalLinkResponse, null, HttpStatus.SC_OK); - AaiResponse aaiResponseServiceRelations = - new AaiResponse<>(relationsList, null, HttpStatus.SC_OK); + GetServiceModelsByDistributionStatusResponse serviceModels = new GetServiceModelsByDistributionStatusResponse(); + serviceModels.setResults(results); - when(aaiClient.getServiceInstance(anyString(), anyString(), anyString())) - .thenReturn(aaiResponseServiceRelations); - when(aaiClient.getLogicalLink(anyString())).thenReturn(aaiResponseLogicalLinkResponse); + AaiResponse serviceModelsByDistributionStatusResponse + = new AaiResponse<>(serviceModels, null, HttpStatus.SC_OK); + + Service[] expectedServices = { + createService("MODEL_TYPE1", "1"), + createService("", "2") + }; + + when(aaiClient.getServiceModelsByDistributionStatus()).thenReturn(serviceModelsByDistributionStatusResponse); + Collection actualServices = aaiService.getServicesByDistributionStatus(); + + assertThat(actualServices) + .hasSize(2) + .usingFieldByFieldElementComparator() + .containsExactly(expectedServices); + } + @Test + public void shouldReturnEmptyListOfServices() { + AaiResponse emptyResponse + = new AaiResponse<>(null, null, HttpStatus.SC_OK); - List expectedPnfs = Collections.singletonList(CORRECT_VALUE); - List actualPnfs = aaiService.getServiceInstanceAssociatedPnfs(anyString(), anyString(), anyString()); + when(aaiClient.getServiceModelsByDistributionStatus()).thenReturn(emptyResponse); + Collection actualServices = aaiService.getServicesByDistributionStatus(); - assertThat(actualPnfs).isEqualTo(expectedPnfs); - } + assertThat(actualServices).isEqualTo(Collections.EMPTY_LIST); + } - @Test - public void shouldGetPortMirroringConfigData() { - AaiResponseTranslator.PortMirroringConfigData expectedData - = mock(AaiResponseTranslator.PortMirroringConfigData.class); + @Test + public void shouldGetServiceInstanceAssociatedPnfs() { + ServiceRelationships relationsList = createServiceRelationships(); + LogicalLinkResponse logicalLinkResponse = new LogicalLinkResponse(); + logicalLinkResponse.setRelationshipList(relationsList.getRelationshipList()); - when(aaiClient.getCloudRegionAndSourceByPortMirroringConfigurationId(anyString())).thenReturn(aaiResponseJsonNode); - when(aaiResponseTranslator.extractPortMirroringConfigData(aaiResponseJsonNode)).thenReturn(expectedData); + AaiResponse aaiResponseLogicalLinkResponse = + new AaiResponse<>(logicalLinkResponse, null, HttpStatus.SC_OK); + AaiResponse aaiResponseServiceRelations = + new AaiResponse<>(relationsList, null, HttpStatus.SC_OK); + + when(aaiClient.getServiceInstance(anyString(), anyString(), anyString())) + .thenReturn(aaiResponseServiceRelations); + when(aaiClient.getLogicalLink(anyString())).thenReturn(aaiResponseLogicalLinkResponse); - AaiResponseTranslator.PortMirroringConfigData actualData = aaiService.getPortMirroringConfigData(anyString()); - assertThat(actualData).isEqualTo(expectedData); - } + List expectedPnfs = Collections.singletonList(CORRECT_VALUE); + List actualPnfs = aaiService.getServiceInstanceAssociatedPnfs(anyString(), anyString(), anyString()); + assertThat(actualPnfs).isEqualTo(expectedPnfs); + } - @Test - public void shouldGetInstanceGroupsByVnfInstanceId() { - List instanceGroupInfo = Collections.singletonList(new InstanceGroupInfo(CORRECT_VALUE)); - AaiGetRelatedInstanceGroupsByVnfId relatedInstanceGroups = new AaiGetRelatedInstanceGroupsByVnfId(); - relatedInstanceGroups.setRelationshipList(createRelationshipList()); - - AaiResponse correctCodeResponse = - new AaiResponse<>(relatedInstanceGroups, null, HttpStatus.SC_OK); - - AaiResponse> expectedCorrectCodeResponse = - new AaiResponse<>(instanceGroupInfo, null, HttpStatus.SC_OK); - AaiResponse expectedIncorrectCodeResponse = - new AaiResponse<>(relatedInstanceGroups, null, HttpStatus.SC_PAYMENT_REQUIRED); - List expectedCorrectResponseObject = expectedCorrectCodeResponse.getT(); - - when(aaiClient.getInstanceGroupsByVnfInstanceId(VNF_INSTANCE_ID_OK)).thenReturn(correctCodeResponse); - when(aaiClient.getInstanceGroupsByVnfInstanceId(VNF_INSTANCE_ID_FAIL)).thenReturn(expectedIncorrectCodeResponse); - - AaiResponse actualCorrectCodeResponse = aaiService.getInstanceGroupsByVnfInstanceId(VNF_INSTANCE_ID_OK); - AaiResponse actualIncorrectCodeResponse = aaiService.getInstanceGroupsByVnfInstanceId(VNF_INSTANCE_ID_FAIL); - - List actualCorrectResponseObject = - (List) actualCorrectCodeResponse.getT(); - - assertThat(actualCorrectResponseObject) - .usingFieldByFieldElementComparator() - .hasSameElementsAs(expectedCorrectResponseObject); - - assertThat(actualIncorrectCodeResponse).isEqualTo(expectedIncorrectCodeResponse); - } - - @Test - public void shouldGetHomingDataByVfModule() { - GetTenantsResponse expectedResponse = new GetTenantsResponse(); - when(aaiClient.getHomingDataByVfModule(anyString(), anyString())).thenReturn(expectedResponse); - - GetTenantsResponse actualResponse = aaiService.getHomingDataByVfModule(anyString(), anyString()); - assertThat(actualResponse).isEqualTo(expectedResponse); - } - - @Test - public void shouldSearchGroupMembers() { - Properties properties = createProperties(); - Map regionsAndTenants = createRegionsAndTenantsMap(properties); - - AAITreeNode validTreeNode = new AAITreeNode(); - addAdditionalPropertiesToAaiTreeNode(validTreeNode); - List validNodes = Arrays.asList(validTreeNode, validTreeNode); - - AAITreeNode validBranch = createTree(validNodes); - addAdditionalPropertiesToAaiTreeNode(validBranch); - List testedBranches = Collections.singletonList(validBranch); - - AAITreeNode testedTree = createTree(testedBranches); - - RelatedVnf expectedVnf = createExpectedVnf(validBranch); - List expectedResult = Collections.singletonList(expectedVnf); - - when(aaiServiceTree.buildAAITree(anyString(), any())).thenReturn(Collections.singletonList(testedTree)); - when(aaiClient.getCloudRegionAndTenantByVnfId(anyString())).thenReturn(regionsAndTenants); - - List actualGroupMembers = aaiService.searchGroupMembers(GLOBAL_CUSTOMER_ID, SERVICE_TYPE, - INVARIANT_ID, GROUP_TYPE_FAILING, GROUP_ROLE_FAILING); - - assertThat(actualGroupMembers) - .usingFieldByFieldElementComparator() - .hasSameElementsAs(expectedResult); - } - - @Test - public void shouldGetPortMirroringSourcePorts() { - PortDetailsTranslator.PortDetails details = mock(PortDetailsTranslator.PortDetails.class); - List expectedDetailsList = Arrays.asList( - details, details, details - ); - - when(aaiClient.getPortMirroringSourcePorts(anyString())).thenReturn(expectedDetailsList); - List actualDetails = aaiService.getPortMirroringSourcePorts(anyString()); - - assertThat(actualDetails).isEqualTo(expectedDetailsList); - } - - @Test - public void shouldGetAAIServiceTree() throws JsonProcessingException { - ServiceInstance serviceInstance = mock(ServiceInstance.class); - String expectedResult = new ObjectMapper().writeValueAsString(serviceInstance); - - when(aaiServiceTree.getServiceInstanceTopology(anyString(), anyString(), anyString())) - .thenReturn(serviceInstance); - String actualResult = aaiService.getAAIServiceTree(anyString(), anyString(), anyString()); - - assertThat(actualResult).isEqualTo(expectedResult); - } - - @NotNull - private Map createRegionsAndTenantsMap(Properties properties) { - Map regionsAndTenants = new HashMap<>(); - regionsAndTenants.put("tenant", properties); - regionsAndTenants.put("cloud-region", properties); - return regionsAndTenants; - } - - private Properties createProperties() { - Properties properties = new Properties(); - properties.setTenantId(TENANT_ID); - properties.setTenantName(TENANT_NAME); - properties.setCloudRegionId(CLOUD_REGION_ID); - return properties; - } - - @NotNull - private RelatedVnf createExpectedVnf(AAITreeNode validBranch) { - RelatedVnf expectedVnf = RelatedVnf.from(validBranch); - expectedVnf.setTenantId(TENANT_ID); - expectedVnf.setTenantName(TENANT_NAME); - expectedVnf.setLcpCloudRegionId(CLOUD_REGION_ID); - expectedVnf.setServiceInstanceId(PARENT_ID); - expectedVnf.setServiceInstanceName(PARENT_NAME); - expectedVnf.setInstanceType(VNF_TYPE); - - return expectedVnf; - } - - - private AAITreeNode createTree(List children) { - AAITreeNode tree = new AAITreeNode(); - tree.addChildren(children); - tree.setId(PARENT_ID); - tree.setName(PARENT_NAME); - return tree; - } - - private void addAdditionalPropertiesToAaiTreeNode(AAITreeNode tree) { - Map additionalProperties = new HashMap<>(); - additionalProperties.put("instance-group-role", GROUP_ROLE_OK); - additionalProperties.put("instance-group-type", group_type_ok); - additionalProperties.put("vnf-type", VNF_TYPE); - additionalProperties.put("cloud-region", CLOUD_TYPE); - tree.setAdditionalProperties(additionalProperties); - } - - private org.onap.vid.asdc.beans.Service createService(String category, String suffix) { - return new Service.ServiceBuilder() - .setUuid("MODELVER_VERSION_ID" + suffix) - .setInvariantUUID("MODEL_INVARIANT_NAME" + suffix) - .setCategory(category) - .setVersion("MODELVER_VERSION" + suffix) - .setName("MODELVER_NAME" + suffix) - .setDistributionStatus("MODELVER_DIST_STATUS" + suffix) - .setToscaModelURL(null) - .setLifecycleState(null) - .setArtifacts(null) - .setResources(null) - .build(); - } - - @NotNull - private Result createResultWithoutValidModel() { - ModelVers modelVers = new ModelVers(); - modelVers.setModelVer(Collections.singletonList(new ModelVer())); - - Model model = new Model(); - model.setModelVers(modelVers); - - Result result1 = new Result(); - result1.setModel(model); - return result1; - } - - @NotNull - private Result createResult(String modelType, String suffix) { - ModelVer modelVer = new ModelVer(); - modelVer.setModelVersionId("MODELVER_VERSION_ID" + suffix); - modelVer.setModelVersion("MODELVER_VERSION" + suffix); - modelVer.setModelName("MODELVER_NAME" + suffix); - modelVer.setDistributionStatus("MODELVER_DIST_STATUS" + suffix); - - ModelVers modelVers = new ModelVers(); - modelVers.setModelVer(Collections.singletonList(modelVer)); - - Model model = new Model(); - model.setModelType(modelType); - model.setModelInvariantId("MODEL_INVARIANT_NAME" + suffix); - model.setModelVers(modelVers); - - Result result = new Result(); - result.setModel(model); - return result; - } - - @NotNull - private ServiceRelationships createServiceRelationships() { - RelationshipList relationsList = createRelationshipList(CORRECT_VALUE); - ServiceRelationships relationsService = new ServiceRelationships(); - relationsService.setRelationshipList(relationsList); - return relationsService; - } - - @NotNull - private RelationshipList createRelationshipList(String expectedValue) { - List relationsDataList = createRelationshipDataList(expectedValue); - return createRelationshipList(relationsDataList); - } - - @NotNull - private RelationshipList createRelationshipList(List relationsDataList) { - Relationship relation1 = crateRelationship("any", relationsDataList); - Relationship relation2 = crateRelationship("zone", relationsDataList); - Relationship relation3 = crateRelationship("logical-link", relationsDataList); - Relationship relation4 = crateRelationship("lag-interface", relationsDataList); - Relationship relation5 = crateRelationship("pnf", relationsDataList); - - RelationshipList relationsList = new RelationshipList(); - relationsList.setRelationship(Arrays.asList(relation1, relation2, relation3, relation4, relation5)); - return relationsList; - } - - @NotNull - private List createRelationshipDataList(String expectedValue) { - RelationshipData relationData1 = createRelationshipData("any-key", "incorrect_key"); - RelationshipData relationData2 = createRelationshipData("zone.zone-id", expectedValue); - RelationshipData relationData3 = createRelationshipData("logical-link.link-name", expectedValue); - RelationshipData relationData4 = createRelationshipData("pnf.pnf-name", expectedValue); - - return Arrays.asList(relationData1, relationData2, relationData3, relationData4); - } - - @NotNull - private Relationship crateRelationship(String relatedTo, List relationsDataList) { - Relationship relation = new Relationship(); - relation.setRelatedTo(relatedTo); - relation.setRelationDataList(relationsDataList); - return relation; - } - - @NotNull - private RelationshipData createRelationshipData(String key, String value) { - RelationshipData relationData = new RelationshipData(); - relationData.setRelationshipKey(key); - relationData.setRelationshipValue(value); - return relationData; - } - - private org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.RelationshipList createRelationshipList() { - RelatedToProperty property1 = - createRelatedToProperty("instance-group.instance-group-name", CORRECT_VALUE); - RelatedToProperty property2 = - createRelatedToProperty("anything-key", "anything-value"); - List properties = Arrays.asList(property1, property2); - - org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Relationship relationship1 = - createRelationship("instance-group", properties); - org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Relationship relationship2 = - createRelationship("any-key", properties); - - List relationships = - Arrays.asList(relationship1, relationship2); - - org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.RelationshipList relationshipList = - new org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.RelationshipList(); - relationshipList.setRelationship(relationships); - - return relationshipList; - } - - @NotNull - private org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Relationship createRelationship(String relatedTo, - List relatedToPropertyList) { - org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Relationship relationship1 = - new org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Relationship(); - relationship1.setRelatedTo(relatedTo); - relationship1.setRelatedToPropertyList(relatedToPropertyList); - return relationship1; - } - - @NotNull - private RelatedToProperty createRelatedToProperty(String key, String value) { - RelatedToProperty prop = new RelatedToProperty(); - prop.setPropertyKey(key); - prop.setPropertyValue(value); - return prop; - } - - @NotNull - private AaiResponse createAaiResponseVnfResponse(List vnfResults) { - AaiGetVnfResponse vnfResponse = new AaiGetVnfResponse(); - vnfResponse.setResults(vnfResults); - return new AaiResponse<>(vnfResponse, null, HttpStatus.SC_OK); - } - - private VnfResult createVnfResult(String id, String nodeType) { - VnfResult result = new VnfResult(); - result.setJsonId(id); - result.setJsonNodeType(nodeType); - return result; - } - - - private org.onap.vid.aai.model.AaiGetServicesRequestModel.Service createService(String serviceId, - String resourceVersion, - String serviceDescription) { - org.onap.vid.aai.model.AaiGetServicesRequestModel.Service service - = new org.onap.vid.aai.model.AaiGetServicesRequestModel.Service(); - service.isPermitted = false; - service.resourceVersion = resourceVersion; - service.serviceDescription = serviceDescription; - service.serviceId = serviceId; - return service; - } - - @NotNull - private Services createAaiResponseServices() { - ServiceSubscription sub1 = new ServiceSubscription(); - sub1.isPermitted = false; - sub1.serviceType = "serviceSubsType1"; - - ServiceSubscription sub2 = new ServiceSubscription(); - sub2.isPermitted = true; - sub2.serviceType = "serviceSubsType2"; - - ServiceSubscriptions serviceSubs = new ServiceSubscriptions(); - serviceSubs.serviceSubscription = Collections.singletonList(sub2); - - Services services = new Services(); - services.globalCustomerId = GLOBAL_CUSTOMER_ID; - services.resourceVersion = "v-1"; - services.subscriberName = "name-1"; - services.subscriberType = "type-1"; - services.serviceSubscriptions = serviceSubs; - return services; - } - - @NotNull - private Subscriber createSubscriber() { - Subscriber subscriber = new Subscriber(); - subscriber.globalCustomerId = "id-1"; - subscriber.resourceVersion = "v-1"; - subscriber.subscriberName = "name-1"; - subscriber.subscriberType = "type-1"; - return subscriber; - } + @Test + public void shouldGetPortMirroringConfigData() { + AaiResponseTranslator.PortMirroringConfigData expectedData + = mock(AaiResponseTranslator.PortMirroringConfigData.class); + + when(aaiClient.getCloudRegionAndSourceByPortMirroringConfigurationId(anyString())) + .thenReturn(aaiResponseJsonNode); + when(aaiResponseTranslator.extractPortMirroringConfigData(aaiResponseJsonNode)).thenReturn(expectedData); + + AaiResponseTranslator.PortMirroringConfigData actualData = aaiService.getPortMirroringConfigData(anyString()); + assertThat(actualData).isEqualTo(expectedData); + } + + + @Test + public void shouldGetInstanceGroupsByVnfInstanceId() { + List instanceGroupInfo = Collections.singletonList(new InstanceGroupInfo(CORRECT_VALUE)); + AaiGetRelatedInstanceGroupsByVnfId relatedInstanceGroups = new AaiGetRelatedInstanceGroupsByVnfId(); + relatedInstanceGroups.setRelationshipList(createRelationshipList()); + + AaiResponse correctCodeResponse = + new AaiResponse<>(relatedInstanceGroups, null, HttpStatus.SC_OK); + + AaiResponse> expectedCorrectCodeResponse = + new AaiResponse<>(instanceGroupInfo, null, HttpStatus.SC_OK); + AaiResponse expectedIncorrectCodeResponse = + new AaiResponse<>(relatedInstanceGroups, null, HttpStatus.SC_PAYMENT_REQUIRED); + List expectedCorrectResponseObject = expectedCorrectCodeResponse.getT(); + + when(aaiClient.getInstanceGroupsByVnfInstanceId(VNF_INSTANCE_ID_OK)).thenReturn(correctCodeResponse); + when(aaiClient.getInstanceGroupsByVnfInstanceId(VNF_INSTANCE_ID_FAIL)) + .thenReturn(expectedIncorrectCodeResponse); + + AaiResponse actualCorrectCodeResponse = aaiService.getInstanceGroupsByVnfInstanceId(VNF_INSTANCE_ID_OK); + AaiResponse actualIncorrectCodeResponse = aaiService.getInstanceGroupsByVnfInstanceId(VNF_INSTANCE_ID_FAIL); + + List actualCorrectResponseObject = + (List) actualCorrectCodeResponse.getT(); + + assertThat(actualCorrectResponseObject) + .usingFieldByFieldElementComparator() + .hasSameElementsAs(expectedCorrectResponseObject); + + assertThat(actualIncorrectCodeResponse).isEqualTo(expectedIncorrectCodeResponse); + } + + @Test + public void shouldGetHomingDataByVfModule() { + GetTenantsResponse expectedResponse = new GetTenantsResponse(); + when(aaiClient.getHomingDataByVfModule(anyString(), anyString())).thenReturn(expectedResponse); + + GetTenantsResponse actualResponse = aaiService.getHomingDataByVfModule(anyString(), anyString()); + assertThat(actualResponse).isEqualTo(expectedResponse); + } + + @Test + public void shouldSearchGroupMembers() { + Properties properties = createProperties(); + Map regionsAndTenants = createRegionsAndTenantsMap(properties); + + AAITreeNode validTreeNode = new AAITreeNode(); + addAdditionalPropertiesToAaiTreeNode(validTreeNode); + List validNodes = Arrays.asList(validTreeNode, validTreeNode); + + AAITreeNode validBranch = createTree(validNodes); + addAdditionalPropertiesToAaiTreeNode(validBranch); + List testedBranches = Collections.singletonList(validBranch); + + AAITreeNode testedTree = createTree(testedBranches); + + RelatedVnf expectedVnf = createExpectedVnf(validBranch); + List expectedResult = Collections.singletonList(expectedVnf); + + when(aaiServiceTree.buildAAITree(anyString(), isNull(), eq(HttpMethod.GET), any(), anyBoolean())) + .thenReturn(Collections.singletonList(testedTree)); + when(aaiClient.getCloudRegionAndTenantByVnfId(anyString())).thenReturn(regionsAndTenants); + + List actualGroupMembers = aaiService.searchGroupMembers(GLOBAL_CUSTOMER_ID, SERVICE_TYPE, + INVARIANT_ID, GROUP_TYPE_FAILING, GROUP_ROLE_FAILING); + + assertThat(actualGroupMembers) + .usingFieldByFieldElementComparator() + .hasSameElementsAs(expectedResult); + } + + @Test + public void shouldGetPortMirroringSourcePorts() { + PortDetailsTranslator.PortDetails details = mock(PortDetailsTranslator.PortDetails.class); + List expectedDetailsList = Arrays.asList( + details, details, details + ); + + when(aaiClient.getPortMirroringSourcePorts(anyString())).thenReturn(expectedDetailsList); + List actualDetails = aaiService.getPortMirroringSourcePorts(anyString()); + + assertThat(actualDetails).isEqualTo(expectedDetailsList); + } + + @Test + public void shouldGetAAIServiceTree() throws JsonProcessingException { + ServiceInstance serviceInstance = mock(ServiceInstance.class); + String expectedResult = new ObjectMapper().writeValueAsString(serviceInstance); + + when(aaiServiceTree.getServiceInstanceTopology(anyString(), anyString(), anyString())) + .thenReturn(serviceInstance); + String actualResult = aaiService.getAAIServiceTree(anyString(), anyString(), anyString()); + + assertThat(actualResult).isEqualTo(expectedResult); + } + + @NotNull + private Map createRegionsAndTenantsMap(Properties properties) { + Map regionsAndTenants = new HashMap<>(); + regionsAndTenants.put("tenant", properties); + regionsAndTenants.put("cloud-region", properties); + return regionsAndTenants; + } + + private Properties createProperties() { + Properties properties = new Properties(); + properties.setTenantId(TENANT_ID); + properties.setTenantName(TENANT_NAME); + properties.setCloudRegionId(CLOUD_REGION_ID); + return properties; + } + + @NotNull + private RelatedVnf createExpectedVnf(AAITreeNode validBranch) { + RelatedVnf expectedVnf = RelatedVnf.from(validBranch); + expectedVnf.setTenantId(TENANT_ID); + expectedVnf.setTenantName(TENANT_NAME); + expectedVnf.setLcpCloudRegionId(CLOUD_REGION_ID); + expectedVnf.setServiceInstanceId(PARENT_ID); + expectedVnf.setServiceInstanceName(PARENT_NAME); + expectedVnf.setInstanceType(VNF_TYPE); + + return expectedVnf; + } + + + private AAITreeNode createTree(List children) { + AAITreeNode tree = new AAITreeNode(); + tree.addChildren(children); + tree.setId(PARENT_ID); + tree.setName(PARENT_NAME); + tree.setType(SERVICE_INSTANCE); + return tree; + } + + private void addAdditionalPropertiesToAaiTreeNode(AAITreeNode tree) { + Map additionalProperties = new HashMap<>(); + additionalProperties.put("instance-group-role", GROUP_ROLE_OK); + additionalProperties.put("instance-group-type", group_type_ok); + additionalProperties.put("vnf-type", VNF_TYPE); + additionalProperties.put("cloud-region", CLOUD_TYPE); + tree.setAdditionalProperties(additionalProperties); + } + + private org.onap.vid.asdc.beans.Service createService(String category, String suffix) { + return new Service.ServiceBuilder() + .setUuid("MODELVER_VERSION_ID" + suffix) + .setInvariantUUID("MODEL_INVARIANT_NAME" + suffix) + .setCategory(category) + .setVersion("MODELVER_VERSION" + suffix) + .setName("MODELVER_NAME" + suffix) + .setDistributionStatus("MODELVER_DIST_STATUS" + suffix) + .setToscaModelURL(null) + .setLifecycleState(null) + .setArtifacts(null) + .setResources(null) + .build(); + } + + @NotNull + private Result createResultWithoutValidModel() { + ModelVers modelVers = new ModelVers(); + modelVers.setModelVer(Collections.singletonList(new ModelVer())); + + Model model = new Model(); + model.setModelVers(modelVers); + + Result result1 = new Result(); + result1.setModel(model); + return result1; + } + + @NotNull + private Result createResult(String modelType, String suffix) { + ModelVer modelVer = new ModelVer(); + modelVer.setModelVersionId("MODELVER_VERSION_ID" + suffix); + modelVer.setModelVersion("MODELVER_VERSION" + suffix); + modelVer.setModelName("MODELVER_NAME" + suffix); + modelVer.setDistributionStatus("MODELVER_DIST_STATUS" + suffix); + + ModelVers modelVers = new ModelVers(); + modelVers.setModelVer(Collections.singletonList(modelVer)); + + Model model = new Model(); + model.setModelType(modelType); + model.setModelInvariantId("MODEL_INVARIANT_NAME" + suffix); + model.setModelVers(modelVers); + + Result result = new Result(); + result.setModel(model); + return result; + } + + @NotNull + private ServiceRelationships createServiceRelationships() { + RelationshipList relationsList = createRelationshipList(CORRECT_VALUE); + ServiceRelationships relationsService = new ServiceRelationships(); + relationsService.setRelationshipList(relationsList); + return relationsService; + } + + @NotNull + private RelationshipList createRelationshipList(String expectedValue) { + List relationsDataList = createRelationshipDataList(expectedValue); + return createRelationshipList(relationsDataList); + } + + @NotNull + private RelationshipList createRelationshipList(List relationsDataList) { + Relationship relation1 = crateRelationship("any", relationsDataList); + Relationship relation2 = crateRelationship("zone", relationsDataList); + Relationship relation3 = crateRelationship("logical-link", relationsDataList); + Relationship relation4 = crateRelationship("lag-interface", relationsDataList); + Relationship relation5 = crateRelationship("pnf", relationsDataList); + + RelationshipList relationsList = new RelationshipList(); + relationsList.setRelationship(Arrays.asList(relation1, relation2, relation3, relation4, relation5)); + return relationsList; + } + + @NotNull + private List createRelationshipDataList(String expectedValue) { + RelationshipData relationData1 = createRelationshipData("any-key", "incorrect_key"); + RelationshipData relationData2 = createRelationshipData("zone.zone-id", expectedValue); + RelationshipData relationData3 = createRelationshipData("logical-link.link-name", expectedValue); + RelationshipData relationData4 = createRelationshipData("pnf.pnf-name", expectedValue); + + return Arrays.asList(relationData1, relationData2, relationData3, relationData4); + } + + @NotNull + private Relationship crateRelationship(String relatedTo, List relationsDataList) { + Relationship relation = new Relationship(); + relation.setRelatedTo(relatedTo); + relation.setRelationDataList(relationsDataList); + return relation; + } + + @NotNull + private RelationshipData createRelationshipData(String key, String value) { + RelationshipData relationData = new RelationshipData(); + relationData.setRelationshipKey(key); + relationData.setRelationshipValue(value); + return relationData; + } + + private org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.RelationshipList createRelationshipList() { + RelatedToProperty property1 = + createRelatedToProperty("instance-group.instance-group-name", CORRECT_VALUE); + RelatedToProperty property2 = + createRelatedToProperty("anything-key", "anything-value"); + List properties = Arrays.asList(property1, property2); + + org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Relationship relationship1 = + createRelationship("instance-group", properties); + org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Relationship relationship2 = + createRelationship("any-key", properties); + + List relationships = + Arrays.asList(relationship1, relationship2); + + org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.RelationshipList relationshipList = + new org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.RelationshipList(); + relationshipList.setRelationship(relationships); + + return relationshipList; + } + + @NotNull + private org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Relationship createRelationship(String relatedTo, + List relatedToPropertyList) { + org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Relationship relationship1 = + new org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Relationship(); + relationship1.setRelatedTo(relatedTo); + relationship1.setRelatedToPropertyList(relatedToPropertyList); + return relationship1; + } + + @NotNull + private RelatedToProperty createRelatedToProperty(String key, String value) { + RelatedToProperty prop = new RelatedToProperty(); + prop.setKey(key); + prop.setValue(value); + return prop; + } + + @NotNull + private AaiResponse createAaiResponseVnfResponse(List vnfResults) { + AaiGetVnfResponse vnfResponse = new AaiGetVnfResponse(); + vnfResponse.setResults(vnfResults); + return new AaiResponse<>(vnfResponse, null, HttpStatus.SC_OK); + } + + private VnfResult createVnfResult(String id, String nodeType) { + VnfResult result = new VnfResult(); + result.setJsonId(id); + result.setJsonNodeType(nodeType); + return result; + } + + + private org.onap.vid.aai.model.AaiGetServicesRequestModel.Service createService(String serviceId, + String resourceVersion, + String serviceDescription) { + org.onap.vid.aai.model.AaiGetServicesRequestModel.Service service + = new org.onap.vid.aai.model.AaiGetServicesRequestModel.Service(); + service.isPermitted = false; + service.resourceVersion = resourceVersion; + service.serviceDescription = serviceDescription; + service.serviceId = serviceId; + return service; + } + + @NotNull + private Services createAaiResponseServices() { + ServiceSubscription sub1 = new ServiceSubscription(); + sub1.isPermitted = false; + sub1.serviceType = "serviceSubsType1"; + + ServiceSubscription sub2 = new ServiceSubscription(); + sub2.isPermitted = true; + sub2.serviceType = "serviceSubsType2"; + + ServiceSubscriptions serviceSubs = new ServiceSubscriptions(); + serviceSubs.serviceSubscription = Collections.singletonList(sub2); + + Services services = new Services(); + services.globalCustomerId = GLOBAL_CUSTOMER_ID; + services.resourceVersion = "v-1"; + services.subscriberName = "name-1"; + services.subscriberType = "type-1"; + services.serviceSubscriptions = serviceSubs; + return services; + } + + @NotNull + private Subscriber createSubscriber() { + Subscriber subscriber = new Subscriber(); + subscriber.globalCustomerId = "id-1"; + subscriber.resourceVersion = "v-1"; + subscriber.subscriberName = "name-1"; + subscriber.subscriberType = "type-1"; + return subscriber; + } } diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBaseTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBaseTest.java index 401a56c58..4cab99816 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBaseTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBaseTest.java @@ -25,11 +25,16 @@ import com.google.common.collect.ImmutableMap; import org.onap.vid.aai.AaiClientInterface; import org.onap.vid.aai.ExceptionWithRequestInfo; import org.onap.vid.model.Action; +import org.onap.vid.model.VidNotions; +import org.onap.vid.model.VidNotions.InstantiationType; +import org.onap.vid.model.VidNotions.InstantiationUI; +import org.onap.vid.model.VidNotions.ModelCategory; import org.onap.vid.model.serviceInstantiation.*; import org.onap.vid.mso.RestObject; import org.onap.vid.mso.model.ModelInfo; import org.onap.vid.mso.rest.AsyncRequestStatus; import org.onap.vid.mso.rest.RequestStatus; +import org.onap.vid.properties.Features; import org.onap.vid.utils.TimeUtils; import org.springframework.http.HttpMethod; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; @@ -38,14 +43,18 @@ import org.togglz.core.manager.FeatureManager; import javax.inject.Inject; import java.time.ZonedDateTime; import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import static java.util.Collections.emptyList; import static java.util.Collections.emptyMap; -import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.when; public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests { public static final String OWNING_ENTITY_ID = "038d99af-0427-42c2-9d15-971b99b9b489"; + public static final String JULIO_ERICKSON = "JULIO ERICKSON"; public static final String PACKET_CORE = "PACKET CORE"; public static final String PROJECT_NAME = "{some project name}"; public static final String SUBSCRIBER_ID = "{some subscriber id}"; @@ -98,7 +107,7 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests return new ServiceInstantiation ( modelInfo, AsyncInstantiationBusinessLogicTest.OWNING_ENTITY_ID, - AsyncInstantiationBusinessLogicTest.PACKET_CORE, + AsyncInstantiationBusinessLogicTest.JULIO_ERICKSON, projectName, AsyncInstantiationBusinessLogicTest.SUBSCRIBER_ID, AsyncInstantiationBusinessLogicTest.SUBSCRIBER_NAME, @@ -114,6 +123,7 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests vnfs, networks, vnfGroups, + null, instanceParams, isPause, bulkSize, @@ -121,8 +131,8 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests isAlacarte, testApi, instanceId, - action.name() - ); + action.name(), + UUID.randomUUID().toString(), null, null, null); } private List> createInstanceParams() { @@ -146,10 +156,12 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests if (isAlacarte) { vfModuleInfo.setModelInvariantId("22222222-f63c-463e-ba94-286933b895f9"); vfModuleInfo.setModelVersion("10.0"); - return new VfModule(vfModuleInfo, instanceName, volumeGroupInstanceName, Action.Create.name(), "mdt1", null, "88a6ca3ee0394ade9403f075db23167e", instanceParams, supplementaryParams, false, true, null); + return new VfModule(vfModuleInfo, instanceName, volumeGroupInstanceName, Action.Create.name(), "mdt1", null, + "88a6ca3ee0394ade9403f075db23167e", instanceParams, supplementaryParams, false, true, null, UUID.randomUUID().toString(), null, null); } - return new VfModule(vfModuleInfo, instanceName, volumeGroupInstanceName, Action.Create.name(), null, null, null, instanceParams, supplementaryParams, false, false, null); + return new VfModule(vfModuleInfo, instanceName, volumeGroupInstanceName, Action.Create.name(), null, null, null, + instanceParams, supplementaryParams, false, false, null, UUID.randomUUID().toString(), null, null); } protected ModelInfo createVnfModelInfo(boolean isAlacarte) { @@ -167,19 +179,20 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests return vnfModelInfo; } - private ModelInfo createNetworkModelInfo(boolean isAlacarte) { - ModelInfo vnfModelInfo = new ModelInfo(); - vnfModelInfo.setModelType("network"); - vnfModelInfo.setModelName("2016-73_MOW-AVPN-vPE-BV-L"); - vnfModelInfo.setModelVersionId("7f40c192-f63c-463e-ba94-286933b895f8"); - vnfModelInfo.setModelCustomizationName("2016-73_MOW-AVPN-vPE-BV-L 0"); - vnfModelInfo.setModelCustomizationId("ab153b6e-c364-44c0-bef6-1f2982117f04"); + private ModelInfo createNetworkModelInfo(boolean isAlacarte, String modelCustomizationId) + { + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelType("network"); + modelInfo.setModelName("2016-73_MOW-AVPN-vPE-BV-L"); + modelInfo.setModelVersionId("7f40c192-f63c-463e-ba94-286933b895f8"); + modelInfo.setModelCustomizationName("2016-73_MOW-AVPN-vPE-BV-L 0"); + modelInfo.setModelCustomizationId(modelCustomizationId); //added two conditional fields according to MSO AID - needed only in alacarte if (isAlacarte) { - vnfModelInfo.setModelInvariantId("11111111-f63c-463e-ba94-286933b895f9"); - vnfModelInfo.setModelVersion("10.0"); + modelInfo.setModelInvariantId("11111111-f63c-463e-ba94-286933b895f9"); + modelInfo.setModelVersion("10.0"); } - return vnfModelInfo; + return modelInfo; } private ModelInfo createModelInfo() { @@ -214,21 +227,33 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests vfModules.get(vfModuleModelName).put(vfModuleModelName + ":002", vfModule2); Vnf vnf = new Vnf(vnfModelInfo, "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", (isUserProvidedNaming ? VNF_NAME : null), Action.Create.name(), - "platformName", "mdt1", null, "88a6ca3ee0394ade9403f075db23167e", vnfInstanceParams,"lineOfBusinessName" , false, null, vfModules); + "platformName", "mdt1", null, "88a6ca3ee0394ade9403f075db23167e", vnfInstanceParams,"lineOfBusinessName" , false, null, vfModules, + UUID.randomUUID().toString(), null, null); vnfs.put(vnf.getModelInfo().getModelName(), vnf); return vnfs; } - protected Map createNetworkList(List vnfInstanceParams, boolean isUserProvidedNaming, boolean isALaCarte) { - Map networks = new HashMap<>(); - ModelInfo networkModelInfo = createNetworkModelInfo(isALaCarte); + public static class NetworkDetails { + + public NetworkDetails(String name, String modelCustomizationId) { + this.name = name; + this.modelCustomizationId = modelCustomizationId; + } + + public String name; + public String modelCustomizationId; + } - Network network = new Network(networkModelInfo, "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", isUserProvidedNaming ? VNF_NAME : null, Action.Create.name(), - "platformName", "mdt1", null, "88a6ca3ee0394ade9403f075db23167e", vnfInstanceParams,"lineOfBusinessName" , false, null); - networks.put(network.getModelInfo().getModelName(), network); - return networks; + protected Map createNetworkList(List instanceParams, List networkDetails, boolean isALaCarte) { + Stream networkStream = networkDetails.stream().map( + details->new Network(createNetworkModelInfo(isALaCarte, details.modelCustomizationId), "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", + details.name, Action.Create.name(), + "platformName", "mdt1", null, "88a6ca3ee0394ade9403f075db23167e", instanceParams,"lineOfBusinessName" , + false, null, UUID.randomUUID().toString(), null, null)); +// I can't tell why compiler don't like the statement if it's only one line... + return networkStream.collect(Collectors.toMap(network -> network.getModelInfo().getModelCustomizationId(), network -> network)); } protected InstanceGroup createInstanceGroup(boolean isUserProvidedNaming, Action action) { @@ -241,7 +266,7 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests modelInfo.setModelInvariantId("11111111-f63c-463e-ba94-286933b895f9"); modelInfo.setModelVersion("10.0"); - return new InstanceGroup(modelInfo, (isUserProvidedNaming ? VNF_GROUP_NAME : null), action.name(), false, null); + return new InstanceGroup(modelInfo, (isUserProvidedNaming ? VNF_GROUP_NAME : null), action.name(), false, null, emptyMap(), UUID.randomUUID().toString(), null, null); } protected ModelInfo createServiceModelInfo() { @@ -277,11 +302,11 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests return asyncRequestStatus; } - protected RestObject asyncRequestStatusResponseAsRestObject(String msoStatus) { + public static RestObject asyncRequestStatusResponseAsRestObject(String msoStatus) { return asyncRequestStatusResponseAsRestObject(msoStatus, 200); } - protected RestObject asyncRequestStatusResponseAsRestObject(String msoStatus, int httpStatusCode) { + public static RestObject asyncRequestStatusResponseAsRestObject(String msoStatus, int httpStatusCode) { RestObject restObject = new RestObject<>(); restObject.set(asyncRequestStatusResponse(msoStatus)); restObject.setStatusCode(httpStatusCode); @@ -302,6 +327,12 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests return serviceInstantiation; } + protected ServiceInstantiation generateALaCarteWithNetworksPayload(List networkDetails) { + Map networks = createNetworkList(emptyList(), networkDetails, true); + ServiceInstantiation serviceInstantiation = generateMockALaCarteServiceInstantiationPayload(false, emptyMap(), networks, emptyMap(), 1, true, PROJECT_NAME, false, "VNF_API"); + return serviceInstantiation; + } + protected ServiceInstantiation generateALaCarteUpdateWith1ExistingGroup2NewGroupsPayload() { final InstanceGroup instanceGroup1 = createInstanceGroup(true, Action.None); final InstanceGroup instanceGroup2 = createInstanceGroup(false, Action.Create); @@ -315,4 +346,38 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests 1, true, PROJECT_NAME, false, true, "VNF_API", Action.None, "1234567890"); } + + protected void enableAddCloudOwnerOnMsoRequest() { + enableAddCloudOwnerOnMsoRequest(true); + } + + protected void enableAddCloudOwnerOnMsoRequest(boolean isActive) { + // always turn on the feature flag + when(featureManager.isActive(Features.FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST)).thenReturn(isActive); + when(aaiClient.getCloudOwnerByCloudRegionId(anyString())).thenReturn("irma-aic"); + } + + protected ServiceInstantiation generateALaCarteServiceInstantiationPayload() { + return generateMockALaCarteServiceInstantiationPayload(false, Collections.EMPTY_MAP, Collections.EMPTY_MAP, Collections.EMPTY_MAP, 1, true, PROJECT_NAME, false, "VNF_API"); + } + + protected ServiceInstantiation generateMacroMockServiceInstantiationPayload(boolean isPause, Map vnfs) { + return generateMockMacroServiceInstantiationPayload(isPause, vnfs, 1, true, PROJECT_NAME, false); + } + + protected ServiceInstantiation generatePre1806MacroTransportServiceInstantiationPayload(String tenantId, String lcpCloudRegionId) { + List> instanceParams = ImmutableList.of(ImmutableMap.of("someUserParam","someValue", "anotherUserParam","anotherValue")); + ServiceInstantiation serviceInstantiation = new ServiceInstantiation(createServiceModelInfo(), "038d99af-0427-42c2-9d15-971b99b9b489", + "JULIO ERICKSON", "some_project_name", "some_subscriber_id", "some_subscriber_name", + "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", null, "MOG", lcpCloudRegionId, null, tenantId, + null, null, null, Collections.EMPTY_MAP, Collections.EMPTY_MAP, Collections.EMPTY_MAP, Collections.EMPTY_MAP, instanceParams, false, 1, false, false, + null, null, null, null, null, null, + new VidNotions(InstantiationUI.TRANSPORT_SERVICE, ModelCategory.Transport, InstantiationUI.TRANSPORT_SERVICE, InstantiationType.Macro) + ); + return serviceInstantiation; + } + + protected void mockAaiClientAaiStatusOK() { + when(aaiClient.isNodeTypeExistsByName(eq(AsyncInstantiationBusinessLogicImpl.NAME_FOR_CHECK_AAI_STATUS), any())).thenReturn(false); + } } diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBusinessLogicTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBusinessLogicTest.java index 21b8f3f00..e2d182c06 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBusinessLogicTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBusinessLogicTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,69 +20,13 @@ package org.onap.vid.services; -import static com.google.common.collect.Maps.newHashMap; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.contains; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.hasItems; -import static org.hamcrest.Matchers.hasProperty; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.matchesPattern; -import static org.hamcrest.Matchers.not; -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.Mockito.doNothing; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.eq; -import static org.mockito.Mockito.mock; -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.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.STOPPED; -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.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import java.io.IOException; -import java.lang.reflect.Method; -import java.net.URL; -import java.time.Instant; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.Callable; -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 net.javacrumbs.jsonunit.JsonAssert; 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; import org.mockito.Mock; @@ -97,48 +41,64 @@ import org.onap.vid.aai.model.ResourceType; import org.onap.vid.changeManagement.RequestDetailsWrapper; import org.onap.vid.config.DataSourceConfig; import org.onap.vid.config.MockedAaiClientAndFeatureManagerConfig; -import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.dal.AsyncInstantiationRepository; import org.onap.vid.exceptions.MaxRetriesException; +import org.onap.vid.exceptions.NotFoundException; import org.onap.vid.exceptions.OperationNotAllowedException; import org.onap.vid.job.Job; import org.onap.vid.job.Job.JobStatus; import org.onap.vid.job.JobAdapter; import org.onap.vid.job.JobType; import org.onap.vid.job.JobsBrokerService; +import org.onap.vid.job.command.MsoRequestBuilder; +import org.onap.vid.job.command.ResourceCommandTest.FakeResourceCreator; import org.onap.vid.job.impl.JobDaoImpl; import org.onap.vid.job.impl.JobSharedData; -import org.onap.vid.model.Action; -import org.onap.vid.model.JobAuditStatus; -import org.onap.vid.model.JobAuditStatus.SourceStatus; -import org.onap.vid.model.NameCounter; -import org.onap.vid.model.ServiceInfo; -import org.onap.vid.model.serviceInstantiation.InstanceGroup; -import org.onap.vid.model.serviceInstantiation.Network; +import org.onap.vid.model.*; +import org.onap.vid.model.serviceInstantiation.BaseResource; import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; -import org.onap.vid.model.serviceInstantiation.VfModule; import org.onap.vid.model.serviceInstantiation.Vnf; import org.onap.vid.mso.MsoOperationalEnvironmentTest; -import org.onap.vid.mso.model.InstanceGroupInstantiationRequestDetails; +import org.onap.vid.mso.RestObject; import org.onap.vid.mso.model.ModelInfo; -import org.onap.vid.mso.model.NetworkInstantiationRequestDetails; -import org.onap.vid.mso.model.ServiceDeletionRequestDetails; import org.onap.vid.mso.model.ServiceInstantiationRequestDetails; -import org.onap.vid.mso.model.VfModuleInstantiationRequestDetails; -import org.onap.vid.mso.model.VfModuleMacro; -import org.onap.vid.mso.model.VnfInstantiationRequestDetails; -import org.onap.vid.mso.model.VolumeGroupRequestDetails; import org.onap.vid.mso.rest.AsyncRequestStatus; +import org.onap.vid.mso.rest.RequestStatus; 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; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; +import org.testng.annotations.*; + +import javax.inject.Inject; +import java.io.IOException; +import java.lang.reflect.Method; +import java.net.URL; +import java.time.*; +import java.util.Optional; +import java.util.*; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +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.core.Option.IGNORING_ARRAY_ORDER; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; +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.*; +import static org.onap.vid.job.Job.JobStatus.*; +import static org.onap.vid.testUtils.TestUtils.generateRandomAlphaNumeric; +import static org.testng.Assert.*; @ContextConfiguration(classes = {DataSourceConfig.class, SystemProperties.class, MockedAaiClientAndFeatureManagerConfig.class}) public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseTest { @@ -152,24 +112,42 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT @Mock private JobsBrokerService jobsBrokerServiceMock; + private AsyncInstantiationRepository asyncInstantiationRepository; + + 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 job with uuid .* from ServiceInfo table. Instances found: .*"; + "Failed to retrieve class .*ServiceInfo with jobId .* from table. no resource found"; private static final String DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE = "Service status does not allow deletion from the queue"; + private String uuidRegex = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"; + private org.hamcrest.Matcher uuidRegexMatcher = is(matchesPattern(uuidRegex)); + + @BeforeClass void initServicesInfoService() { MockitoAnnotations.initMocks(this); - asyncInstantiationBL = new AsyncInstantiationBusinessLogicImpl(dataAccessService, jobAdapterMock, jobsBrokerServiceMock, sessionFactory, aaiClient, featureManager, cloudOwnerService); + AsyncInstantiationRepository realAsyncInstantiationRepository = new AsyncInstantiationRepository(dataAccessService); + asyncInstantiationRepository = spy(realAsyncInstantiationRepository); + + auditService = new AuditServiceImpl(null, asyncInstantiationRepository); + + AsyncInstantiationBusinessLogicImpl realAsyncInstantiationBL = new AsyncInstantiationBusinessLogicImpl(jobAdapterMock, jobsBrokerServiceMock, sessionFactory, aaiClient, featureManager, cloudOwnerService, asyncInstantiationRepository, auditService); + asyncInstantiationBL = Mockito.spy(realAsyncInstantiationBL); + + msoRequestBuilder = new MsoRequestBuilder(asyncInstantiationBL, cloudOwnerService, aaiClient, featureManager); + createInstanceParamsMaps(); } @@ -182,16 +160,6 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT enableAddCloudOwnerOnMsoRequest(); } - private void enableAddCloudOwnerOnMsoRequest() { - enableAddCloudOwnerOnMsoRequest(true); - } - - private void enableAddCloudOwnerOnMsoRequest(boolean isActive) { - // always turn on the feature flag - when(featureManager.isActive(Features.FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST)).thenReturn(isActive); - when(aaiClient.getCloudOwnerByCloudRegionId(anyString())).thenReturn("att-aic"); - } - @BeforeMethod void resetServiceCount() { serviceCount = 0; @@ -215,13 +183,13 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT uuid = UUID.randomUUID(); addNewJob(uuid); createdDate = NOW.minusYears(1); - addNewServiceInfo(uuid, userId, "Old", createdDate, createdDate, COMPLETED, false); + addNewServiceInfo(uuid, userId, "Old", createdDate, createdDate, COMPLETED, false, false); uuid = UUID.randomUUID(); addNewJob(uuid); createdDate = NOW.minusDays(20); modifiedDate = NOW.minusDays(19); - addNewServiceInfo(uuid, userId, "Hidden", createdDate, modifiedDate, PAUSE, true); + addNewServiceInfo(uuid, userId, "Hidden", createdDate, modifiedDate, PAUSE, true, false); createNewTestServicesInfo(String.valueOf(userId)); } @@ -236,20 +204,20 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT addNewJob(uuid); createdDate = NOW.minusDays(40); - addNewServiceInfo(uuid, userId, "service instance 5", createdDate, createdDate, COMPLETED, false); - addNewServiceInfo(uuid, userId, "service instance 6", createdDate, createdDate, STOPPED, false); + addNewServiceInfo(uuid, userId, "service instance 5", createdDate, createdDate, COMPLETED, false, false); + addNewServiceInfo(uuid, userId, "service instance 6", createdDate, createdDate, STOPPED, false, false); uuid = UUID.randomUUID(); addNewJob(uuid); createdDate = NOW.minusDays(20); modifiedDate = NOW.minusDays(10); - addNewServiceInfo(uuid, userId, "service instance 4", createdDate, modifiedDate, STOPPED, false); - addNewServiceInfo(uuid, userId, "service instance 2", createdDate, modifiedDate, COMPLETED, false); - addNewServiceInfo(uuid, userId, "service instance 3", createdDate, modifiedDate, PAUSE, false); + 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); modifiedDate = NOW.minusDays(19); - addNewServiceInfo(uuid, userId, "service instance 1", createdDate, modifiedDate, FAILED, false); + addNewServiceInfo(uuid, userId, "service instance 1", createdDate, modifiedDate, FAILED, false, false); // Job to a different user @@ -257,7 +225,7 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT addNewJob(uuid); createdDate = NOW.minusMonths(2); - addNewServiceInfo(uuid, "2221", "service instance 7", createdDate, createdDate, COMPLETED, false); + addNewServiceInfo(uuid, "2221", "service instance 7", createdDate, createdDate, COMPLETED, false, false); } @@ -269,7 +237,7 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT uuid = UUID.randomUUID(); addNewJob(uuid, status); - addNewServiceInfo(uuid, null, "service instance 1", NOW, NOW, status, false); + addNewServiceInfo(uuid, null, "service instance 1", NOW, NOW, status, false, false); return uuid; @@ -292,7 +260,7 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT .toLocalDateTime(); } - private void addNewServiceInfo(UUID uuid, String userId, String serviceName, LocalDateTime createDate, LocalDateTime statusModifiedDate, Job.JobStatus status, boolean isHidden) { + 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); @@ -302,6 +270,7 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT serviceInfo.setPause(false); serviceInfo.setOwningEntityId("1234"); serviceInfo.setCreatedBulkDate(toDate(createDate)); + serviceInfo.setRetryEnabled(retryEnabled); serviceInfo.setHidden(isHidden); dataAccessService.saveDomainObject(serviceInfo, getPropsMap()); @@ -334,6 +303,39 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT dataAccessService.saveDomainObject(jobDao, getPropsMap()); } + private ServiceInstantiation addOriginalService(UUID jobId, String userID){ + addNewServiceInfo(jobId, userID, "name", LocalDateTime.now(), LocalDateTime.now(), COMPLETED_WITH_ERRORS, false, true); + assertThat(asyncInstantiationRepository.getServiceInfoByJobId(jobId).isRetryEnabled(), is(true)); + ServiceInstantiation originalServiceInstantiation = prepareServiceInstantiation(true, 1); + doReturn(originalServiceInstantiation).when(asyncInstantiationRepository).getJobRequest(jobId); + return originalServiceInstantiation; + } + + private void assertRetryDisabled(UUID jobId){ + assertThat(asyncInstantiationRepository.getServiceInfoByJobId(jobId).isRetryEnabled(), is(false)); + } + + private void assertNewJobExistsAsExpectedAfterRetry(List newJobIds, ServiceInstantiation expectedServiceInstantiation, UUID jobId, String userId){ + assertThat(newJobIds, hasSize(1)); + assertThat(newJobIds.get(0), not(equalTo(jobId))); + + ArgumentCaptor requestsCaptor = ArgumentCaptor.forClass(ServiceInstantiation.class); + ArgumentCaptor uuidsCaptor = ArgumentCaptor.forClass(UUID.class); + ArgumentCaptor jobTypeCaptor = ArgumentCaptor.forClass(JobType.class); + + verify(asyncInstantiationRepository).addJobRequest(uuidsCaptor.capture(), requestsCaptor.capture()); + verify(jobAdapterMock).createServiceInstantiationJob(jobTypeCaptor.capture(), requestsCaptor.capture(), uuidsCaptor.capture(), eq(userId), any(), anyString(), anyInt()); + verify(jobsBrokerServiceMock).add(any()); + + requestsCaptor.getAllValues().forEach(x->assertJsonEquals(expectedServiceInstantiation, x, whenIgnoringPaths( + "trackById", + "vnfs.2016-73_MOW-AVPN-vPE-BV-L.trackById", + "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", + "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" + ))); + + } + @Test public void testServiceInfoAreOrderedAsExpected() { int userId = 2222; @@ -343,6 +345,12 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT assertThat("Services aren't ordered as expected", serviceInfoListResult, equalTo(expectedOrderServiceInfo)); } + @Test + public void whenNewServiceInfoCreated_isRetryEnablesIsFalse() { + UUID uuid = createServicesInfoWithDefaultValues(PENDING); + assertFalse(asyncInstantiationRepository.getServiceInfoByJobId(uuid).isRetryEnabled()); + } + @Test public void testServiceInfoAreFilteredAsExpected() { int userId = 2222; @@ -364,9 +372,9 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT defineMocks(); ServiceInstantiation serviceInstantiationPayload = generateMockMacroServiceInstantiationPayload(isPause, createVnfList(vfModuleInstanceParamsMap, vnfInstanceParams, true), 2, true, PROJECT_NAME, false); final URL resource = this.getClass().getResource("/payload_jsons/bulk_service_request_unique_names.json"); - when(jobAdapterMock.createServiceInstantiationJob(any(), any(), any(), any(), anyString(), any())).thenAnswer(invocation -> { + when(jobAdapterMock.createServiceInstantiationJob(any(), any(), any(), any(), any(), anyString(), any())).thenAnswer(invocation -> { Object[] args = invocation.getArguments(); - return new MockedJob((String)args[4]); + return new MockedJob((String)args[5]); }); when(jobsBrokerServiceMock.add(any(MockedJob.class))).thenAnswer((Answer) invocation -> { @@ -376,13 +384,13 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT return job.getUuid(); }); - when(featureManager.isActive(Features.FLAG_SHIFT_VFMODULE_PARAMS_TO_VNF)).thenReturn(true); + when(asyncInstantiationBL.isPartOfBulk(any())).thenReturn(true); List uuids = asyncInstantiationBL.pushBulkJob(serviceInstantiationPayload, "az2016"); for (int i = 0; i < 2; i++) { UUID currentUuid = uuids.get(i); RequestDetailsWrapper result = - asyncInstantiationBL.generateMacroServiceInstantiationRequest(currentUuid, serviceInstantiationPayload, + msoRequestBuilder.generateMacroServiceInstantiationRequest(currentUuid, serviceInstantiationPayload, MockedJob.getJob(currentUuid).getOptimisticUniqueServiceInstanceName(), "az2016"); String unique = i==0 ? "" : String.format("_00%s", i); String expected = IOUtils.toString(resource, "UTF-8") @@ -403,7 +411,9 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT } protected void verifySearchNodeTypeByName(String unique, String resourceName, ResourceType serviceInstance) { - verify(aaiClient, times(1)).isNodeTypeExistsByName(resourceName + unique, serviceInstance); + String uniqueName = resourceName + unique; + verify(aaiClient, times(1)).isNodeTypeExistsByName(uniqueName, serviceInstance); + when(aaiClient.isNodeTypeExistsByName(uniqueName, serviceInstance)).thenReturn(true); } private HashMap getPropsMap() { @@ -423,25 +433,115 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT @Test(dataProvider="dataProviderForInstanceNames") public void pushBulkJob_bulkWithSize3_instancesNamesAreExactlyAsExpected(boolean isUserProvidedNaming, List expectedNames) { - int bulkSize = 3; + final ServiceInstantiation request = prepareServiceInstantiation(isUserProvidedNaming, 3); + + + asyncInstantiationBL.pushBulkJob(request, "myUserId"); + List serviceInfoList = dataAccessService.getList(ServiceInfo.class, getPropsMap()); + assertEquals(serviceInfoList.stream().map(ServiceInfo::getServiceInstanceName).collect(Collectors.toList()), expectedNames); + } + + protected ServiceInstantiation prepareServiceInstantiation(String projectName, boolean isUserProvidedNaming, int bulkSize) { final ServiceInstantiation request = generateMockMacroServiceInstantiationPayload( false, createVnfList(instanceParamsMapWithoutParams, Collections.EMPTY_LIST, true), - bulkSize, isUserProvidedNaming, PROJECT_NAME, true + bulkSize, isUserProvidedNaming, projectName, true ); // in "createServiceInstantiationJob()" we will probe the service, with the generated names configureMockitoWithMockedJob(); + return request; + } + protected ServiceInstantiation prepareServiceInstantiation(boolean isUserProvidedNaming, int bulkSize) { + return prepareServiceInstantiation(PROJECT_NAME, isUserProvidedNaming, bulkSize); + } - asyncInstantiationBL.pushBulkJob(request, "myUserId"); - List serviceInfoList = dataAccessService.getList(ServiceInfo.class, getPropsMap()); - assertEquals(serviceInfoList.stream().map(ServiceInfo::getServiceInstanceName).collect(Collectors.toList()), expectedNames); + + @Test + public void whenPushBulkJob_thenJobRequestIsSaveInJobRequestDb() { + Mockito.reset(asyncInstantiationRepository); + int bulkSize = 3; + final ServiceInstantiation request = prepareServiceInstantiation(true, bulkSize); + when(jobsBrokerServiceMock.add(any())).thenReturn(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID()); + List jobIds = asyncInstantiationBL.pushBulkJob(request, "abc"); + + ArgumentCaptor asyncJobRequestCaptor = ArgumentCaptor.forClass(JobAdapter.AsyncJobRequest.class); + ArgumentCaptor requestsCaptor = ArgumentCaptor.forClass(ServiceInstantiation.class); + ArgumentCaptor uuidsCaptor = ArgumentCaptor.forClass(UUID.class); + verify(asyncInstantiationRepository, times(bulkSize)).addJobRequest(uuidsCaptor.capture(), requestsCaptor.capture()); + verify(jobsBrokerServiceMock, times(bulkSize)).add(any()); + verify(jobAdapterMock, times(bulkSize)).createServiceInstantiationJob(any(), asyncJobRequestCaptor.capture(), any(), any(), any(), any(), any()); + + //verify that all for each job we saved an row in jobRequest table + assertThat(uuidsCaptor.getAllValues(), containsInAnyOrder(jobIds.toArray())); + + //assert that each real job we created with the adaptor, request is save in jobRequest table + assertThat(requestsCaptor.getAllValues(), containsInAnyOrder(asyncJobRequestCaptor.getAllValues().toArray())); + + assertThat(requestsCaptor.getAllValues(),everyItem(hasProperty("bulkSize", is(1)))); + + //assert that the requests that save in DB are the same as original request expect of the trackById + requestsCaptor.getAllValues().forEach(x->assertJsonEquals(request, x, whenIgnoringPaths( + "bulkSize", + "trackById", + "vnfs.2016-73_MOW-AVPN-vPE-BV-L.trackById", + "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", + "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" + ))); + + //assert that each trackById on all bulk jobs is unique + Set usedUUID = new HashSet<>(); + requestsCaptor.getAllValues().forEach(x->assertTrackByIdRecursively(x, uuidRegexMatcher, usedUUID)); + } + + @Test + public void whenRetryJob_prevJobRetryIsDisabled() { + reset(asyncInstantiationRepository); + UUID jobId = UUID.randomUUID(); + String userID = generateRandomAlphaNumeric(8); + addOriginalService(jobId, userID); + doReturn(mock(Map.class)).when(asyncInstantiationRepository).getResourceInfoByRootJobId(jobId); + asyncInstantiationBL.retryJob(jobId, userID); + assertRetryDisabled(jobId); + } + + @Test + public void whenRetryJobWithEditedData_prevJobRetryIsDisabled() { + reset(asyncInstantiationRepository); + UUID jobId = UUID.randomUUID(); + String userID = generateRandomAlphaNumeric(8); + addOriginalService(jobId, userID); + ServiceInstantiation editedServiceInstantiation = prepareServiceInstantiation("editedProjectName", true, 1); + asyncInstantiationBL.retryJob(editedServiceInstantiation, jobId, userID); + assertRetryDisabled(jobId); + } + + @Test + public void retryJobWithEditedData_expectedNewJobDifferentData() { + reset(asyncInstantiationRepository); + UUID jobId = UUID.randomUUID(); + String userID = generateRandomAlphaNumeric(8); + addOriginalService(jobId, userID); + ServiceInstantiation editedServiceInstantiation = prepareServiceInstantiation("editedProjectName", true, 1); + List newJobIds = asyncInstantiationBL.retryJob(editedServiceInstantiation, jobId, userID); + assertNewJobExistsAsExpectedAfterRetry(newJobIds, editedServiceInstantiation, jobId, userID); + } + + @Test + public void retryJob_expectedNewJob() { + reset(asyncInstantiationRepository); + UUID jobId = UUID.randomUUID(); + String userID = "az2016"; + ServiceInstantiation originalServiceInstantiation = addOriginalService(jobId, userID); + doReturn(mock(Map.class)).when(asyncInstantiationRepository).getResourceInfoByRootJobId(jobId); + List newJobIds = asyncInstantiationBL.retryJob(jobId, userID); + assertNewJobExistsAsExpectedAfterRetry(newJobIds, originalServiceInstantiation, jobId, userID); } - @Test(dataProvider = "aLaCarteAndMacroPayload") + @Test (dataProvider = "aLaCarteAndMacroPayload") public void generateMockServiceInstantiationPayload_serializeBackAndForth_sourceShouldBeTheSame(ServiceInstantiation serviceInstantiationPayload) throws IOException { ObjectMapper mapper = new ObjectMapper(); final String asString = mapper.writeValueAsString(serviceInstantiationPayload); @@ -449,7 +549,7 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT final ServiceInstantiation asObject = mapper.readValue(asString, ServiceInstantiation.class); final String asString2 = mapper.writeValueAsString(asObject); - JsonAssert.assertJsonEquals(asString, asString2); + assertJsonEquals(asString, asString2); } @DataProvider @@ -517,10 +617,6 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT }; } - private ServiceInstantiation generateMacroMockServiceInstantiationPayload(boolean isPause, Map vnfs) { - return generateMockMacroServiceInstantiationPayload(isPause, vnfs, 1, true, PROJECT_NAME, false); - } - @Test public void testUpdateServiceInfo_WithExistingServiceInfo_ServiceInfoIsUpdated() { UUID uuid = createFakedJobAndServiceInfo(); @@ -550,12 +646,12 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT return uuid; } - @Test(expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE) + @Test(expectedExceptions = NotFoundException.class, expectedExceptionsMessageRegExp = UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE) public void testUpdateServiceInfo_WithNonExisting_ThrowException() { asyncInstantiationBL.updateServiceInfo(UUID.randomUUID(), x -> x.setServiceInstanceName("not matter")); } - @Test(expectedExceptions = GenericUncheckedException.class, expectedExceptionsMessageRegExp = UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE) + @Test(expectedExceptions = NotFoundException.class, expectedExceptionsMessageRegExp = UPDATE_SERVICE_INFO_EXCEPTION_MESSAGE) public void testUpdateServiceInfo_WithDoubleServiceWithSameJobUuid_ThrowException() { UUID uuid = createFakedJobAndServiceInfo(); ServiceInfo serviceInfo = new ServiceInfo(); @@ -584,219 +680,10 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT @Test public void testCreateVnfEndpoint_useProvidedInstanceId() { String path = asyncInstantiationBL.getVnfInstantiationPath("myGreatId"); - assertThat(path, matchesPattern("/serviceInstances/v./myGreatId/vnfs")); - } - - @Test - public void createServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected() throws IOException { - createMacroServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(true); - } - - @Test - public void createServiceInfo_WithUserProvidedNamingFalseAndNoVfmodules_ServiceInfoIsAsExpected() throws IOException { - createMacroServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(false); - } - - private void createMacroServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(boolean withVfmodules) throws IOException { - when(featureManager.isActive(Features.FLAG_SHIFT_VFMODULE_PARAMS_TO_VNF)).thenReturn(true); - - ServiceInstantiation serviceInstantiationPayload = generateMockMacroServiceInstantiationPayload(true, - createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, Collections.EMPTY_LIST, false), - 1, - false, PROJECT_NAME, true); - URL resource; - if (withVfmodules) { - resource = this.getClass().getResource("/payload_jsons/bulk_service_request_ecomp_naming.json"); - } else { - // remove the vf modules - serviceInstantiationPayload.getVnfs().values().forEach(vnf -> vnf.getVfModules().clear()); - resource = this.getClass().getResource("/payload_jsons/bulk_service_request_no_vfmodule_ecomp_naming.json"); - } - - RequestDetailsWrapper result = - asyncInstantiationBL.generateMacroServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016"); - - String expected = IOUtils.toString(resource, "UTF-8"); - MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result); - } - - @Test - public void createALaCarteService_WithUserProvidedNamingFalse_RequestDetailsIsAsExpected() throws IOException { - ServiceInstantiation serviceInstantiationPayload = generateMockALaCarteServiceInstantiationPayload(false, - newHashMap(), - newHashMap(), - newHashMap(), - 1, - false, PROJECT_NAME, true, null); - - RequestDetailsWrapper result = - asyncInstantiationBL.generateALaCarteServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016"); - - URL resource = this.getClass().getResource("/payload_jsons/bulk_alacarte_service_request_naming_false.json"); - String expected = IOUtils.toString(resource, "UTF-8"); - MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result); - } - - @Test - public void generateALaCarteServiceInstantiationRequest_withVnfList_HappyFllow() throws IOException { - ServiceInstantiation serviceInstantiationPayload = generateALaCarteWithVnfsServiceInstantiationPayload(); - RequestDetailsWrapper result = - asyncInstantiationBL.generateALaCarteServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016"); - - String serviceExpected = IOUtils.toString(this.getClass().getResource("/payload_jsons/bulk_alacarte_service_request.json"), "UTF-8"); - MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(serviceExpected, result); + assertThat(path, equalTo("/serviceInstantiation/v7/serviceInstances/myGreatId/vnfs")); } - @Test(dataProvider = "createVnfParameters") - public void createVnfRequestDetails_detailsAreAsExpected(boolean isFlagAddCloudOwnerActive, boolean isUserProvidedNaming, String file) throws IOException { - final List vnfList = new ArrayList<>(createVnfList(new HashMap<>(), null, isUserProvidedNaming, true).values()); - ModelInfo siModelInfo = createServiceModelInfo(); - String serviceInstanceId = "aa3514e3-5a33-55df-13ab-12abad84e7aa"; - - //we validate that the asyncInstantiationBL call to getUniqueName by simulate that aai retrun that original - //vnf name is used, and only next picked name is free. - Mockito.reset(aaiClient); - mockAaiClientAaiStatusOK(); - when(aaiClient.isNodeTypeExistsByName(eq(VNF_NAME), eq(ResourceType.GENERIC_VNF))).thenReturn(true); - when(aaiClient.isNodeTypeExistsByName(eq(VNF_NAME+"_001"), eq(ResourceType.GENERIC_VNF))).thenReturn(false); - enableAddCloudOwnerOnMsoRequest(isFlagAddCloudOwnerActive); - - String expected = IOUtils.toString(this.getClass().getResource(file), "UTF-8"); - final RequestDetailsWrapper result = asyncInstantiationBL.generateVnfInstantiationRequest(vnfList.get(0), siModelInfo, serviceInstanceId, "pa0916"); - MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result); - } - - @DataProvider - public static Object[][] createVnfParameters() { - return new Object[][]{ - {true, true, "/payload_jsons/bulk_vnf_request.json"}, - {false, true, "/payload_jsons/bulk_vnf_request_without_cloud_owner.json"}, - {true, false, "/payload_jsons/bulk_vnf_request_without_instance_name.json"}, - }; - } - - @DataProvider - public static Object[][] vfModuleRequestDetails(Method test) { - return new Object[][]{ - {"cc3514e3-5a33-55df-13ab-12abad84e7cc", true, "/payload_jsons/vfmodule_instantiation_request.json"}, - {null, true, "/payload_jsons/vfmodule_instantiation_request_without_volume_group.json"}, - {null, false, "/payload_jsons/vfmodule_instantiation_request_without_instance_name.json"} - }; - } - - @Test(dataProvider = "vfModuleRequestDetails") - public void createVfModuleRequestDetails_detailsAreAsExpected(String volumeGroupInstanceId, boolean isUserProvidedNaming, String fileName) throws IOException { - - ModelInfo siModelInfo = createServiceModelInfo(); - ModelInfo vnfModelInfo = createVnfModelInfo(true); - List> instanceParams = ImmutableList.of(ImmutableMap.of("vmx_int_net_len", "24", - "vre_a_volume_size_0" , "120")); - Map supplementaryParams = ImmutableMap.of("vre_a_volume_size_0" , "100", - "availability_zone_0" , "mtpocdv-kvm-az01"); - VfModule vfModule = createVfModule("201673MowAvpnVpeBvL..AVPN_vRE_BV..module-1", "56e2b103-637c-4d1a-adc8-3a7f4a6c3240", - "72d9d1cd-f46d-447a-abdb-451d6fb05fa8", instanceParams, supplementaryParams, - (isUserProvidedNaming ? "vmxnjr001_AVPN_base_vRE_BV_expansion": null), "myVgName", true); - - String serviceInstanceId = "aa3514e3-5a33-55df-13ab-12abad84e7aa"; - String vnfInstanceId = "bb3514e3-5a33-55df-13ab-12abad84e7bb"; - - Mockito.reset(aaiClient); - mockAaiClientAaiStatusOK(); - enableAddCloudOwnerOnMsoRequest(); - when(aaiClient.isNodeTypeExistsByName(eq("vmxnjr001_AVPN_base_vRE_BV_expansion"), eq(ResourceType.VF_MODULE))).thenReturn(false); - - String expected = IOUtils.toString(this.getClass().getResource(fileName), "UTF-8"); - final RequestDetailsWrapper result = asyncInstantiationBL.generateVfModuleInstantiationRequest( - vfModule, siModelInfo, serviceInstanceId, - vnfModelInfo, vnfInstanceId, volumeGroupInstanceId, "pa0916"); - MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result); - } - - @DataProvider - public static Object[][] expectedAggregatedParams() { - return new Object[][]{ - {ImmutableMap.of("a", "b", "c", "d"), ImmutableMap.of("e", "f", "g", "h"), ImmutableList.of(ImmutableMap.of("c", "d", "a", "b", "e", "f", "g", "h"))}, - {ImmutableMap.of("a", "b", "c", "g"), ImmutableMap.of("c", "d", "e", "f"), ImmutableList.of(ImmutableMap.of("a", "b", "c", "d", "e", "f"))}, - {ImmutableMap.of(), ImmutableMap.of("c", "d", "e", "f"), ImmutableList.of(ImmutableMap.of("c", "d", "e", "f"))}, - {ImmutableMap.of("a", "b", "c", "g"), ImmutableMap.of(), ImmutableList.of(ImmutableMap.of("a", "b", "c", "g"))}, - {ImmutableMap.of(), ImmutableMap.of(), ImmutableList.of()}, - {null, ImmutableMap.of(), ImmutableList.of()}, - {ImmutableMap.of(), null, ImmutableList.of()}, - }; - } - - @Test(dataProvider = "expectedAggregatedParams") - public void testAggregateInstanceParamsAndSuppFile(Map instanceParams, Map suppParams, List> expected) { - List> aggParams = ((AsyncInstantiationBusinessLogicImpl)asyncInstantiationBL).aggregateAllInstanceParams(instanceParams, suppParams); - assertThat("Aggregated params are not as expected", aggParams, equalTo(expected)); - } - - @DataProvider - public static Object[][] expectedNetworkRequestDetailsParameters() { - return new Object[][]{ - {true, "/payload_jsons/network_instantiation_request.json"}, - {false, "/payload_jsons/network_instantiation_request_without_instance_name.json"} - }; - } - - @Test(dataProvider = "expectedNetworkRequestDetailsParameters") - public void createNetworkRequestDetails_detailsAreAsExpected(boolean isUserProvidedNaming, String filePath) throws IOException { - - final List networksList = new ArrayList<>(createNetworkList(null, isUserProvidedNaming, true).values()); - ModelInfo siModelInfo = createServiceModelInfo(); - String serviceInstanceId = "aa3514e3-5a33-55df-13ab-12abad84e7aa"; - - Mockito.reset(aaiClient); - mockAaiClientAaiStatusOK(); - enableAddCloudOwnerOnMsoRequest(); - when(aaiClient.isNodeTypeExistsByName(eq(VNF_NAME), eq(ResourceType.L3_NETWORK))).thenReturn(true); - when(aaiClient.isNodeTypeExistsByName(eq(VNF_NAME+"_001"), eq(ResourceType.L3_NETWORK))).thenReturn(false); - - String expected = IOUtils.toString(this.getClass().getResource(filePath), "UTF-8"); - final RequestDetailsWrapper result = asyncInstantiationBL.generateNetworkInstantiationRequest(networksList.get(0), siModelInfo, serviceInstanceId, "pa0916"); - MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result); - } - - @Test - public void createInstanceGroupRequestDetails_detailsAreAsExpected() throws IOException { - - final InstanceGroup instanceGroup = createInstanceGroup(true, Action.Create); - ModelInfo siModelInfo = createServiceModelInfo(); - String serviceInstanceId = "aa3514e3-5a33-55df-13ab-12abad84e7aa"; - - Mockito.reset(aaiClient); - mockAaiClientAaiStatusOK(); - enableAddCloudOwnerOnMsoRequest(); - when(aaiClient.isNodeTypeExistsByName(eq(VNF_GROUP_NAME), eq(ResourceType.INSTANCE_GROUP))).thenReturn(true); - when(aaiClient.isNodeTypeExistsByName(eq(VNF_GROUP_NAME+"_001"), eq(ResourceType.INSTANCE_GROUP))).thenReturn(false); - - String expected = IOUtils.toString(this.getClass().getResource("/payload_jsons/instance_group_instantiation_request.json"), "UTF-8"); - final RequestDetailsWrapper result = asyncInstantiationBL.generateInstanceGroupInstantiationRequest(instanceGroup, siModelInfo, serviceInstanceId, "az2018"); - MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result); - } - - @Test - public void checkIfNullProjectNameSentToMso(){ - ServiceInstantiation serviceInstantiationPayload = generateMockMacroServiceInstantiationPayload(true, - createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, Collections.EMPTY_LIST, false), - 1, - false,null,false); - RequestDetailsWrapper result = - asyncInstantiationBL.generateMacroServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016"); - JsonNode jsonNode = new ObjectMapper().valueToTree(result.requestDetails); - Assert.assertTrue(jsonNode.get("project").isNull()); - serviceInstantiationPayload = generateMockMacroServiceInstantiationPayload(true, - createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, Collections.EMPTY_LIST, false), - 1, - false,"not null",false); - result = asyncInstantiationBL.generateMacroServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016"); - jsonNode = new ObjectMapper().valueToTree(result.requestDetails); - Assert.assertTrue(jsonNode.get("project").get("projectName").asText().equalsIgnoreCase("not null")); - - - - } @Test public void pushBulkJob_macroServiceverifyCreatedDateBehavior_createdDateIsTheSameForAllServicesInSameBulk() { @@ -853,7 +740,9 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT Mockito.reset(jobAdapterMock); final Job job = mock(Job.class); when(job.getStatus()).thenReturn(PENDING); - when(jobAdapterMock.createServiceInstantiationJob(any(), any(), any(), any(), any(), any())).thenReturn(job); + when(job.getUuid()).thenReturn(UUID.fromString("db2c5ed9-1c19-41ce-9cb7-edf0d878cdeb")); + when(jobAdapterMock.createServiceInstantiationJob(any(), any(), any(), any(), any(), any(), any())).thenReturn(job); + when(jobsBrokerServiceMock.add(job)).thenReturn(UUID.randomUUID()); } @DataProvider @@ -869,7 +758,11 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT {"Paused", JobStatus.PAUSE}, {"Pause", JobStatus.PAUSE}, {"PENDING_MANUAL_TASK", JobStatus.PAUSE}, - {"UNLOCKED", JobStatus.IN_PROGRESS} + {"UNLOCKED", JobStatus.IN_PROGRESS}, + {"AbORtEd", COMPLETED_WITH_ERRORS}, + {"RoLlED_baCK", FAILED}, + {"ROllED_BAcK_To_ASsIGnED", FAILED}, + {"rOLLED_bACK_tO_CrEATeD", FAILED}, }; } @@ -879,131 +772,6 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT assertThat(asyncInstantiationBL.calcStatus(asyncRequestStatus), equalTo(expectedJobStatus)); } - private void createNewAuditStatus(JobAuditStatus auditStatus) - { - Date createdDate= auditStatus.getCreated(); - dataAccessService.saveDomainObject(auditStatus, getPropsMap()); - setDateToStatus(auditStatus.getSource(), auditStatus.getJobStatus(), createdDate); - } - - - - private static final String MSO_ARBITRARY_STATUS = "completed mso status"; - - @DataProvider - public static Object[][] auditStatuses(Method test) { - return new Object[][]{ - { - SourceStatus.VID, - new String[]{ JobStatus.PENDING.toString(), JobStatus.IN_PROGRESS.toString()} - }, - { SourceStatus.MSO, - new String[]{ JobStatus.IN_PROGRESS.toString(), MSO_ARBITRARY_STATUS } - } - }; - - } - - private void setDateToStatus(SourceStatus source, String status, Date date) { - List jobAuditStatusList = dataAccessService.getList(JobAuditStatus.class, getPropsMap()); - DaoUtils.tryWithSessionAndTransaction(sessionFactory, session -> { - jobAuditStatusList.stream() - .filter(auditStatus -> source.equals(auditStatus.getSource()) && status.equals(auditStatus.getJobStatus())) - .forEach(auditStatus -> { - auditStatus.setCreated(date); - session.saveOrUpdate(auditStatus); - }); - return 1; - }); - } - - - @Test(dataProvider = "auditStatuses") - public void givenSomeAuditStatuses_getStatusesOfSpecificSourceAndJobId_getSortedResultsMatchingToParameters(SourceStatus expectedSource, String [] expectedSortedStatuses){ - UUID jobUuid = UUID.randomUUID(); - List auditStatusList = com.google.common.collect.ImmutableList.of( - new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.VID, toDate(LocalDateTime.now().minusHours(2))), - new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, UUID.randomUUID(),"",toDate(LocalDateTime.now().minusHours(30))), - new JobAuditStatus(jobUuid, MSO_ARBITRARY_STATUS, SourceStatus.MSO, UUID.randomUUID(),"",toDate(LocalDateTime.now().minusHours(3))), - new JobAuditStatus(jobUuid, PENDING.toString(), SourceStatus.VID, toDate(LocalDateTime.now().minusHours(3))), - new JobAuditStatus(UUID.randomUUID(), PENDING.toString(), SourceStatus.VID, toDate(LocalDateTime.now().minusHours(3)))); - auditStatusList.forEach((auditStatus) -> createNewAuditStatus(auditStatus)); - List statuses = asyncInstantiationBL.getAuditStatuses(jobUuid, expectedSource); - List statusesList = statuses.stream().map(status -> status.getJobStatus()).collect(Collectors.toList()); - Assert.assertTrue(statuses.stream().allMatch(status -> (status.getSource().equals(expectedSource)&& status.getJobId().equals(jobUuid))),"Only statuses of " + expectedSource + " for " + jobUuid + " should be returned. Returned statuses: " + String.join(",", statusesList )); - assertThat(statusesList, contains(expectedSortedStatuses)); - } - - - - @Test - public void addSomeVidStatuses_getThem_verifyGetInsertedWithoutDuplicates(){ - ImmutableList statusesToBeInserted = ImmutableList.of(PENDING, IN_PROGRESS, IN_PROGRESS, COMPLETED); - UUID jobUuid = UUID.randomUUID(); - statusesToBeInserted.forEach(status-> - { - asyncInstantiationBL.auditVidStatus(jobUuid, status); - }); - List statusesFromDB = asyncInstantiationBL.getAuditStatuses(jobUuid, SourceStatus.VID).stream().map(auditStatus -> auditStatus.getJobStatus()).collect(Collectors.toList()); - List statusesWithoutDuplicates = statusesToBeInserted.stream().distinct().map(x -> x.toString()).collect(Collectors.toList()); - assertThat(statusesFromDB, is(statusesWithoutDuplicates)); - } - - @DataProvider - public static Object[][] msoAuditStatuses(Method test) { - UUID jobUuid = UUID.randomUUID(); - UUID requestId = UUID.randomUUID(); - return new Object[][]{ - { - jobUuid, - ImmutableList.of( - new JobAuditStatus(jobUuid, PENDING.toString(), SourceStatus.MSO, null, null), - new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, requestId, null), - new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, requestId, null), - new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, requestId, null), - new JobAuditStatus(jobUuid, COMPLETED.toString(), SourceStatus.MSO, requestId, null)), - ImmutableList.of(PENDING.toString(), IN_PROGRESS.toString(), COMPLETED.toString()), - "All distinct statuses should be without duplicates" - }, - { - jobUuid, - ImmutableList.of( - new JobAuditStatus(jobUuid, PENDING.toString(), SourceStatus.MSO, null, null), - new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, requestId, null), - new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, requestId, "aa"), - new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, requestId, "aa"), - new JobAuditStatus(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, UUID.randomUUID(), "aa"), - new JobAuditStatus(jobUuid, COMPLETED.toString(), SourceStatus.MSO, requestId, null)), - ImmutableList.of(PENDING.toString(), IN_PROGRESS.toString(), IN_PROGRESS.toString(),IN_PROGRESS.toString(), COMPLETED.toString()), - "Statuses should be without duplicates only with same requestId and additionalInfo" - - } - }; - } - - @Test(dataProvider = "msoAuditStatuses") - public void addSomeMsoStatuses_getThem_verifyGetInsertedWithoutDuplicates(UUID jobUuid, ImmutableList msoStatuses, ImmutableList expectedStatuses, String assertionReason) { - msoStatuses.forEach(status -> { - asyncInstantiationBL.auditMsoStatus(status.getJobId(), status.getJobStatus(), status.getRequestId() != null ? status.getRequestId().toString() : null, status.getAdditionalInfo()); - }); - List statusesFromDB = asyncInstantiationBL.getAuditStatuses(jobUuid, SourceStatus.MSO).stream().map(auditStatus -> auditStatus.getJobStatus()).collect(Collectors.toList()); - assertThat( assertionReason, statusesFromDB, is(expectedStatuses)); - } - - @Test - public void addSameStatusOfVidAndMso_verifyThatBothWereAdded(){ - UUID jobUuid = UUID.randomUUID(); - JobStatus sameStatus = IN_PROGRESS; - asyncInstantiationBL.auditMsoStatus(jobUuid, sameStatus.toString(),null,null); - asyncInstantiationBL.auditVidStatus(jobUuid, sameStatus); - List list = dataAccessService.getList( - JobAuditStatus.class, - String.format(" where JOB_ID = '%s'", jobUuid), - null, null); - Assert.assertEquals(list.size(),2); - assertThat(list,everyItem(hasProperty("jobStatus", is(sameStatus.toString())))); - } - @DataProvider public static Object[][] msoRequestStatusFiles(Method test) { return new Object[][]{ @@ -1026,7 +794,7 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT doNothing().when(jobsBrokerServiceMock).delete(any()); UUID uuid = createServicesInfoWithDefaultValues(PENDING); asyncInstantiationBL.deleteJob(uuid); - assertNotNull(asyncInstantiationBL.getServiceInfoByJobId(uuid).getDeletedAt(), "service info wasn't deleted"); + assertNotNull(asyncInstantiationRepository.getServiceInfoByJobId(uuid).getDeletedAt(), "service info wasn't deleted"); } @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = DELETE_SERVICE_INFO_STATUS_EXCEPTION_MESSAGE) @@ -1036,7 +804,7 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT try { asyncInstantiationBL.deleteJob(uuid); } catch (Exception e) { - assertNull(asyncInstantiationBL.getServiceInfoByJobId(uuid).getDeletedAt(), "service info shouldn't deleted"); + assertNull(asyncInstantiationRepository.getServiceInfoByJobId(uuid).getDeletedAt(), "service info shouldn't deleted"); throw e; } } @@ -1081,7 +849,7 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT try { asyncInstantiationBL.hideServiceInfo(uuid); } catch (Exception e) { - assertFalse(asyncInstantiationBL.getServiceInfoByJobId(uuid).isHidden(), "service info shouldn't be hidden"); + assertFalse(asyncInstantiationRepository.getServiceInfoByJobId(uuid).isHidden(), "service info shouldn't be hidden"); throw e; } } @@ -1126,16 +894,23 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT assertThat(asyncInstantiationBL.getUniqueName(name, type), equalTo(name+"_001")); } + @Test(enabled = false) //skip till we will handle macro bulk again... + public void whenNamedNotInUsedInAai_getSameNameTwice() { + String name = someCommonStepsAndGetName(); + ResourceType type = ResourceType.GENERIC_VNF; + when(aaiClient.isNodeTypeExistsByName(name, type)).thenReturn(false); + assertThat(asyncInstantiationBL.getUniqueName(name, type), equalTo(name)); + assertThat(asyncInstantiationBL.getUniqueName(name, type), equalTo(name)); + when(aaiClient.isNodeTypeExistsByName(name, type)).thenReturn(true); + assertThat(asyncInstantiationBL.getUniqueName(name, type), equalTo(name+"_001")); + } + private String someCommonStepsAndGetName() { mockAaiClientAaiStatusOK(); return UUID.randomUUID().toString(); } - private void mockAaiClientAaiStatusOK() { - when(aaiClient.isNodeTypeExistsByName(eq(AsyncInstantiationBusinessLogicImpl.NAME_FOR_CHECK_AAI_STATUS), any())).thenReturn(false); - } - - @Test(expectedExceptions=ExceptionWithRequestInfo.class) + @Test(expectedExceptions= ExceptionWithRequestInfo.class) public void whenAaiBadResponseCode_throwInvalidAAIResponseException() { String name = someCommonStepsAndGetName(); ResourceType type = ResourceType.SERVICE_INSTANCE; @@ -1171,7 +946,7 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(JobType.class); asyncInstantiationBL.pushBulkJob(request, "myUserId"); - verify(jobAdapterMock).createServiceInstantiationJob(argumentCaptor.capture(),any(),any(),anyString(), anyString(), anyInt()); + verify(jobAdapterMock).createServiceInstantiationJob(argumentCaptor.capture(),any(),any(),anyString(), anyString(), anyString(), anyInt()); assertTrue(argumentCaptor.getValue().equals(JobType.ALaCarteServiceInstantiation)); } @@ -1184,198 +959,285 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(JobType.class); asyncInstantiationBL.pushBulkJob(request, "myUserId"); - verify(jobAdapterMock).createServiceInstantiationJob(argumentCaptor.capture(),any(),any(),anyString(), anyString(), anyInt()); + verify(jobAdapterMock).createServiceInstantiationJob(argumentCaptor.capture(),any(),any(),anyString(), any(), anyString(), anyInt()); assertTrue(argumentCaptor.getValue().equals(JobType.MacroServiceInstantiation)); } - @Test - public void generateALaCarteServiceInstantiationRequest_verifyRequestIsAsExpected() throws IOException { - ServiceInstantiation serviceInstantiationPayload = generateALaCarteServiceInstantiationPayload(); - final URL resource = this.getClass().getResource("/payload_jsons/bulk_alacarte_service_request.json"); - RequestDetailsWrapper result = - asyncInstantiationBL.generateALaCarteServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016"); - String expected = IOUtils.toString(resource, "UTF-8"); - MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result); - } + @Test - public void generateALaCarteServiceDeletionRequest_verifyRequestIsAsExpected() throws IOException { - final URL resource = this.getClass().getResource("/payload_jsons/bulk_alacarte_service_deletion_request.json"); - String expected = IOUtils.toString(resource, "UTF-8"); + public void getALaCarteServiceDeletionPath_verifyPathIsAsExpected() { - ServiceInstantiation serviceDeletionPayload = generateALaCarteServiceDeletionPayload(); - RequestDetailsWrapper result = - asyncInstantiationBL.generateALaCarteServiceDeletionRequest(null, serviceDeletionPayload, "az2016"); + String expected = "/serviceInstantiation/v7/serviceInstances/f36f5734-e9df-4fbf-9f35-61be13f028a1"; - MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result); + String result = asyncInstantiationBL.getServiceDeletionPath("f36f5734-e9df-4fbf-9f35-61be13f028a1"); + + assertThat(expected,equalTo(result)); } @Test - public void getALaCarteServiceDeletionPath_verifyPathIsAsExpected() throws IOException { + public void getResumeRequestPath_verifyPathIsAsExpected() { - String expected = "/serviceInstantiation/v./serviceInstances/f36f5734-e9df-4fbf-9f35-61be13f028a1"; + String expected = "/orchestrationRequests/v7/rq1234d1-5a33-55df-13ab-12abad84e333/resume"; - String result = asyncInstantiationBL.getServiceDeletionPath("f36f5734-e9df-4fbf-9f35-61be13f028a1"); + String result = asyncInstantiationBL.getResumeRequestPath("rq1234d1-5a33-55df-13ab-12abad84e333"); - assertThat(result, matchesPattern(expected)); + assertThat(expected, equalTo(result)); } @Test public void getInstanceGroupsDeletionPath_verifyPathIsAsExpected() { - assertEquals(asyncInstantiationBL.getInstanceGroupDeletePath("9aada4af-0f9b-424f-ae21-e693bd3e005b"), "/serviceInstantiation/v7/instanceGroups/9aada4af-0f9b-424f-ae21-e693bd3e005b"); } + @Test + public void whenLcpRegionNotEmpty_thenCloudRegionIdOfResourceIsLegacy() { + String legacyCloudRegion = "legacyCloudRegion"; + Vnf vnf = new Vnf(new ModelInfo(), null, null, Action.Create.name(), null, "anyCloudRegion", legacyCloudRegion, + null, null, null, false, null, null, UUID.randomUUID().toString(), null, null); + assertThat(vnf.getLcpCloudRegionId(), equalTo(legacyCloudRegion)); + } + + @Test + public void whenLcpRegionNotEmpty_thenCloudRegionIdOfServiceIsLegacy() { + String legacyCloudRegion = "legacyCloudRegion"; + ServiceInstantiation service = new ServiceInstantiation(new ModelInfo(), null, null, null, null, null, null, + null, null, "anyCloudRegion", legacyCloudRegion, null, null, null, null, null, null, null, null, null, + false, 1,false, false, null, null, Action.Create.name(), UUID.randomUUID().toString(), null, null, null); + assertThat(service.getLcpCloudRegionId(), equalTo(legacyCloudRegion)); + } + @DataProvider - public static Object[][] testBuildVnfInstanceParamsDataProvider(Method test) { + public static Object[][] getJobTypeByRequest_verifyResultAsExpectedDataProvider() { return new Object[][]{ - { - Collections.EMPTY_LIST, - ImmutableList.of( - ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2")), - ImmutableList.of(ImmutableMap.of("k3","v3","k2","v2")) - ), - true, - ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2","k3","v3")) - }, - { - ImmutableList.of(ImmutableMap.of("j1", "w1", "k1","v1", "vnf_name","w2", "vf_module_name","w3")), //vnf_name, vf_module_name are excluded - ImmutableList.of( - ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2")), - ImmutableList.of(ImmutableMap.of("k3","v3","k2","v2")), - ImmutableList.of(Collections.EMPTY_MAP), - Collections.singletonList(null) - ), - true, - ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2","k3","v3","j1", "w1")) - }, - { - Collections.EMPTY_LIST, - Arrays.asList(null, null), - true, - Collections.EMPTY_LIST //mso is expect to empty list and not list with empty map - }, - { - ImmutableList.of(Collections.EMPTY_MAP), - ImmutableList.of( - ImmutableList.of(Collections.EMPTY_MAP), - ImmutableList.of(Collections.EMPTY_MAP) - ), - true, - Collections.EMPTY_LIST //mso is expect to empty list and not list with empty map - }, - { - Collections.EMPTY_LIST, - ImmutableList.of( - ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2")), - ImmutableList.of(ImmutableMap.of("k3","v3","k2","v2")) - ), - false, - Collections.EMPTY_LIST //mso is expect to empty list and not list with empty map - }, - { - ImmutableList.of(ImmutableMap.of("j1", "w1", "k1","v1", "vnf_name","w2", "vf_module_name","w3")), - ImmutableList.of( - ImmutableList.of(Collections.EMPTY_MAP) - ), - false, - ImmutableList.of(ImmutableMap.of("j1", "w1", "k1","v1")) - }, - { - ImmutableList.of(ImmutableMap.of("vnf_name","w2", "vf_module_name", "w3", "j2", "w2", "j4","w4")), - ImmutableList.of( - ImmutableList.of(ImmutableMap.of("k1","v1","k2","v2")), - ImmutableList.of(ImmutableMap.of("k3","v3","k2","v2")) - ), - false, - ImmutableList.of(ImmutableMap.of("j2", "w2", "j4","w4")) - }, - + {false, Action.Create, JobType.MacroServiceInstantiation}, + {true, Action.Create, JobType.ALaCarteServiceInstantiation}, + {true, Action.Delete, JobType.ALaCarteService}, }; } - @Test(dataProvider="testBuildVnfInstanceParamsDataProvider") - public void testBuildVnfInstanceParams(List> currentVnfInstanceParams, - List>> vfModulesInstanceParams, - boolean isFeatureActive, - List> expectedResult){ - when(featureManager.isActive(Features.FLAG_SHIFT_VFMODULE_PARAMS_TO_VNF)).thenReturn(isFeatureActive); - List vfModules = - vfModulesInstanceParams.stream().map(params-> new VfModuleMacro(new ModelInfo(), null, null, params)).collect(Collectors.toList()); - List> actual = asyncInstantiationBL.buildVnfInstanceParams(currentVnfInstanceParams, vfModules); - assertThat(actual, equalTo(expectedResult)); + @Test(dataProvider = "getJobTypeByRequest_verifyResultAsExpectedDataProvider") + public void getJobTypeByRequest_verifyResultAsExpected(boolean isALaCarte, Action action, JobType expectedJobType) { + ServiceInstantiation service = createServiceWithIsALaCarteAndAction(isALaCarte, action); + assertThat(asyncInstantiationBL.getJobType(service), equalTo(expectedJobType)); + } + @NotNull + protected ServiceInstantiation createServiceWithIsALaCarteAndAction(boolean isALaCarte, Action action) { + return new ServiceInstantiation(new ModelInfo(), null, null, null, null, null, null, + null, null, null, null, null, null, null, null, null, null, null, null, null, + false, 1, false, isALaCarte, null, null, action.name(), + UUID.randomUUID().toString(), null, null, null); } - @Test - public void whenLcpRegionNotEmpty_thenCloudRegionIdOfResourceIsLegacy() { - String legacyCloudRegion = "legacyCloudRegion"; - Vnf vnf = new Vnf(new ModelInfo(), null, null, Action.Create.name(), null, "anyCloudRegion", legacyCloudRegion, null, null, null, false, null, null); - assertThat(vnf.getLcpCloudRegionId(), equalTo(legacyCloudRegion)); + @DataProvider + public static Object[][] isRetryEnabledForStatusDataProvider(Method test) { + return new Object[][]{ + {FAILED, true, true}, + {COMPLETED_WITH_ERRORS, true, true}, + {COMPLETED_WITH_NO_ACTION, true, false}, + {COMPLETED, true, false}, + {IN_PROGRESS, true, false}, + {FAILED, false, false}, + {COMPLETED_WITH_ERRORS, false, false}, + {COMPLETED, false, false}, + }; + } + @Test(dataProvider = "isRetryEnabledForStatusDataProvider") + public void whenUpdateServiceInfoAndAuditStatus_thenServiceInfoRowIsUpdatedAndIsRetryIsRight( + JobStatus jobStatus, boolean isRetryfeatureEnabled, boolean expectedIsRetry) { + when(featureManager.isActive(Features.FLAG_1902_RETRY_JOB)).thenReturn(isRetryfeatureEnabled); + UUID uuid = createFakedJobAndServiceInfo(); + asyncInstantiationBL.updateServiceInfoAndAuditStatus(uuid, jobStatus); + ServiceInfo serviceInfo = ((List)dataAccessService.getList(ServiceInfo.class, getPropsMap())). + stream().filter(x->x.getJobId().equals(uuid)).findFirst().get(); + assertEquals(jobStatus, serviceInfo.getJobStatus()); + + //we don't test serviceInfo.getStatusModifiedDate() because it's too complicated + assertEquals(expectedIsRetry, serviceInfo.isRetryEnabled()); } @Test - public void whenLcpRegionNotEmpty_thenCloudRegionIdOfServiceIsLegacy() { - String legacyCloudRegion = "legacyCloudRegion"; - ServiceInstantiation service = new ServiceInstantiation(new ModelInfo(), null, null, null, null, null, null, - null, null, "anyCloudRegion", legacyCloudRegion, null, null, null, null, null, null, null, null, - false, 1,false, false, null, null, Action.Create.name()); - assertThat(service.getLcpCloudRegionId(), equalTo(legacyCloudRegion)); + public void givenServiceWithNullTrackByIds_whenReplaceTrackByIds_thenAllLevelsHasTrackByIdWithUUID() { + ServiceInstantiation serviceInstantiation = FakeResourceCreator.createServiceWith2InstancesInEachLevel(Action.Create); + //assert for the given that all trackById are null + assertTrackByIdRecursively(serviceInstantiation, is(nullValue()), new HashSet<>()); + ServiceInstantiation modifiedServiceInstantiation = asyncInstantiationBL.prepareServiceToBeUnique(serviceInstantiation); + assertTrackByIdRecursively(modifiedServiceInstantiation, uuidRegexMatcher, new HashSet<>()); + } + + private void assertTrackByIdRecursively(BaseResource baseResource, org.hamcrest.Matcher matcher, Set usedUuids) { + assertThat(baseResource.getTrackById(), matcher); + if (baseResource.getTrackById()!=null) { + assertThat(usedUuids, not(hasItem(baseResource.getTrackById()))); + usedUuids.add(baseResource.getTrackById()); + } + baseResource.getChildren().forEach(x->assertTrackByIdRecursively(x, matcher, usedUuids)); } @Test - public void createVolumeGroup_verifyResultAsExpected() throws IOException { - final URL resource = this.getClass().getResource("/payload_jsons/volumegroup_instantiation_request.json"); - VfModule vfModule = createVfModule("201673MowAvpnVpeBvL..AVPN_vRE_BV..module-1", - "56e2b103-637c-4d1a-adc8-3a7f4a6c3240", - "72d9d1cd-f46d-447a-abdb-451d6fb05fa8", - Collections.emptyList(), - Collections.emptyMap(), - "vmxnjr001_AVPN_base_vRE_BV_expansion", - "myVgName", - true); - vfModule.getModelInfo().setModelInvariantId("ff5256d2-5a33-55df-13ab-12abad84e7ff"); - vfModule.getModelInfo().setModelVersion("1"); - ModelInfo vnfModelInfo = createVnfModelInfo(true); - RequestDetailsWrapper result = - asyncInstantiationBL.generateVolumeGroupInstantiationRequest(vfModule, - createServiceModelInfo(), - "ff3514e3-5a33-55df-13ab-12abad84e7ff", - vnfModelInfo, - "vnfInstanceId", - "az2016"); - String expected = IOUtils.toString(resource, "UTF-8"); - MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result); + public void givenServicefromDB_returnsTheBulkRequest() throws IOException { + ServiceInstantiation serviceInstantiation = TestUtils.readJsonResourceFileAsObject("/payload_jsons/VnfGroupCreate3Delete1None1Request.json", ServiceInstantiation.class); + UUID jobId = UUID.randomUUID(); + doReturn(serviceInstantiation).when(asyncInstantiationRepository).getJobRequest(jobId); + doReturn(mock(Map.class)).when(asyncInstantiationRepository).getResourceInfoByRootJobId(jobId); + ServiceInstantiation modifiedServiceInstantiation = asyncInstantiationBL.getBulkForRetry(jobId); + assertThat(modifiedServiceInstantiation, jsonEquals(serviceInstantiation).when(IGNORING_ARRAY_ORDER)); } @Test - public void getJobTypeByRequest_verifyResultAsExpected(){ - ServiceInstantiation service = new ServiceInstantiation(new ModelInfo(), null, null, null, null, null, null, - null, null, null, null, null, null, null, null, null, null, null, null, - false, 1,false, false, null, null, Action.Create.name()); - JobType jobType = asyncInstantiationBL.getJobType(service) ; - assertThat(jobType, equalTo(JobType.MacroServiceInstantiation)); - service = new ServiceInstantiation(new ModelInfo(), null, null, null, null, null, null, - null, null, null, null, null, null, null, null, null, null, null, null, - false, 1,false, true, null, null, Action.Create.name()); - jobType = asyncInstantiationBL.getJobType(service); - assertThat(jobType, equalTo(JobType.ALaCarteServiceInstantiation)); - service = new ServiceInstantiation(new ModelInfo(), null, null, null, null, null, null, - null, null, null, null, null, null, null, null, null, null, null, null, - false, 1,false, true, null, null, Action.Delete.name()); - jobType = asyncInstantiationBL.getJobType(service); - assertThat(jobType, equalTo(JobType.ALaCarteService)); + public void givenServiceFromDB_returnsResolvedData() throws IOException { + ServiceInstantiation serviceInstantiation = TestUtils.readJsonResourceFileAsObject("/payload_jsons/VnfGroupCreate3Delete1None1Request.json", ServiceInstantiation.class); + ServiceInstantiation expectedServiceInstantiation = TestUtils.readJsonResourceFileAsObject("/payload_jsons/VnfGroupCreate3Delete1None1RequestResolvedForRetry.json", ServiceInstantiation.class); + UUID jobId = UUID.randomUUID(); + AsyncRequestStatus asyncRequestStatus = TestUtils.readJsonResourceFileAsObject( + "/responses/mso/orchestrationRequestsVnf.json", + AsyncRequestStatus.class); + Map mockedResourceInfoMap = ImmutableMap.of( + "groupingservicefortest..ResourceInstanceGroup..0:001", new ResourceInfo("groupingservicefortest..ResourceInstanceGroup..0:001",jobId,"VNF_GROUP1_INSTANCE_ID", COMPLETED, asyncRequestStatus),// TODO case: delete completed + "ag5aav86u4j", new ResourceInfo("ag5aav86u4j",jobId, null, FAILED, asyncRequestStatus),// case: failed + "asedrftjko", new ResourceInfo("asedrftjko",jobId, "VNF_GROUP1_INSTANCE_ID_3", COMPLETED, asyncRequestStatus),//case: completed after retry failed + "rgedfdged4", new ResourceInfo("rgedfdged4", jobId,"VNF_GROUP1_INSTANCE_ID_4", COMPLETED, asyncRequestStatus ));// case: create completed + + doReturn(mockedResourceInfoMap).when(asyncInstantiationRepository).getResourceInfoByRootJobId(jobId); + ServiceInstantiation modifiedServiceInstantiation = asyncInstantiationBL.enrichBulkForRetry(serviceInstantiation,jobId); + assertThat(modifiedServiceInstantiation, jsonEquals(expectedServiceInstantiation).when(IGNORING_ARRAY_ORDER)); + } + + @DataProvider + public static Object[][] readStatusMsgDataProvider(Method test) throws IOException { + AsyncRequestStatus asyncRequestStatus = TestUtils.readJsonResourceFileAsObject( + "/responses/mso/orchestrationRequestsVnf.json", + AsyncRequestStatus.class); + return new Object[][]{ + {null, null}, + {new AsyncRequestStatus(), null}, + {new AsyncRequestStatus(new AsyncRequestStatus.Request()), null}, + {new AsyncRequestStatus(new AsyncRequestStatus.Request(new RequestStatus())), null}, + {asyncRequestStatus, "Vnf has been created successfully."} + }; + } + + @Test(dataProvider = "readStatusMsgDataProvider") + public void resourceInfoReadStatusMsg_returnsStatusMsgOrNull(AsyncRequestStatus asyncRequestStatus, String expected) { + ResourceInfo resourceInfo = new ResourceInfo("groupingservicefortest..ResourceInstanceGroup..0:001",UUID.randomUUID(),"VNF_GROUP1_INSTANCE_ID", COMPLETED, asyncRequestStatus); + String msg= asyncInstantiationBL.readStatusMsg(resourceInfo); + assertThat(msg, equalTo( expected)); + } + + @Test + public void testAddResourceInfoForOkResponse() { + reset(asyncInstantiationRepository); + String serviceInstanceId = "service-instance-id"; + UUID jobUuid = UUID.randomUUID(); + + asyncInstantiationBL.addResourceInfo(prepareSharedDataForAddResourceInfo(jobUuid), JobStatus.IN_PROGRESS, serviceInstanceId); + + ArgumentCaptor resourceInfoCaptor = ArgumentCaptor.forClass(ResourceInfo.class); + verify(asyncInstantiationRepository).saveResourceInfo(resourceInfoCaptor.capture()); + + ResourceInfo resourceInfo = resourceInfoCaptor.getValue(); + assertResourceInfoValues(resourceInfo, serviceInstanceId, jobUuid, JobStatus.IN_PROGRESS); + assertThat(resourceInfo.getErrorMessage(), is(nullValue())); + } + + private JobSharedData prepareSharedDataForAddResourceInfo(UUID jobUuid) { + ServiceInstantiation serviceInstantiation = mock(ServiceInstantiation.class); + when(serviceInstantiation.getTrackById()).thenReturn("track-by-id"); + return new JobSharedData(jobUuid, "", serviceInstantiation, ""); + } + + private void assertResourceInfoValues(ResourceInfo resourceInfo, String serviceInstanceId, UUID jobUuid, JobStatus jobStatus) { + assertThat(resourceInfo.getInstanceId(), equalTo(serviceInstanceId)); + assertThat(resourceInfo.getJobStatus(), equalTo(jobStatus)); + assertThat(resourceInfo.getRootJobId(), equalTo(jobUuid)); + assertThat(resourceInfo.getTrackById(), equalTo("track-by-id")); + } + + @DataProvider + public static Object[][] addResourceInfoWithError() { + String message = "Failed to create service instance"; + return new Object[][]{ + {500, message}, + {199, "{\"serviceException\":{\"messageId\":\"SVC2000\",\"text\":\"Error: " + message + "\"}}"} + }; } - protected ServiceInstantiation generateALaCarteServiceInstantiationPayload() { - return generateMockALaCarteServiceInstantiationPayload(false, Collections.EMPTY_MAP, Collections.EMPTY_MAP, Collections.EMPTY_MAP, 1, true, PROJECT_NAME, false, "VNF_API"); + @Test(dataProvider = "addResourceInfoWithError") + public void testAddResourceInfoForErrorResponse(int errorCode, String errorMessage) { + reset(asyncInstantiationRepository); + UUID jobUuid = UUID.randomUUID(); + + RestObject restObject = mock(RestObject.class); + when(restObject.getStatusCode()).thenReturn(errorCode); + when(restObject.getRaw()).thenReturn(errorMessage); + asyncInstantiationBL.addFailedResourceInfo(prepareSharedDataForAddResourceInfo(jobUuid), restObject); + + ArgumentCaptor resourceInfoCaptor = ArgumentCaptor.forClass(ResourceInfo.class); + verify(asyncInstantiationRepository).saveResourceInfo(resourceInfoCaptor.capture()); + + ResourceInfo resourceInfo = resourceInfoCaptor.getValue(); + assertResourceInfoValues(resourceInfo, null, jobUuid, JobStatus.FAILED); + assertThat(resourceInfo.getErrorMessage().request.requestStatus.getStatusMessage(), containsString("Failed to create service instance")); + assertThat(resourceInfo.getErrorMessage().request.requestStatus.getStatusMessage(), containsString(String.valueOf(errorCode))); + ZonedDateTime parsedDate = TimeUtils.parseZonedDateTime(resourceInfo.getErrorMessage().request.requestStatus.getTimestamp()); + assertThat(parsedDate.toLocalDate(), is(LocalDate.now())); + + doReturn(resourceInfo).when(asyncInstantiationRepository).getResourceInfoByTrackId(any()); + JobAuditStatus jobAuditStatus = auditService.getResourceAuditStatus(resourceInfo.getTrackById()); + assertThat(jobAuditStatus.getJobStatus(), equalTo("FAILED")); + assertThat(jobAuditStatus.getAdditionalInfo(), containsString("Failed to create service instance")); + assertThat(jobAuditStatus.getAdditionalInfo(), containsString(String.valueOf(errorCode))); + assertTrue(DateUtils.isSameDay(jobAuditStatus.getCreatedDate(), new Date())); } - private ServiceInstantiation generateALaCarteServiceDeletionPayload() { - return generateMockALaCarteServiceDeletionPayload(false, Collections.EMPTY_MAP, Collections.EMPTY_MAP, Collections.EMPTY_MAP, 1, true, PROJECT_NAME, false, "VNF_API", "1234567890"); + @DataProvider + public static Object[][] updateResourceInfoParameters() { + return new Object[][] { + {JobStatus.COMPLETED, "Instance was created successfully"}, + {JobStatus.FAILED, "Failed to create instance"} + }; + } + + @Test(dataProvider = "updateResourceInfoParameters") + public void testUpdateResourceInfo(JobStatus jobStatus, String message) { + reset(asyncInstantiationRepository); + UUID jobUuid = UUID.randomUUID(); + JobSharedData sharedData = new JobSharedData(jobUuid, "", mock(ServiceInstantiation.class),""); + + ResourceInfo resourceInfoMock = new ResourceInfo(); + resourceInfoMock.setTrackById(UUID.randomUUID().toString()); + doReturn(resourceInfoMock).when(asyncInstantiationRepository).getResourceInfoByTrackId(any()); + + AsyncRequestStatus asyncRequestStatus = asyncInstantiationBL.convertMessageToAsyncRequestStatus(message); + + asyncInstantiationBL.updateResourceInfo(sharedData, jobStatus, asyncRequestStatus); + + ArgumentCaptor resourceInfoCaptor = ArgumentCaptor.forClass(ResourceInfo.class); + verify(asyncInstantiationRepository).saveResourceInfo(resourceInfoCaptor.capture()); + + ResourceInfo resourceInfo = resourceInfoCaptor.getValue(); + assertThat(resourceInfo.getJobStatus(), equalTo(jobStatus)); + if (jobStatus == JobStatus.FAILED) { + assertThat(resourceInfo.getErrorMessage(), is(not(nullValue()))); + assertThat(resourceInfo.getErrorMessage().request.requestStatus.getStatusMessage(), equalTo(message)); + ZonedDateTime parsedDate = TimeUtils.parseZonedDateTime(resourceInfo.getErrorMessage().request.requestStatus.getTimestamp()); + assertThat(parsedDate.toLocalDate(), is(LocalDate.now())); + } else { + assertThat(resourceInfo.getErrorMessage(), is(nullValue())); + } + + JobAuditStatus jobAuditStatus = auditService.getResourceAuditStatus(resourceInfo.getTrackById()); + if (jobStatus == JobStatus.FAILED) { + assertThat(jobAuditStatus.getJobStatus(), equalTo("FAILED")); + assertThat(jobAuditStatus.getAdditionalInfo(), equalTo(message)); + } else { + assertThat(jobAuditStatus, is(nullValue())); + } + } static class MockedJob implements Job { @@ -1426,7 +1288,7 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT @Override public JobSharedData getSharedData() { - return new JobSharedData(uuid, "", null); + return new JobSharedData(uuid, "", null,""); } @Override @@ -1463,4 +1325,13 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT return optimisticUniqueServiceInstanceName; } } + + + @Test + public void testGetVfModuleReplacePath_asMSOexpected() + { + String path = asyncInstantiationBL.getVfModuleReplacePath("myService", "myVNF", "myVFModule"); + assertThat(path, equalTo("/serviceInstantiation/v7/serviceInstances/myService/vnfs/myVNF/vfModules/myVFModule/replace")); + + } } diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AuditServiceImplTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AuditServiceImplTest.java index bdb2a2834..ce5840bfc 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/AuditServiceImplTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/AuditServiceImplTest.java @@ -19,71 +19,88 @@ */ package org.onap.vid.services; -import org.glassfish.grizzly.http.util.HttpStatus; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.vid.dal.AsyncInstantiationRepository; import org.onap.vid.model.JobAuditStatus; +import org.onap.vid.mso.RestMsoImplementation; +import org.onap.vid.mso.RestObject; +import org.onap.vid.mso.rest.AsyncRequestStatus; import org.onap.vid.mso.rest.AsyncRequestStatusList; import org.onap.vid.testUtils.TestUtils; -import org.testng.annotations.BeforeClass; +import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import java.io.IOException; -import java.util.Date; import java.util.List; -import java.util.UUID; -import static java.util.stream.Collectors.toList; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.MockitoAnnotations.initMocks; +import static org.hamcrest.Matchers.equalTo; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; public class AuditServiceImplTest { + + @Mock + private RestMsoImplementation restMso; @Mock - private AsyncInstantiationBusinessLogic asyncInstantiationBL; + private AsyncInstantiationRepository asyncInstantiationRepository; @InjectMocks private AuditServiceImpl auditService; - @BeforeClass - public void init() { - initMocks(this); + @BeforeMethod + public void setUp() { + restMso = null; + asyncInstantiationRepository = null; + auditService = null; + MockitoAnnotations.initMocks(this); } @Test - public void setFailedAuditStatusFromMsoTest() { - - UUID jobUuid = UUID.randomUUID(); - String requestId = "1"; - int statusCode = HttpStatus.OK_200.getStatusCode(); - String msoResponse = "{}"; - - auditService.setFailedAuditStatusFromMso(jobUuid, requestId, statusCode, msoResponse); - - verify(asyncInstantiationBL, times(1)) - .auditMsoStatus( - Mockito.any(UUID.class), - Mockito.anyString(), - Mockito.anyString(), - Mockito.anyString()); + public void testGetRequestsIdsByServiceIdAndRequestTypeAndScope() throws Exception { + + String instanceId = "d40c8a82-cc04-45e5-a0f6-0c9394c8f8d2"; + //the request id in multipleOrchestrationRequestsServiceInstance.json + String expectedRequestId = "fab854bf-e53c-415e-b3cc-b6fcce8414b2"; + String msoBasePath = "/someMsoPath/v2019?"; + + AsyncRequestStatusList asyncRequestStatusList = TestUtils.readJsonResourceFileAsObject( + "/responses/mso/multipleOrchestrationRequestsServiceInstance.json", + AsyncRequestStatusList.class); + RestObject msoResponse = new RestObject<>(); + msoResponse.set(asyncRequestStatusList); + msoResponse.setStatusCode(200); + when(restMso.GetForObject(eq(msoBasePath + "filter=serviceInstanceId:EQUALS:" + instanceId), + eq(AsyncRequestStatusList.class))) + .thenReturn(msoResponse); + TestUtils.testWithSystemProperty("mso.restapi.get.orc.reqs", msoBasePath, () -> { + List result = auditService + .retrieveRequestsFromMsoByServiceIdAndRequestTypeAndScope(instanceId, "createInstance", "service"); + assertThat(result.size(), equalTo(1)); + assertThat(result.get(0).requestId, equalTo(expectedRequestId)); + assertThat(result.get(0).startTime, equalTo("Mon, 04 Mar 2019 20:47:15 GMT")); + }); } @Test - public void testConvertMsoResponseStatusToJobAuditStatus_missingDateFromMso_shouldNoError() throws IOException { - final AsyncRequestStatusList asyncRequestStatusList = TestUtils.readJsonResourceFileAsObject("/orchestrationRequestsByServiceInstanceId.json", AsyncRequestStatusList.class); - - AuditServiceImpl auditService = new AuditServiceImpl(null, null); - - final List jobAuditStatuses = auditService.convertMsoResponseStatusToJobAuditStatus(asyncRequestStatusList.getRequestList(), "foo"); - - final List dates = jobAuditStatuses.stream().map(JobAuditStatus::getCreatedDate).collect(toList()); - final List statuses = jobAuditStatuses.stream().map(JobAuditStatus::getJobStatus).collect(toList()); + public void nextOrdinalAfter_givenNull_returnZero() { + assertThat( + auditService.nextOrdinalAfter(null), + equalTo(0) + ); + } - assertThat(dates, containsInAnyOrder(notNullValue(), notNullValue(), nullValue())); - assertThat(statuses, containsInAnyOrder("COMPLETE", "COMPLETE", "IN_PROGRESS")); + @Test + public void nextOrdinalAfter_givenX_returnXplus1() { + final int x = 6; + final JobAuditStatus jobAuditStatus = new JobAuditStatus(); + jobAuditStatus.setOrdinal(x); + + assertThat( + auditService.nextOrdinalAfter(jobAuditStatus), + equalTo(x + 1) + ); } } diff --git a/vid-app-common/src/test/java/org/onap/vid/services/JobsBrokerServiceTest.java b/vid-app-common/src/test/java/org/onap/vid/services/JobsBrokerServiceTest.java index 85cf23edd..40546e967 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/JobsBrokerServiceTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/JobsBrokerServiceTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,57 +21,22 @@ package org.onap.vid.services; -import static java.util.concurrent.TimeUnit.MILLISECONDS; -import static java.util.stream.Collectors.toList; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.both; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.onap.vid.job.Job.JobStatus.COMPLETED; -import static org.onap.vid.job.Job.JobStatus.CREATING; -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.RESOURCE_IN_PROGRESS; -import static org.onap.vid.job.Job.JobStatus.STOPPED; -import static org.onap.vid.utils.Streams.not; -import static org.testng.Assert.assertNotNull; -import static org.testng.AssertJUnit.assertEquals; - import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import java.lang.reflect.Method; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.Arrays; -import java.util.Date; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.ConcurrentSkipListSet; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeoutException; -import java.util.stream.IntStream; -import java.util.stream.Stream; -import javax.inject.Inject; import org.apache.commons.lang.RandomStringUtils; import org.apache.commons.lang3.RandomUtils; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; +import org.apache.commons.lang3.tuple.Pair; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.hibernate.SessionFactory; +import org.jetbrains.annotations.NotNull; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; import org.onap.portalsdk.core.domain.support.DomainVo; import org.onap.portalsdk.core.service.DataAccessService; import org.onap.portalsdk.core.util.SystemProperties; -import org.onap.vid.config.DataSourceConfig; -import org.onap.vid.config.JobAdapterConfig; import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.exceptions.OperationNotAllowedException; import org.onap.vid.job.Job; @@ -80,8 +45,12 @@ import org.onap.vid.job.JobType; import org.onap.vid.job.JobsBrokerService; import org.onap.vid.job.command.JobCommandFactoryTest; import org.onap.vid.job.impl.JobDaoImpl; +import org.onap.vid.job.impl.JobSchedulerInitializer; import org.onap.vid.job.impl.JobsBrokerServiceInDatabaseImpl; +import org.onap.vid.services.VersionService; import org.onap.vid.utils.DaoUtils; +import org.onap.vid.config.DataSourceConfig; +import org.onap.vid.config.JobAdapterConfig; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.Assert; @@ -90,6 +59,31 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import javax.inject.Inject; +import java.lang.reflect.Method; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.util.*; +import java.util.concurrent.*; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static java.util.stream.Collectors.toList; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.both; +import static org.hamcrest.Matchers.containsInAnyOrder; +import static org.mockito.Mockito.when; +import static org.onap.vid.job.Job.JobStatus.*; +import static org.onap.vid.utils.Streams.not; +import static org.onap.vid.testUtils.TestUtils.generateRandomAlphaNumeric; +import static org.testng.Assert.assertNotNull; +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertFalse; + @ContextConfiguration(classes = {DataSourceConfig.class, SystemProperties.class, JobAdapterConfig.class}) public class JobsBrokerServiceTest extends AbstractTestNGSpringContextTests { @@ -101,7 +95,7 @@ public class JobsBrokerServiceTest extends AbstractTestNGSpringContextTests { private final Set threadsIds = new ConcurrentSkipListSet<>(); - private final long FEW = 1000; + private final long FEW = 500; private final String JOBS_SHOULD_MATCH = "the jobs that added and those that pulled must be the same"; private final String JOBS_PEEKED_SHOULD_MATCH = "the jobs that added and those that peeked must be the same"; @@ -116,6 +110,23 @@ public class JobsBrokerServiceTest extends AbstractTestNGSpringContextTests { @Inject private SessionFactory sessionFactory; + @Mock + private VersionService versionService; + + @AfterMethod + public void threadsCounter() { + logger.info("participating threads count: " + threadsIds.size()); + threadsIds.clear(); + } + + @BeforeMethod + public void initializeBroker() { + MockitoAnnotations.initMocks(this); + when(versionService.retrieveBuildNumber()).thenReturn("aBuildNumber"); + broker = new JobsBrokerServiceInDatabaseImpl(dataAccessService, sessionFactory, 200, 0, versionService); + ((JobsBrokerServiceInDatabaseImpl) broker).deleteAll(); + } + /* - pulling jobs is limited to inserted ones - putting back allows getting the job again @@ -147,6 +158,7 @@ public class JobsBrokerServiceTest extends AbstractTestNGSpringContextTests { new JobCommandFactoryTest.MockedRequest(42,"nothing") , UUID.randomUUID(), userId, + null, "optimisticUniqueServiceInstanceName", RandomUtils.nextInt()); } @@ -234,18 +246,6 @@ public class JobsBrokerServiceTest extends AbstractTestNGSpringContextTests { threadsIds.add(Thread.currentThread().getId()); } - @AfterMethod - public void threadsCounter() { - logger.info("participating threads count: " + threadsIds.size()); - threadsIds.clear(); - } - - @BeforeMethod - public void initializeBroker() { - broker = new JobsBrokerServiceInDatabaseImpl(dataAccessService, sessionFactory, 200, 0); - ((JobsBrokerServiceInDatabaseImpl) broker).deleteAll(); - } - @Test public void givenSingleJob_getIt_verifySameJob() { final Job originalJob = waitForFutureJob(newJobAsync(broker)); @@ -254,6 +254,51 @@ public class JobsBrokerServiceTest extends AbstractTestNGSpringContextTests { assertThat(JOBS_SHOULD_MATCH, retrievedJob, is(originalJob)); } + @DataProvider + public static Object[][] allTopics() { + return JobSchedulerInitializer.WORKERS_TOPICS.stream() + .map(topic -> new Object[] { topic }) + .toArray(Object[][]::new); + } + + @Test(dataProvider = "allTopics") + public void givenJobFromSameBuild_pullJobs_jobIsPulled(Job.JobStatus topic) { + when(versionService.retrieveBuildNumber()).thenReturn("someVersion"); + Job mockedJob = createMockJob("user id", topic); + UUID uuid = broker.add(mockedJob); + assertEquals(uuid, broker.pull(topic, UUID.randomUUID().toString()).get().getUuid()); + } + + + @Test(dataProvider = "allTopics") + public void givenJobFromOtherBuild_pullJobs_noneIsPulled(Job.JobStatus topic) { + when(versionService.retrieveBuildNumber()).thenReturn("old"); + Job mockedJob = createMockJob("user id", topic); + broker.add(mockedJob); + when(versionService.retrieveBuildNumber()).thenReturn("new"); + assertFalse(broker.pull(topic, UUID.randomUUID().toString()).isPresent()); + } + + @Test + public void givenJobWithNullBuildAndJobWithRealBuild_pullJobs_jobsWithNonNullIsPulled() { + Job.JobStatus topic = PENDING; + + //push job with null build + when(versionService.retrieveBuildNumber()).thenReturn(null); + broker.add(createMockJob("user id", topic)); + + //push job with "aBuild" build + when(versionService.retrieveBuildNumber()).thenReturn("aBuild"); + UUID newJobId = broker.add(createMockJob("user id", topic)); + + //pull jobs while current build is still "aBuild". Only the non null build is pulled + assertEquals(newJobId, broker.pull(topic, UUID.randomUUID().toString()).get().getUuid()); + + //no more jobs to pull + assertFalse(broker.pull(topic, UUID.randomUUID().toString()).isPresent()); + } + + @Test public void givenManyJobs_getJobsAndPushThemBack_alwaysSeeAllOfThemWithPeek() throws InterruptedException { final List originalJobs = putALotOfJobs(broker); @@ -346,10 +391,10 @@ public class JobsBrokerServiceTest extends AbstractTestNGSpringContextTests { () -> createNewJob(14, UUID.randomUUID(), "userId", STOPPED,null, oldestDate), () -> createNewJob(22, UUID.randomUUID(), "userId", PENDING,null, oldestDate), () -> createNewJob(33, UUID.randomUUID(), "userId", PENDING,null, LocalDateTime.now().minusHours(2))), - 6, - 5, - PENDING, - "Broker should pull the only pending - first pending job by oldest job - ignore deleted,completed, failed, in-progress and stopped statuses" + 6, + 5, + PENDING, + "Broker should pull the only pending - first pending job by oldest job - ignore deleted,completed, failed, in-progress and stopped statuses" }, {ImmutableList.of( (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userId", IN_PROGRESS, UUID.randomUUID().toString(), oldestDate), @@ -374,7 +419,7 @@ public class JobsBrokerServiceTest extends AbstractTestNGSpringContextTests { () -> createNewJob(22, UUID.randomUUID(), "userId", PENDING, UUID.randomUUID().toString(), oldestDate), () -> createNewJob(33, UUID.randomUUID(), "userId", PENDING, null, LocalDateTime.now().minusHours(2)), () -> createNewJob(12, UUID.randomUUID(), "userId", RESOURCE_IN_PROGRESS, UUID.randomUUID().toString(), oldestDate) - ), + ), 3, 2, PENDING, @@ -411,10 +456,10 @@ public class JobsBrokerServiceTest extends AbstractTestNGSpringContextTests { (Jobber)() -> createNewJob(11, sameTemplate, "userId", FAILED, null, oldestDate, DELETED), () -> createNewJob(22, sameTemplate, "userId", STOPPED,null, oldestDate), () -> createNewJob(33, sameTemplate, "userId", PENDING,null, LocalDateTime.now().minusHours(2))), - 3, - 2, - PENDING, - "Broker should pull pending job when there is another job from this template that was deleted, although failed" + 3, + 2, + PENDING, + "Broker should pull pending job when there is another job from this template that was deleted, although failed" }, { ImmutableList.of( (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userA", IN_PROGRESS, null, oldestDate), @@ -475,10 +520,10 @@ public class JobsBrokerServiceTest extends AbstractTestNGSpringContextTests { () -> createNewJob(33, UUID.randomUUID(), "userId", IN_PROGRESS, null, LocalDateTime.now().minusHours(2)), () -> createNewJob(16, UUID.randomUUID(), "userId", RESOURCE_IN_PROGRESS, null, oldestDate) ), - 20, - 6, - IN_PROGRESS, - "Broker with in progress topic should pull only in-progress jobs - first in-progress job by oldest date - ignore all other statuses" + 20, + 6, + IN_PROGRESS, + "Broker with in progress topic should pull only in-progress jobs - first in-progress job by oldest date - ignore all other statuses" }, {ImmutableList.of( (Jobber)() -> createNewJob(11, UUID.randomUUID(), "userId", COMPLETED, null, oldestDate), @@ -541,14 +586,9 @@ public class JobsBrokerServiceTest extends AbstractTestNGSpringContextTests { @Test(dataProvider = "jobs") public void givenSomeJobs_pullNextJob_returnNextOrNothingAsExpected(List jobbers, int msoLimit, int expectedIndexSelected, Job.JobStatus topic, String assertionReason) { - JobsBrokerServiceInDatabaseImpl broker = new JobsBrokerServiceInDatabaseImpl(dataAccessService, sessionFactory, msoLimit, 20); - final List jobs = jobbers.stream().map(Jobber::toJob).collect(toList()); - for (JobDaoImpl job : jobs) { - Date modifiedDate = job.getModified(); - broker.add(job); - setModifiedDateToJob(job.getUuid(), modifiedDate); - } - Optional nextJob = broker.pull(topic, UUID.randomUUID().toString()); + JobsBrokerServiceInDatabaseImpl aBroker = new JobsBrokerServiceInDatabaseImpl(dataAccessService, sessionFactory, msoLimit, 20, versionService); + final List jobs = addJobsWithModifiedDate(jobbers, aBroker); + Optional nextJob = aBroker.pull(topic, UUID.randomUUID().toString()); boolean shouldAnyBeSelected = expectedIndexSelected >= 0; String pulledJobDesc = nextJob.map(job -> ". pulled job: " + job.toString()).orElse(". no job pulled"); Assert.assertEquals(nextJob.isPresent(), shouldAnyBeSelected, assertionReason+pulledJobDesc); @@ -557,10 +597,206 @@ public class JobsBrokerServiceTest extends AbstractTestNGSpringContextTests { } } + @NotNull + protected List addJobsWithModifiedDate(List jobbers, JobsBrokerService broker) { + final List jobs = jobbers.stream().map(Jobber::toJob).collect(toList()); + return addJobsWithModifiedDateByJobDao(jobs, broker); + } + + @NotNull + private List addJobsWithModifiedDateByJobDao(List jobs, JobsBrokerService broker) { + for (JobDaoImpl job : jobs) { + Date modifiedDate = job.getModified(); + broker.add(job); + setModifiedDateToJob(job.getUuid(), modifiedDate); + } + return jobs; + } + + @DataProvider + public static Object[][] jobsForTestingPendingResource(Method test) { + UUID templateId1 = UUID.fromString("311a9196-bbc5-47a1-8b11-bf0f9db1c7ca"); + UUID templateId2 = UUID.fromString("4f1522f9-642e-49f7-af75-a2f344085bcc"); + return new Object[][]{ + {ImmutableList.of( (Jobber) + () -> createNewJob(12, templateId1, "userId", PENDING_RESOURCE, null, LocalDateTime.now().minusSeconds(1), false), + () -> createNewJob(1, templateId2, "userId", CREATING, null, LocalDateTime.now().minusSeconds(1), false), + () -> createNewJob(2, UUID.randomUUID(), "userId", RESOURCE_IN_PROGRESS, null, LocalDateTime.now().minusSeconds(1), false), + () -> createNewJob(3, UUID.randomUUID(), "userId", IN_PROGRESS, null, LocalDateTime.now().minusSeconds(1), false), + () -> createNewJob(4, UUID.randomUUID(), "userId", COMPLETED, null, LocalDateTime.now().minusSeconds(1), false) + ), + 0, + "given there is only one in the queue in PENDING_RESOURCE and no other job with same templateId, then this job is selected" + }, + {ImmutableList.of( (Jobber) + () -> createNewJob(2, templateId1, "userId", PENDING_RESOURCE, null, LocalDateTime.now().minusSeconds(1), false), + () -> createNewJob(3, templateId1, "userId", PENDING_RESOURCE, null, LocalDateTime.now().minusSeconds(2), false), + () -> createNewJob(1, templateId1, "userId", PENDING_RESOURCE, null, LocalDateTime.now(), false) + ), + 2, + "given multiple jobs with same templateId in PENDING_RESOURCE, then job with lowest indexInBulk is selected" + }, + {ImmutableList.of( (Jobber) + () -> createNewJob(1, templateId2, "userId", PENDING_RESOURCE, null, LocalDateTime.now().minusSeconds(1), false), + () -> createNewJob(1, templateId1, "userId", PENDING_RESOURCE, null, LocalDateTime.now(), false) + ), + 1, + "given multiple jobs with same indexInBulk, then job with lowest templateId is selected" + }, + {ImmutableList.of( (Jobber) + () -> createNewJob(1, templateId1, "userId", PENDING_RESOURCE, null, LocalDateTime.now(), false), + () -> createNewJob(2, templateId2, "userId", PENDING_RESOURCE, null, LocalDateTime.now().minusSeconds(1), false) + ), + 0, + "given multiple jobs with different indexInBulk and different templateId, then job with lowest indexInBulk is selected" + }, + {ImmutableList.of( (Jobber) + () -> createNewJob(5, templateId1, "userId", PENDING_RESOURCE, null, LocalDateTime.now().minusMinutes(2), false), + () -> createNewJob(1, templateId1, "userId", PENDING_RESOURCE, "123", LocalDateTime.now(), false) + ), + -1, + "given there is already taken job with same templateId, then no job is selected" + }, + {ImmutableList.of( (Jobber) + () -> createNewJob(2, templateId1, "userId", PENDING_RESOURCE, null, LocalDateTime.now().minusMinutes(2), false), + () -> createNewJob(1, templateId1, "userId", PENDING_RESOURCE, "123", LocalDateTime.now(), false), + () -> createNewJob(9, templateId2, "userId", PENDING_RESOURCE, null, LocalDateTime.now(), false), + () -> createNewJob(8, templateId2, "userId", PENDING_RESOURCE, null, LocalDateTime.now(), false) + ), + 3, + "given 4 jobs, 2 jobs templateId1 but one of them is taken, and 2 jobs with templateId2, then select job with templateId2" + }, + {ImmutableList.of( (Jobber) + () -> createNewJob(5, templateId1, "userId", PENDING_RESOURCE, null, LocalDateTime.now().minusMinutes(1), false), + () -> createNewJob(1, templateId1, "userId", PENDING_RESOURCE, "123", LocalDateTime.now(), true) + ), + 0, + "given 2 jobs with same templateId, one of them is taken but deleted, then the other job is selected" + }, + {ImmutableList.of( (Jobber) + () -> createNewJob(5, templateId1, "userId", PENDING_RESOURCE, null, LocalDateTime.now().minusMinutes(1), false), + () -> createNewJob(1, templateId1, "userId", IN_PROGRESS, null, LocalDateTime.now(), false) + ), + -1, + "given 2 jobs with same templateId, one of them is IN_PROGRESS, then no job is selected" + }, + {ImmutableList.of( (Jobber) + () -> createNewJob(5, templateId1, "userId", PENDING_RESOURCE, null, LocalDateTime.now().minusMinutes(1), false), + () -> createNewJob(1, templateId1, "userId", RESOURCE_IN_PROGRESS, null, LocalDateTime.now(), false) + ), + -1, + "given 2 jobs with same templateId, one of them is RESOURCE_IN_PROGRESS, then no job is selected" + }, + {ImmutableList.of( (Jobber) + () -> createNewJob(6, templateId1, "userId", PENDING_RESOURCE, null, LocalDateTime.now().minusMinutes(2), false), + () -> createNewJob(5, templateId1, "userId", PENDING_RESOURCE, null, LocalDateTime.now().minusMinutes(1), false), + () -> createNewJob(1, templateId1, "userId", RESOURCE_IN_PROGRESS, null, LocalDateTime.now(), true) + ), + 1, + "given 3 jobs with same templateId, one of them is RESOURCE_IN_PROGRESS but deleted, then other job with lowest indexInBulk is selected" + }, + {ImmutableList.of( (Jobber) + () -> createNewJob(6, templateId1, "userId", PENDING_RESOURCE, null, LocalDateTime.now().minusMinutes(2), false), + () -> createNewJob(5, templateId1, "userId", PENDING_RESOURCE, null, LocalDateTime.now().minusMinutes(1), false), + () -> createNewJob(1, templateId1, "userId", RESOURCE_IN_PROGRESS, null, LocalDateTime.now(), false), + () -> createNewJob(12, templateId2, "userId", PENDING_RESOURCE, null, LocalDateTime.now().minusMinutes(2), false), + () -> createNewJob(11, templateId2, "userId", PENDING_RESOURCE, null, LocalDateTime.now(), false) + ), + 4, + "given 5 jobs, 3 with templateId1 that one of them is RESOURCE_IN_PROGRESS,"+ + "2 with templateId2 both in PENDING_RESOURCE, then job with lowest indexInBulk from templateId2 is selected" + + }, + {ImmutableList.of( (Jobber) + () -> createNewJob(6, templateId1, "userId", PENDING_RESOURCE, null, LocalDateTime.now().minusMinutes(2), true) + ), + -1, + "given 1 job in PENDING_RESOURCE but it's deleted, then no job is selected" + }, + {ImmutableList.of( (Jobber) + () -> createNewJob(20, templateId1, "userId", PENDING_RESOURCE, null, LocalDateTime.now().minusSeconds(1), false), + () -> createNewJob(1, templateId1, "userId", CREATING, null, LocalDateTime.now().minusSeconds(1), false), + () -> createNewJob(2, templateId1, "userId", COMPLETED, null, LocalDateTime.now().minusSeconds(1), false), + () -> createNewJob(3, templateId1, "userId", FAILED, null, LocalDateTime.now().minusSeconds(1), false), + () -> createNewJob(4, templateId1, "userId", COMPLETED_WITH_ERRORS, null, LocalDateTime.now().minusSeconds(1), false), + () -> createNewJob(5, templateId1, "userId", STOPPED, null, LocalDateTime.now().minusSeconds(1), false), + () -> createNewJob(6, templateId1, "userId", PAUSE, null, LocalDateTime.now().minusSeconds(1), false) + ), + 0, + "given multiple jobs with same templateId, 1 in PENDING_RESOURCE, and other are not in progress, "+ + "then the job in PENDING_RESOURCE is selected" + }, + {ImmutableList.of( (Jobber) + () -> createNewJob(1, UUID.randomUUID(), "userId", CREATING, null, LocalDateTime.now().minusSeconds(1), false), + () -> createNewJob(2, UUID.randomUUID(), "userId", COMPLETED, null, LocalDateTime.now().minusSeconds(1), false), + () -> createNewJob(3, UUID.randomUUID(), "userId", FAILED, null, LocalDateTime.now().minusSeconds(1), false), + () -> createNewJob(4, UUID.randomUUID(), "userId", COMPLETED_WITH_ERRORS, null, LocalDateTime.now().minusSeconds(1), false), + () -> createNewJob(5, UUID.randomUUID(), "userId", IN_PROGRESS, null, LocalDateTime.now().minusSeconds(1), false), + () -> createNewJob(6, UUID.randomUUID(), "userId", RESOURCE_IN_PROGRESS, null, LocalDateTime.now().minusSeconds(1), false) + ), + -1, + "given there is no job in PENDING_RESOURCE state, then no job is selected" + }, + {ImmutableList.of( (Jobber) + () -> createNewJob(6, null, "userId", PENDING_RESOURCE, null, LocalDateTime.now().minusMinutes(2), false) + ), + -1, + "given there is 1 job in PENDING_RESOURCE but without templateId, then no job is selected" + }, + }; + } + + @Test(dataProvider = "jobsForTestingPendingResource") + public void givenSomeJobs_pullPendingResource_returnNextOrNothingAsExpected(List jobbers, int expectedIndexSelected, String assertionReason) { + givenSomeJobs_pullNextJob_returnNextOrNothingAsExpected(jobbers, 1, expectedIndexSelected, PENDING_RESOURCE, assertionReason); + } + + public static JobDaoImpl createNewJob(Job.JobStatus status, String takenBy, long secondsOffset, boolean deleted) { + return createNewJob(1, UUID.randomUUID(), "af456", status, takenBy, LocalDateTime.now().minusSeconds(secondsOffset), deleted); + } + + @Test + public void givenSomeJobs_deleteOldFinalJobs_onlyExpectedJobsAreDeleted() { + long seconds = 999; + final List> jobs = ImmutableList.of( + //not final + Pair.of(createNewJob(IN_PROGRESS, null, seconds+1, false), true), + Pair.of(createNewJob(RESOURCE_IN_PROGRESS, null, seconds+1, false), true), + Pair.of(createNewJob(PENDING, null, seconds+1, false), true), + Pair.of(createNewJob(CREATING, null, seconds+1, false), true), + Pair.of(createNewJob(PENDING_RESOURCE, null, seconds+1, false), true), + Pair.of(createNewJob(PAUSE, null, seconds+1, false), true), + + //final + Pair.of(createNewJob(COMPLETED, null, seconds+1, false), false), + Pair.of(createNewJob(FAILED, null, seconds+1, false), false), + Pair.of(createNewJob(STOPPED, null, seconds+1, false), false), + Pair.of(createNewJob(COMPLETED_WITH_ERRORS, null, seconds+1, true), false), + Pair.of(createNewJob(COMPLETED_WITH_NO_ACTION, generateRandomAlphaNumeric(5), seconds+1, true), false), + + //final but not old + Pair.of(createNewJob(COMPLETED, generateRandomAlphaNumeric(5), seconds-2, false), true), + Pair.of(createNewJob(COMPLETED, generateRandomAlphaNumeric(5), seconds-400, false), true), + Pair.of(createNewJob(COMPLETED, generateRandomAlphaNumeric(5), 0, false), true) + ); + addJobsWithModifiedDateByJobDao(jobs.stream().map(Pair::getLeft).collect(Collectors.toList()), broker); + assertEquals(jobs.size(), broker.peek().size()); + + broker.deleteOldFinalJobs(seconds); + Stream> expectedJobs = jobs.stream() + .filter(Pair::getRight) + .map(x -> Pair.of( + x.getLeft().getUuid(), + x.getLeft().getStatus() + )); + assertThat(broker.peek().stream().map(x->Pair.of(x.getUuid(), x.getStatus())).collect(Collectors.toList()), + containsInAnyOrder(expectedJobs.toArray())); + } + @DataProvider public Object[][] topics() { return Arrays.stream(Job.JobStatus.values()) - .filter(not(t -> ImmutableList.of(PENDING, IN_PROGRESS, CREATING, RESOURCE_IN_PROGRESS).contains(t))) + .filter(not(t -> ImmutableList.of(PENDING, IN_PROGRESS, CREATING, RESOURCE_IN_PROGRESS, PENDING_RESOURCE).contains(t))) .map(v -> new Object[]{v}).collect(toList()).toArray(new Object[][]{}); } @@ -660,7 +896,7 @@ public class JobsBrokerServiceTest extends AbstractTestNGSpringContextTests { } @Test(dataProvider = "jobStatusesForSuccessDelete", expectedExceptions = NoJobException.class) - public void givenOneJob_deleteIt_canPeekOnItButCantPull(Job.JobStatus status) { + public void givenOneJob_deleteIt_canPeekOnItButCantPull(Job.JobStatus status) { final Job job = waitForFutureJob(newJobAsync(broker, status)); broker.delete(job.getUuid()); assertNotNull(((JobDaoImpl) broker.peek(job.getUuid())).getDeletedAt(), "job should be deleted"); diff --git a/vid-app-common/src/test/java/org/onap/vid/services/PortDetailsTranslatorTest.java b/vid-app-common/src/test/java/org/onap/vid/services/PortDetailsTranslatorTest.java index 117e4442f..33b8c7e3a 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/PortDetailsTranslatorTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/PortDetailsTranslatorTest.java @@ -53,7 +53,7 @@ public class PortDetailsTranslatorTest { " {" + " \"id\": \"4876980240\"," + " \"node-type\": \"l-interface\"," + - " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\"," + + " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/irma-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\"," + " \"properties\": {" + " \"interface-name\": \"zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\"," + " \"selflink\": \"https://network-aic.rdm5b.cci.att.com:9696/v2.0/ports/6de7bf87-6faa-4984-9492-18d1188b3d4a\"," + @@ -89,7 +89,7 @@ public class PortDetailsTranslatorTest { " {" + " \"id\": \"4876980240\"," + " \"node-type\": \"l-interface\"," + - " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\"," + + " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/irma-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\"," + " \"properties\": {" + " \"interface-name\": null," + " \"selflink\": \"https://network-aic.rdm5b.cci.att.com:9696/v2.0/ports/6de7bf87-6faa-4984-9492-18d1188b3d4a\"," + @@ -122,7 +122,7 @@ public class PortDetailsTranslatorTest { " {" + " \"id\": \"4876980240\"," + " \"node-type\": \"l-interface\"," + - " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\"," + + " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/irma-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\"," + " \"properties\": {" + " \"interface-name\": \"zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\"," + " \"selflink\": \"https://network-aic.rdm5b.cci.att.com:9696/v2.0/ports/6de7bf87-6faa-4984-9492-18d1188b3d4a\"," + @@ -155,7 +155,7 @@ public class PortDetailsTranslatorTest { " {" + " \"id\": \"4876980240\"," + " \"node-type\": \"l-interface\"," + - " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\"," + + " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/irma-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\"," + " \"properties\": {" + " \"interface-name\": \"\"," + " \"selflink\": \"https://network-aic.rdm5b.cci.att.com:9696/v2.0/ports/6de7bf87-6faa-4984-9492-18d1188b3d4a\"," + @@ -188,7 +188,7 @@ public class PortDetailsTranslatorTest { " {" + " \"id\": \"4876980240\"," + " \"node-type\": \"l-interface\"," + - " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/att-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\"," + + " \"url\": \"/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/irma-aic/rdm5b/tenants/tenant/460f35aeb53542dc9f77105066483e83/vservers/vserver/15e46e2f-4b98-4e06-9644-f0e6e35cc79a/l-interfaces/l-interface/zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\"," + " \"properties\": {" + " \"interface-name\": \"zrdm5bfprbVLBA005-vlbagent_aff_int_pktmirror_1_port-dr5jhyxva5ib\"," + " \"selflink\": \"https://network-aic.rdm5b.cci.att.com:9696/v2.0/ports/6de7bf87-6faa-4984-9492-18d1188b3d4a\"," + diff --git a/vid-app-common/src/test/java/org/onap/vid/services/RoleGenaratorServiceImplTest.java b/vid-app-common/src/test/java/org/onap/vid/services/RoleGenaratorServiceImplTest.java index 2ad68dd93..2bf73eece 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/RoleGenaratorServiceImplTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/RoleGenaratorServiceImplTest.java @@ -75,7 +75,7 @@ public class RoleGenaratorServiceImplTest { ServiceSubscription serviceSubscription = createServiceSubscription(); AaiResponse subscriberResponse = createServicesAaiResponse(serviceSubscription); - doReturn(subscriberResponse).when(aaiClientInterface).getSubscriberData(subscriber.globalCustomerId); + doReturn(subscriberResponse).when(aaiClientInterface).getSubscriberData(subscriber.globalCustomerId,false); String result = testSubject.generateRoleScript(firstRun); Assert.assertTrue(StringUtils.isNotBlank(result)); @@ -91,7 +91,7 @@ public class RoleGenaratorServiceImplTest { ServiceSubscription serviceSubscription = createServiceSubscription(); AaiResponse subscriberResponse = createServicesAaiResponse(serviceSubscription); - doReturn(subscriberResponse).when(aaiClientInterface).getSubscriberData(subscriber.globalCustomerId); + doReturn(subscriberResponse).when(aaiClientInterface).getSubscriberData(subscriber.globalCustomerId, false); String result = testSubject.generateRoleScript(firstRun); Assert.assertTrue(StringUtils.isNotBlank(result)); diff --git a/vid-app-common/src/test/java/org/onap/vid/testUtils/TestUtils.java b/vid-app-common/src/test/java/org/onap/vid/testUtils/TestUtils.java index 756d17534..5fc583274 100644 --- a/vid-app-common/src/test/java/org/onap/vid/testUtils/TestUtils.java +++ b/vid-app-common/src/test/java/org/onap/vid/testUtils/TestUtils.java @@ -20,10 +20,14 @@ package org.onap.vid.testUtils; +import static com.fasterxml.jackson.module.kotlin.ExtensionsKt.jacksonObjectMapper; import static java.util.function.Function.identity; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; import static org.apache.commons.beanutils.PropertyUtils.getPropertyDescriptors; +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; +import static org.apache.commons.text.CharacterPredicates.DIGITS; +import static org.apache.commons.text.CharacterPredicates.LETTERS; import static org.mockito.Matchers.any; import static org.mockito.Mockito.RETURNS_DEFAULTS; import static org.mockito.Mockito.mock; @@ -33,6 +37,7 @@ import static org.testng.Assert.fail; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.code.beanmatchers.BeanMatchers; import com.google.common.collect.ImmutableList; import java.beans.PropertyDescriptor; import java.io.ByteArrayInputStream; @@ -50,7 +55,9 @@ import javax.ws.rs.core.GenericType; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.commons.beanutils.BeanUtils; +import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.reflect.MethodUtils; +import org.apache.commons.text.RandomStringGenerator; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.json.JSONArray; @@ -62,8 +69,9 @@ import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.onap.portalsdk.core.util.SystemProperties; import org.onap.vid.asdc.beans.Service; +import org.onap.vid.mso.model.CloudConfiguration; import org.springframework.core.env.Environment; -import org.springframework.mock.env.MockEnvironment; +import org.testng.annotations.DataProvider; /** * Created by Oren on 6/7/17. @@ -127,13 +135,22 @@ public class TestUtils { return readJsonResourceFileAsObject(pathInResource, valueType, false); } - public static T readJsonResourceFileAsObject(String pathInResource, Class valueType, boolean ignoreUnknownProperties) - throws IOException { - ObjectMapper objectMapper = new ObjectMapper(); - objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, ignoreUnknownProperties); + public static T readJsonResourceFileAsObject(String pathInResource, Class valueType, + boolean failOnUnknownProperties) + throws IOException { + ObjectMapper objectMapper = jacksonObjectMapper() + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, failOnUnknownProperties); return objectMapper.readValue( - TestUtils.class.getResource(pathInResource), - valueType); + TestUtils.class.getResource(pathInResource), + valueType); + } + + public static String readFileAsString(String pathInResource) { + try { + return IOUtils.toString(TestUtils.class.getResource(pathInResource), "UTF-8"); + } catch (IOException e) { + throw new RuntimeException(e); + } } public static String[] allPropertiesOf(Class aClass) { @@ -169,6 +186,12 @@ public class TestUtils { } } + public static void registerCloudConfigurationValueGenerator() { + BeanMatchers.registerValueGenerator(() -> new CloudConfiguration( + randomAlphabetic(7), randomAlphabetic(7), randomAlphabetic(7) + ), CloudConfiguration.class); + } + public static class JavaxRsClientMocks { private final javax.ws.rs.client.Client fakeClient; @@ -277,4 +300,18 @@ public class TestUtils { } } + private static RandomStringGenerator generator = new RandomStringGenerator.Builder() + .withinRange('0', 'z') + .filteredBy(LETTERS, DIGITS) + .build(); + + public static String generateRandomAlphaNumeric(int length) { + return generator.generate(length); + } + + @DataProvider + public static Object[][] trueAndFalse() { + return new Object[][]{{true}, {false}}; + } + } -- cgit 1.2.3-korg