diff options
Diffstat (limited to 'vid-app-common/src/test/java/org/onap/vid/services')
8 files changed, 2057 insertions, 1493 deletions
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<AAITreeNode> nodesAccumulator = new ConcurrentSkipListSet<>(comparing(AAITreeNode::getUniqueNodeKey)); - ConcurrentLinkedQueue<String> 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<Relationship> 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<Relationship> 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<Relationship> 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<AAITreeNode> 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<AAIServiceTree.AaiRelationship> firstLevelTree = getPathsTree(); + + Tree<AAIServiceTree.AaiRelationship> secondLevelTree = aaiTreeNodeBuilder.getNextLevelInPathsTree(firstLevelTree, NodeType.GENERIC_VNF.getType()); + assertEquals(NodeType.GENERIC_VNF.getType(), secondLevelTree.getRootValue().type); + + Tree<AAIServiceTree.AaiRelationship> thirdLevelTree = aaiTreeNodeBuilder.getNextLevelInPathsTree(secondLevelTree, NodeType.INSTANCE_GROUP.getType()); + assertEquals(NodeType.INSTANCE_GROUP.getType(), thirdLevelTree.getRootValue().type); + } + + @Test + public void getNextLevelInPathsTreeTest_givenIrrelevantNode_expectedNull() { + Tree<AAIServiceTree.AaiRelationship> pathsTree = getPathsTree(); + + Tree<AAIServiceTree.AaiRelationship> 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<Relationship> 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<Relationship> 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<Relationship> 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<String, Object> 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<AAITreeNode> nodesAccumulator = new ConcurrentSkipListSet<>(comparing(AAITreeNode::getUniqueNodeKey)); + + Pair<AAITreeNode, List<Relationship>> 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<AAITreeNode> nodesAccumulator = new ConcurrentSkipListSet<>(comparing(AAITreeNode::getUniqueNodeKey)); + ExecutorService threadPool = Executors.newFixedThreadPool(5); + + AAITreeNode rootNode = createExpectedGroupNode(); + JsonNode relationshipJson = getRelationships(NodeType.GENERIC_VNF, NodeType.NETWORK); + List<Relationship> 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<JsonNode>) 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<AAIServiceTree.AaiRelationship> getPathsTree() { + Tree<AAIServiceTree.AaiRelationship> 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<SubscriberList> responseAllSubscribers; - @Mock - private AaiResponse<OperationalEnvironmentList> aaiResponseOpEnvList; - @Mock - private AaiResponse aaiResponse; - @Mock - private AaiResponse<JsonNode> 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<SubscriberList> 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<OperationalEnvironmentList> expectedEnvList = - aaiService.getOperationalEnvironments(anyString(), anyString()); - - assertThat(expectedEnvList).isEqualTo(aaiResponseOpEnvList); - } - - @Test - public void shouldGetSubscriberData() { - Services services = createAaiResponseServices(); - AaiResponse<Services> 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<ServiceSubscription> actualServiceSubscriptions = ((AaiResponse<Services>) actualResponse) - .getT().serviceSubscriptions.serviceSubscription; - - assertThat(actualResponse).isEqualTo(aaiResponseServices); - assertThat(actualServiceSubscriptions).allMatch(s -> s.isPermitted); - } - - @Test - public void shouldGetServiceInstanceEmptySearchResults() { - ServiceInstancesSearchResults serviceInstancesSearchResults = new ServiceInstancesSearchResults(); - AaiResponse<ServiceInstancesSearchResults> 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<Pnf> expectedResponse = new AaiResponse<>(Pnf.builder().build(), null, HttpStatus.SC_OK); - when(aaiClient.getSpecificPnf(anyString())).thenReturn(expectedResponse); - - AaiResponse<Pnf> 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<GetServicesAAIRespone> 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<GetTenantsResponse[]> 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<SubscriberList> responseAllSubscribers; + @Mock + private AaiResponse<OperationalEnvironmentList> aaiResponseOpEnvList; + @Mock + private AaiResponse aaiResponse; + @Mock + private AaiResponse<JsonNode> 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<SubscriberList> 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<OperationalEnvironmentList> expectedEnvList = + aaiService.getOperationalEnvironments(anyString(), anyString()); + + assertThat(expectedEnvList).isEqualTo(aaiResponseOpEnvList); + } + + @Test + public void shouldGetSubscriberData() { + Services services = createAaiResponseServices(); + AaiResponse<Services> 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<ServiceSubscription> actualServiceSubscriptions = ((AaiResponse<Services>) actualResponse) + .getT().serviceSubscriptions.serviceSubscription; + + assertThat(actualResponse).isEqualTo(aaiResponseServices); + assertThat(actualServiceSubscriptions).allMatch(s -> s.isPermitted); + } + + @Test + public void shouldGetServiceInstanceEmptySearchResults() { + ServiceInstancesSearchResults serviceInstancesSearchResults = new ServiceInstancesSearchResults(); + AaiResponse<ServiceInstancesSearchResults> 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<Pnf> expectedResponse = new AaiResponse<>(Pnf.builder().build(), null, HttpStatus.SC_OK); + when(aaiClient.getSpecificPnf(anyString())).thenReturn(expectedResponse); + + AaiResponse<Pnf> 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<VnfResult> vnfResults = Arrays.asList(vnfResult1, vnfResult2, vnfResult3); - AaiResponse<AaiGetVnfResponse> aaiResponseGetVnfResponse = createAaiResponseVnfResponse(vnfResults); + AaiResponse actualResponse = aaiService.getPNFData(anyString(), anyString(), anyString(), anyString(), + anyString(), anyString(), anyString()); - vnfResults = Arrays.asList(vnfResult1, vnfResult2); - AaiResponse<AaiGetVnfResponse> 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<AaiGetVnfResponse> actualResponseWithReturnedVnfs = - aaiService.getVNFData(GLOBAL_SUBSCRIBER_ID, SERVICE_TYPE); - AaiResponse<AaiGetVnfResponse> 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<GetServicesAAIRespone> 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<ServiceRelationships> expectedServiceInstanceResp = - new AaiResponse<>(relationsService, null, HttpStatus.SC_OK); - AaiResponse<String> 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<GetTenantsResponse[]> 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<AaiGetInstanceGroupsByCloudRegion> expectedResponse = - new AaiResponse<>(aaiGetInstanceGroupsByCloudRegion, null, HttpStatus.SC_OK); + List<VnfResult> vnfResults = Arrays.asList(vnfResult1, vnfResult2, vnfResult3); + AaiResponse<AaiGetVnfResponse> aaiResponseGetVnfResponse = createAaiResponseVnfResponse(vnfResults); - when(aaiClient.getInstanceGroupsByCloudRegion(anyString(), anyString(), anyString())) - .thenReturn(expectedResponse); - AaiResponse<AaiGetInstanceGroupsByCloudRegion> actualResponse = - aaiService.getInstanceGroupsByCloudRegion(anyString(), anyString(), anyString()); + vnfResults = Arrays.asList(vnfResult1, vnfResult2); + AaiResponse<AaiGetVnfResponse> 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<Result> results = Arrays.asList(resultWithModelType, resultWithEmptyModelType, resultWithoutModel, - resultWithoutValidModel); + AaiResponse<AaiGetVnfResponse> actualResponseWithReturnedVnfs = + aaiService.getVNFData(GLOBAL_SUBSCRIBER_ID, SERVICE_TYPE); + AaiResponse<AaiGetVnfResponse> 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<GetServiceModelsByDistributionStatusResponse> 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<Service> actualServices = aaiService.getServicesByDistributionStatus(); + assertThat(actualResponse).isEqualTo(aaiResponse); + } + + @Test + public void shouldGetAicZoneForPnf() { + ServiceRelationships relationsService = createServiceRelationships(); + AaiResponse<ServiceRelationships> expectedServiceInstanceResp = + new AaiResponse<>(relationsService, null, HttpStatus.SC_OK); + AaiResponse<String> 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<GetServiceModelsByDistributionStatusResponse> 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<AaiGetInstanceGroupsByCloudRegion> expectedResponse = + new AaiResponse<>(aaiGetInstanceGroupsByCloudRegion, null, HttpStatus.SC_OK); - when(aaiClient.getServiceModelsByDistributionStatus()).thenReturn(emptyResponse); - Collection<Service> actualServices = aaiService.getServicesByDistributionStatus(); + when(aaiClient.getInstanceGroupsByCloudRegion(anyString(), anyString(), anyString())) + .thenReturn(expectedResponse); + AaiResponse<AaiGetInstanceGroupsByCloudRegion> 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<Result> results = Arrays.asList(resultWithModelType, resultWithEmptyModelType, resultWithoutModel, + resultWithoutValidModel); - AaiResponse<LogicalLinkResponse> aaiResponseLogicalLinkResponse = - new AaiResponse<>(logicalLinkResponse, null, HttpStatus.SC_OK); - AaiResponse<ServiceRelationships> 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<GetServiceModelsByDistributionStatusResponse> serviceModelsByDistributionStatusResponse + = new AaiResponse<>(serviceModels, null, HttpStatus.SC_OK); + + Service[] expectedServices = { + createService("MODEL_TYPE1", "1"), + createService("", "2") + }; + + when(aaiClient.getServiceModelsByDistributionStatus()).thenReturn(serviceModelsByDistributionStatusResponse); + Collection<Service> actualServices = aaiService.getServicesByDistributionStatus(); + + assertThat(actualServices) + .hasSize(2) + .usingFieldByFieldElementComparator() + .containsExactly(expectedServices); + } + @Test + public void shouldReturnEmptyListOfServices() { + AaiResponse<GetServiceModelsByDistributionStatusResponse> emptyResponse + = new AaiResponse<>(null, null, HttpStatus.SC_OK); - List<String> expectedPnfs = Collections.singletonList(CORRECT_VALUE); - List<String> actualPnfs = aaiService.getServiceInstanceAssociatedPnfs(anyString(), anyString(), anyString()); + when(aaiClient.getServiceModelsByDistributionStatus()).thenReturn(emptyResponse); + Collection<Service> 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<LogicalLinkResponse> aaiResponseLogicalLinkResponse = + new AaiResponse<>(logicalLinkResponse, null, HttpStatus.SC_OK); + AaiResponse<ServiceRelationships> 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<String> expectedPnfs = Collections.singletonList(CORRECT_VALUE); + List<String> actualPnfs = aaiService.getServiceInstanceAssociatedPnfs(anyString(), anyString(), anyString()); + assertThat(actualPnfs).isEqualTo(expectedPnfs); + } - @Test - public void shouldGetInstanceGroupsByVnfInstanceId() { - List<InstanceGroupInfo> instanceGroupInfo = Collections.singletonList(new InstanceGroupInfo(CORRECT_VALUE)); - AaiGetRelatedInstanceGroupsByVnfId relatedInstanceGroups = new AaiGetRelatedInstanceGroupsByVnfId(); - relatedInstanceGroups.setRelationshipList(createRelationshipList()); - - AaiResponse<AaiGetRelatedInstanceGroupsByVnfId> correctCodeResponse = - new AaiResponse<>(relatedInstanceGroups, null, HttpStatus.SC_OK); - - AaiResponse<List<InstanceGroupInfo>> expectedCorrectCodeResponse = - new AaiResponse<>(instanceGroupInfo, null, HttpStatus.SC_OK); - AaiResponse<AaiGetRelatedInstanceGroupsByVnfId> expectedIncorrectCodeResponse = - new AaiResponse<>(relatedInstanceGroups, null, HttpStatus.SC_PAYMENT_REQUIRED); - List<InstanceGroupInfo> 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<InstanceGroupInfo> actualCorrectResponseObject = - (List<InstanceGroupInfo>) 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<String, Properties> regionsAndTenants = createRegionsAndTenantsMap(properties); - - AAITreeNode validTreeNode = new AAITreeNode(); - addAdditionalPropertiesToAaiTreeNode(validTreeNode); - List<AAITreeNode> validNodes = Arrays.asList(validTreeNode, validTreeNode); - - AAITreeNode validBranch = createTree(validNodes); - addAdditionalPropertiesToAaiTreeNode(validBranch); - List<AAITreeNode> testedBranches = Collections.singletonList(validBranch); - - AAITreeNode testedTree = createTree(testedBranches); - - RelatedVnf expectedVnf = createExpectedVnf(validBranch); - List<RelatedVnf> expectedResult = Collections.singletonList(expectedVnf); - - when(aaiServiceTree.buildAAITree(anyString(), any())).thenReturn(Collections.singletonList(testedTree)); - when(aaiClient.getCloudRegionAndTenantByVnfId(anyString())).thenReturn(regionsAndTenants); - - List<RelatedVnf> 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<PortDetailsTranslator.PortDetails> expectedDetailsList = Arrays.asList( - details, details, details - ); - - when(aaiClient.getPortMirroringSourcePorts(anyString())).thenReturn(expectedDetailsList); - List<PortDetailsTranslator.PortDetails> 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<String, Properties> createRegionsAndTenantsMap(Properties properties) { - Map<String, Properties> 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<AAITreeNode> children) { - AAITreeNode tree = new AAITreeNode(); - tree.addChildren(children); - tree.setId(PARENT_ID); - tree.setName(PARENT_NAME); - return tree; - } - - private void addAdditionalPropertiesToAaiTreeNode(AAITreeNode tree) { - Map<String, Object> 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<RelationshipData> relationsDataList = createRelationshipDataList(expectedValue); - return createRelationshipList(relationsDataList); - } - - @NotNull - private RelationshipList createRelationshipList(List<RelationshipData> 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<RelationshipData> 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<RelationshipData> 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<RelatedToProperty> 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<org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Relationship> 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<RelatedToProperty> 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<AaiGetVnfResponse> createAaiResponseVnfResponse(List<VnfResult> 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> instanceGroupInfo = Collections.singletonList(new InstanceGroupInfo(CORRECT_VALUE)); + AaiGetRelatedInstanceGroupsByVnfId relatedInstanceGroups = new AaiGetRelatedInstanceGroupsByVnfId(); + relatedInstanceGroups.setRelationshipList(createRelationshipList()); + + AaiResponse<AaiGetRelatedInstanceGroupsByVnfId> correctCodeResponse = + new AaiResponse<>(relatedInstanceGroups, null, HttpStatus.SC_OK); + + AaiResponse<List<InstanceGroupInfo>> expectedCorrectCodeResponse = + new AaiResponse<>(instanceGroupInfo, null, HttpStatus.SC_OK); + AaiResponse<AaiGetRelatedInstanceGroupsByVnfId> expectedIncorrectCodeResponse = + new AaiResponse<>(relatedInstanceGroups, null, HttpStatus.SC_PAYMENT_REQUIRED); + List<InstanceGroupInfo> 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<InstanceGroupInfo> actualCorrectResponseObject = + (List<InstanceGroupInfo>) 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<String, Properties> regionsAndTenants = createRegionsAndTenantsMap(properties); + + AAITreeNode validTreeNode = new AAITreeNode(); + addAdditionalPropertiesToAaiTreeNode(validTreeNode); + List<AAITreeNode> validNodes = Arrays.asList(validTreeNode, validTreeNode); + + AAITreeNode validBranch = createTree(validNodes); + addAdditionalPropertiesToAaiTreeNode(validBranch); + List<AAITreeNode> testedBranches = Collections.singletonList(validBranch); + + AAITreeNode testedTree = createTree(testedBranches); + + RelatedVnf expectedVnf = createExpectedVnf(validBranch); + List<RelatedVnf> 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<RelatedVnf> 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<PortDetailsTranslator.PortDetails> expectedDetailsList = Arrays.asList( + details, details, details + ); + + when(aaiClient.getPortMirroringSourcePorts(anyString())).thenReturn(expectedDetailsList); + List<PortDetailsTranslator.PortDetails> 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<String, Properties> createRegionsAndTenantsMap(Properties properties) { + Map<String, Properties> 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<AAITreeNode> 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<String, Object> 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<RelationshipData> relationsDataList = createRelationshipDataList(expectedValue); + return createRelationshipList(relationsDataList); + } + + @NotNull + private RelationshipList createRelationshipList(List<RelationshipData> 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<RelationshipData> 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<RelationshipData> 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<RelatedToProperty> 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<org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Relationship> 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<RelatedToProperty> 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<AaiGetVnfResponse> createAaiResponseVnfResponse(List<VnfResult> 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<Map<String,String>> 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<String, Network> createNetworkList(List vnfInstanceParams, boolean isUserProvidedNaming, boolean isALaCarte) { - Map<String, Network> 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<String, Network> createNetworkList(List instanceParams, List<NetworkDetails> networkDetails, boolean isALaCarte) { + Stream<Network> 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<AsyncRequestStatus> asyncRequestStatusResponseAsRestObject(String msoStatus) { + public static RestObject<AsyncRequestStatus> asyncRequestStatusResponseAsRestObject(String msoStatus) { return asyncRequestStatusResponseAsRestObject(msoStatus, 200); } - protected RestObject<AsyncRequestStatus> asyncRequestStatusResponseAsRestObject(String msoStatus, int httpStatusCode) { + public static RestObject<AsyncRequestStatus> asyncRequestStatusResponseAsRestObject(String msoStatus, int httpStatusCode) { RestObject<AsyncRequestStatus> 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> networkDetails) { + Map<String, Network> 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<String, Vnf> vnfs) { + return generateMockMacroServiceInstantiationPayload(isPause, vnfs, 1, true, PROJECT_NAME, false); + } + + protected ServiceInstantiation generatePre1806MacroTransportServiceInstantiationPayload(String tenantId, String lcpCloudRegionId) { + List<Map<String, String>> 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<UUID> newJobIds, ServiceInstantiation expectedServiceInstantiation, UUID jobId, String userId){ + assertThat(newJobIds, hasSize(1)); + assertThat(newJobIds.get(0), not(equalTo(jobId))); + + ArgumentCaptor<ServiceInstantiation> requestsCaptor = ArgumentCaptor.forClass(ServiceInstantiation.class); + ArgumentCaptor<UUID> uuidsCaptor = ArgumentCaptor.forClass(UUID.class); + ArgumentCaptor<JobType> 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; @@ -344,6 +346,12 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT } @Test + public void whenNewServiceInfoCreated_isRetryEnablesIsFalse() { + UUID uuid = createServicesInfoWithDefaultValues(PENDING); + assertFalse(asyncInstantiationRepository.getServiceInfoByJobId(uuid).isRetryEnabled()); + } + + @Test public void testServiceInfoAreFilteredAsExpected() { int userId = 2222; createNewTestServicesInfoForFilter(String.valueOf(userId)); @@ -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<UUID>) 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<UUID> uuids = asyncInstantiationBL.pushBulkJob(serviceInstantiationPayload, "az2016"); for (int i = 0; i < 2; i++) { UUID currentUuid = uuids.get(i); RequestDetailsWrapper<ServiceInstantiationRequestDetails> 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<String, Object> getPropsMap() { @@ -423,25 +433,115 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT @Test(dataProvider="dataProviderForInstanceNames") public void pushBulkJob_bulkWithSize3_instancesNamesAreExactlyAsExpected(boolean isUserProvidedNaming, List<String> expectedNames) { - int bulkSize = 3; + final ServiceInstantiation request = prepareServiceInstantiation(isUserProvidedNaming, 3); + + + asyncInstantiationBL.pushBulkJob(request, "myUserId"); + List<ServiceInfo> 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<ServiceInfo> 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<UUID> jobIds = asyncInstantiationBL.pushBulkJob(request, "abc"); + + ArgumentCaptor<JobAdapter.AsyncJobRequest> asyncJobRequestCaptor = ArgumentCaptor.forClass(JobAdapter.AsyncJobRequest.class); + ArgumentCaptor<ServiceInstantiation> requestsCaptor = ArgumentCaptor.forClass(ServiceInstantiation.class); + ArgumentCaptor<UUID> 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<String> 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<UUID> 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<UUID> 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<String, Vnf> 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<ServiceInstantiationRequestDetails> 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<ServiceInstantiationRequestDetails> 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<ServiceInstantiationRequestDetails> 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<Vnf> 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<VnfInstantiationRequestDetails> 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<Map<String, String>> instanceParams = ImmutableList.of(ImmutableMap.of("vmx_int_net_len", "24", - "vre_a_volume_size_0" , "120")); - Map<String, String> 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<VfModuleInstantiationRequestDetails> 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<String, String> instanceParams, Map<String, String> suppParams, List<VfModuleInstantiationRequestDetails.UserParamMap<String, String>> expected) { - List<VfModuleInstantiationRequestDetails.UserParamMap<String, String>> 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<Network> 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<NetworkInstantiationRequestDetails> 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<InstanceGroupInstantiationRequestDetails> 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<ServiceInstantiationRequestDetails> 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<JobAuditStatus> 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<JobAuditStatus> 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<JobAuditStatus> statuses = asyncInstantiationBL.getAuditStatuses(jobUuid, expectedSource); - List<String> 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<JobStatus> statusesToBeInserted = ImmutableList.of(PENDING, IN_PROGRESS, IN_PROGRESS, COMPLETED); - UUID jobUuid = UUID.randomUUID(); - statusesToBeInserted.forEach(status-> - { - asyncInstantiationBL.auditVidStatus(jobUuid, status); - }); - List<String> statusesFromDB = asyncInstantiationBL.getAuditStatuses(jobUuid, SourceStatus.VID).stream().map(auditStatus -> auditStatus.getJobStatus()).collect(Collectors.toList()); - List<String> 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<JobAuditStatus> msoStatuses, ImmutableList<String> expectedStatuses, String assertionReason) { - msoStatuses.forEach(status -> { - asyncInstantiationBL.auditMsoStatus(status.getJobId(), status.getJobStatus(), status.getRequestId() != null ? status.getRequestId().toString() : null, status.getAdditionalInfo()); - }); - List<String> 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<JobAuditStatus> 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<JobType> 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<JobType> 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<ServiceInstantiationRequestDetails> 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<ServiceDeletionRequestDetails> 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<Map<String, String>> currentVnfInstanceParams, - List<List<Map<String, String>>> vfModulesInstanceParams, - boolean isFeatureActive, - List<Map<String,String>> expectedResult){ - when(featureManager.isActive(Features.FLAG_SHIFT_VFMODULE_PARAMS_TO_VNF)).thenReturn(isFeatureActive); - List<VfModuleMacro> vfModules = - vfModulesInstanceParams.stream().map(params-> new VfModuleMacro(new ModelInfo(), null, null, params)).collect(Collectors.toList()); - List<Map<String,String>> 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<ServiceInfo>)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<String> 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<VolumeGroupRequestDetails> 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<String, ResourceInfo> 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<ResourceInfo> 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<ResourceInfo> 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<ResourceInfo> 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<AsyncRequestStatusList> 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<AsyncRequestStatus.Request> 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<JobAuditStatus> jobAuditStatuses = auditService.convertMsoResponseStatusToJobAuditStatus(asyncRequestStatusList.getRequestList(), "foo"); - - final List<Date> dates = jobAuditStatuses.stream().map(JobAuditStatus::getCreatedDate).collect(toList()); - final List<String> 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<Long> 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<Job> 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<Jobber> jobbers, int msoLimit, int expectedIndexSelected, Job.JobStatus topic, String assertionReason) { - JobsBrokerServiceInDatabaseImpl broker = new JobsBrokerServiceInDatabaseImpl(dataAccessService, sessionFactory, msoLimit, 20); - final List<JobDaoImpl> jobs = jobbers.stream().map(Jobber::toJob).collect(toList()); - for (JobDaoImpl job : jobs) { - Date modifiedDate = job.getModified(); - broker.add(job); - setModifiedDateToJob(job.getUuid(), modifiedDate); - } - Optional<Job> nextJob = broker.pull(topic, UUID.randomUUID().toString()); + JobsBrokerServiceInDatabaseImpl aBroker = new JobsBrokerServiceInDatabaseImpl(dataAccessService, sessionFactory, msoLimit, 20, versionService); + final List<JobDaoImpl> jobs = addJobsWithModifiedDate(jobbers, aBroker); + Optional<Job> 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<JobDaoImpl> addJobsWithModifiedDate(List<Jobber> jobbers, JobsBrokerService broker) { + final List<JobDaoImpl> jobs = jobbers.stream().map(Jobber::toJob).collect(toList()); + return addJobsWithModifiedDateByJobDao(jobs, broker); + } + + @NotNull + private List<JobDaoImpl> addJobsWithModifiedDateByJobDao(List<JobDaoImpl> 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<Jobber> 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<Pair<JobDaoImpl,Boolean>> 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<Pair<UUID, Job.JobStatus>> 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<Services> 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<Services> 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)); |