summaryrefslogtreecommitdiffstats
path: root/vid-app-common/src/test
diff options
context:
space:
mode:
authorIttay Stern <ittay.stern@att.com>2019-07-31 10:26:39 +0300
committerIttay Stern <ittay.stern@att.com>2019-07-31 13:31:33 +0300
commit0d37e2c3db490fac0b7b7e53612dbf9450bb2841 (patch)
tree97ad033436b51d2fb98a277086ab277e224912cc /vid-app-common/src/test
parent5efec2c3cfcead17394beb825200e132f827eb31 (diff)
Handle A&AI Service-Tree and add tests
Issue-ID: VID-378 Change-Id: Id1b86b77732768f9b497e2fcd29ee1665381ac57 Signed-off-by: Ittay Stern <ittay.stern@att.com>
Diffstat (limited to 'vid-app-common/src/test')
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/aai/util/TestWithAaiClient.java59
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/controller/LocalWebConfig.java17
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/AAIServiceIntegrativeTest.java226
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/AAIServiceTreeTest.java63
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/AaiServiceTest.java230
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBaseTest.java153
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/AuditServiceIntegrativeTest.java288
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/MsoRequestBuilderTest.java620
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/VidServiceImplTest.java31
-rw-r--r--vid-app-common/src/test/resources/payload_jsons/bulk_alacarte_service_deletion_request.json4
10 files changed, 1601 insertions, 90 deletions
diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/util/TestWithAaiClient.java b/vid-app-common/src/test/java/org/onap/vid/aai/util/TestWithAaiClient.java
new file mode 100644
index 000000000..98fca6796
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/aai/util/TestWithAaiClient.java
@@ -0,0 +1,59 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * VID
+ * ================================================================================
+ * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.vid.aai.util;
+
+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 java.net.URI;
+import javax.ws.rs.core.Response;
+import org.onap.vid.aai.ResponseWithRequestInfo;
+import org.springframework.http.HttpMethod;
+
+public class TestWithAaiClient {
+
+ protected ResponseWithRequestInfo mockedResponseWithRequestInfo(Response.Status status, String entity) {
+ return mockedResponseWithRequestInfo(status, entity, "/my/mocked/url", HttpMethod.GET);
+ }
+
+ protected ResponseWithRequestInfo mockedResponseWithRequestInfo(Response.Status status, String entity, String requestUrl, HttpMethod method) {
+ final Response mockResponse = mock(Response.class);
+ when(mockResponse.getStatus()).thenReturn(status.getStatusCode());
+ when(mockResponse.getStatusInfo()).thenReturn(status);
+ when(mockResponse.readEntity(String.class)).thenReturn(entity);
+ return new ResponseWithRequestInfo(mockResponse, requestUrl, method);
+ }
+
+ protected void mockForGetRequest(AAIRestInterface aaiRestInterface, ResponseWithRequestInfo responseWithRequestInfo) {
+ when(aaiRestInterface.doRest(anyString(), anyString(), any(URI.class), isNull(), eq(HttpMethod.GET), anyBoolean(), anyBoolean()))
+ .thenReturn(responseWithRequestInfo);
+ }
+
+ protected void mockForPutRequest(AAIRestInterface aaiRestInterface, ResponseWithRequestInfo responseWithRequestInfo) {
+ when(aaiRestInterface.doRest(anyString(), anyString(), any(URI.class), anyString(), eq(HttpMethod.PUT), anyBoolean(), anyBoolean()))
+ .thenReturn(responseWithRequestInfo);
+ }
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/LocalWebConfig.java b/vid-app-common/src/test/java/org/onap/vid/controller/LocalWebConfig.java
index 701f1c62a..aae1b0621 100644
--- a/vid-app-common/src/test/java/org/onap/vid/controller/LocalWebConfig.java
+++ b/vid-app-common/src/test/java/org/onap/vid/controller/LocalWebConfig.java
@@ -22,12 +22,21 @@
package org.onap.vid.controller;
import com.fasterxml.jackson.databind.ObjectMapper;
+import java.io.File;
+import java.util.concurrent.ExecutorService;
+import javax.servlet.ServletContext;
import org.onap.vid.aai.AaiClient;
import org.onap.vid.aai.AaiClientInterface;
import org.onap.vid.aai.AaiOverTLSClientInterface;
import org.onap.vid.aai.AaiResponseTranslator;
import org.onap.vid.aai.model.PortDetailsTranslator;
-import org.onap.vid.aai.util.*;
+import org.onap.vid.aai.util.AAIRestInterface;
+import org.onap.vid.aai.util.CacheProvider;
+import org.onap.vid.aai.util.HttpsAuthClient;
+import org.onap.vid.aai.util.NonCachingCacheProvider;
+import org.onap.vid.aai.util.SSLContextProvider;
+import org.onap.vid.aai.util.ServletRequestHelper;
+import org.onap.vid.aai.util.SystemPropertyHelper;
import org.onap.vid.asdc.AsdcClient;
import org.onap.vid.asdc.parser.ToscaParserImpl2;
import org.onap.vid.asdc.parser.VidNotionsBuilder;
@@ -42,10 +51,6 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.togglz.core.manager.FeatureManager;
-import javax.servlet.ServletContext;
-import java.io.File;
-import java.util.concurrent.ExecutorService;
-
@Configuration
public class LocalWebConfig {
@@ -68,7 +73,7 @@ public class LocalWebConfig {
@Bean
public AaiService getAaiService(AaiClientInterface aaiClient, AaiOverTLSClientInterface aaiOverTLSClient,
AaiResponseTranslator aaiResponseTranslator, AAITreeNodeBuilder aaiTreeNode, AAIServiceTree aaiServiceTree, ExecutorService executorService) {
- return new AaiServiceImpl(aaiClient, aaiOverTLSClient, aaiResponseTranslator, aaiTreeNode, aaiServiceTree, executorService);
+ return new AaiServiceImpl(aaiClient, aaiOverTLSClient, aaiResponseTranslator, aaiServiceTree, executorService);
}
@Bean
diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AAIServiceIntegrativeTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AAIServiceIntegrativeTest.java
new file mode 100644
index 000000000..d42747c20
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/services/AAIServiceIntegrativeTest.java
@@ -0,0 +1,226 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * VID
+ * ================================================================================
+ * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.vid.services;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.empty;
+import static org.hamcrest.Matchers.hasSize;
+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.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+import static org.testng.AssertJUnit.assertEquals;
+
+import com.google.common.util.concurrent.MoreExecutors;
+import java.net.URI;
+import java.util.List;
+import java.util.concurrent.ExecutorService;
+import javax.ws.rs.core.Response;
+import org.onap.vid.aai.AaiClient;
+import org.onap.vid.aai.ExceptionWithRequestInfo;
+import org.onap.vid.aai.ResponseWithRequestInfo;
+import org.onap.vid.aai.util.AAIRestInterface;
+import org.onap.vid.aai.util.AAITreeConverter;
+import org.onap.vid.aai.util.CacheProvider;
+import org.onap.vid.aai.util.TestWithAaiClient;
+import org.onap.vid.model.aaiTree.Network;
+import org.onap.vid.model.aaiTree.VpnBinding;
+import org.onap.vid.testUtils.TestUtils;
+import org.springframework.http.HttpMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+public class AAIServiceIntegrativeTest extends TestWithAaiClient {
+
+ private AAIRestInterface aaiRestInterface;
+ private AaiServiceImpl aaiServiceWithoutMocks;
+
+ private AaiServiceImpl createAaiServiceWithoutMocks(AAIRestInterface aaiRestInterface, CacheProvider cacheProvider) {
+ AaiClient aaiClient = new AaiClient(aaiRestInterface, null, cacheProvider);
+ ExecutorService executorService = MoreExecutors.newDirectExecutorService();
+ AAIServiceTree aaiServiceTree = new AAIServiceTree(
+ aaiClient,
+ new AAITreeNodeBuilder(aaiClient),
+ new AAITreeConverter(),
+ null,
+ null,
+ executorService
+ );
+ return new AaiServiceImpl(aaiClient, null, null, aaiServiceTree, executorService);
+ }
+
+ @BeforeMethod
+ public void setUp() {
+ aaiRestInterface = mock(AAIRestInterface.class);
+ CacheProvider cacheProvider = mock(CacheProvider.class);
+ CacheProvider.Cache cache = mock(CacheProvider.Cache.class);
+ when(cache.get(any())).thenReturn("ddd");
+ when(cacheProvider.aaiClientCacheFor(eq("getCloudOwnerByCloudRegionId"), any())).thenReturn(cache);
+ aaiServiceWithoutMocks = createAaiServiceWithoutMocks(aaiRestInterface, cacheProvider);
+ }
+
+ @Test
+ public void getVpnListTest_successResponse() {
+
+ final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK,
+ "{" +
+ " \"vpn-binding\": [" +
+ " {" +
+ " \"vpn-id\": \"7a7b327d9-287aa00-82c4b0-100001\"," +
+ " \"vpn-name\": \"GN_EVPN_direct_net_0_ST_Subnets_Pools_Ipv4\"," +
+ " \"resource-version\": \"1494001848224\"," +
+ " \"relationship-list\": {" +
+ " \"relationship\": [" +
+ " {" +
+ " \"related-to\": \"l3-network\"," +
+ " \"relationship-label\": \"org.onap.relationships.inventory.Uses\"," +
+ " \"related-link\": \"/aai/v15/network/l3-networks/l3-network/148b7892-c654-411d-9bb1-0d31fa6f9cc0\"," +
+ " \"relationship-data\": [" +
+ " {" +
+ " \"relationship-key\": \"l3-network.network-id\"," +
+ " \"relationship-value\": \"148b7892-c654-411d-9bb1-0d31fa6f9cc0\"" +
+ " }" +
+ " ]," +
+ " \"related-to-property\": [" +
+ " {" +
+ " \"property-key\": \"l3-network.network-name\"," +
+ " \"property-value\": \"GN_EVPN_direct_net_0_ST_Subnets_Pools_Ipv4\"" +
+ " }" +
+ " ]" +
+ " }" +
+ " ]" +
+ " }" +
+ " }" +
+ " ]}"
+ );
+
+ mockForGetRequest(aaiRestInterface, responseWithRequestInfo);
+
+ List<VpnBinding> vpnList = aaiServiceWithoutMocks.getVpnListByVpnType("aaa");
+ assertThat(vpnList, hasSize(1));
+ }
+
+ @Test
+ public void getVpnListTest_notFoundResponse() {
+
+ final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.NOT_FOUND,
+ "{" +
+ " \"requestError\": {" +
+ " \"serviceException\": {" +
+ " \"messageId\": \"SVC3001\"," +
+ " \"text\": \"Resource not found for %1 using id %2 (msg=%3) (ec=%4)\"," +
+ " \"variables\": [" +
+ " \"GET\"," +
+ " \"network/vpn-bindings\"," +
+ " \"Node Not Found:No Node of type vpn-binding found at: network/vpn-bindings\"," +
+ " \"ERR.5.4.6114\"" +
+ " ]" +
+ " }" +
+ " }" +
+ "}"
+ );
+
+ mockForGetRequest(aaiRestInterface, responseWithRequestInfo);
+
+ List<VpnBinding> vpnList = aaiServiceWithoutMocks.getVpnListByVpnType("aaa");
+ assertThat(vpnList, empty());
+ }
+
+ @Test(expectedExceptions = ExceptionWithRequestInfo.class, expectedExceptionsMessageRegExp = ".*errorCode.*500.*raw.*entity")
+ public void getVpnListTest_errorResponse() {
+
+ final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.INTERNAL_SERVER_ERROR,
+ "entity"
+ );
+
+ mockForGetRequest(aaiRestInterface, responseWithRequestInfo);
+
+ aaiServiceWithoutMocks.getVpnListByVpnType("aaa");
+ }
+
+ public void getNetworkListTest_successResponse() {
+ String rawResponse = TestUtils.readFileAsString("/responses/aai/l3-networks-by-cloud-region-and-tenantId.json");
+ final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.OK,
+ rawResponse,
+ "/my/mocked/url",
+ HttpMethod.PUT);
+ mockForPutRequest(aaiRestInterface, responseWithRequestInfo);
+ List<Network> networkList = aaiServiceWithoutMocks.getL3NetworksByCloudRegion("aaa", "bbb", "ccc");
+ assertThat(networkList, hasSize(4));
+ verify(aaiRestInterface).doRest(anyString(), anyString(), eq(URI.create("query?format=resource")),
+ eq("{\"start\":\"/cloud-infrastructure/cloud-regions/cloud-region/ddd/aaa\",\"query\":\"query/l3-networks-by-cloud-region?tenantId=bbb&networkRole=ccc\"}"), eq(HttpMethod.PUT), anyBoolean(), anyBoolean());
+ }
+
+ @DataProvider
+ public static Object[][] networkRoles() {
+ return new Object[][]{
+ {"", "{\"start\":\"/cloud-infrastructure/cloud-regions/cloud-region/ddd/aaa\",\"query\":\"query/l3-networks-by-cloud-region?tenantId=bbb\"}"},
+ {null, "{\"start\":\"/cloud-infrastructure/cloud-regions/cloud-region/ddd/aaa\",\"query\":\"query/l3-networks-by-cloud-region?tenantId=bbb\"}"},
+ {"ccc", "{\"start\":\"/cloud-infrastructure/cloud-regions/cloud-region/ddd/aaa\",\"query\":\"query/l3-networks-by-cloud-region?tenantId=bbb&networkRole=ccc\"}"}
+ };
+ }
+
+ @Test(dataProvider = "networkRoles")
+ public void testBuildPayloadForL3NetworksByCloudRegion(String networkRole, String expected) {
+ String payload = aaiServiceWithoutMocks.buildPayloadForL3NetworksByCloudRegion("aaa", "bbb", networkRole);
+ assertEquals(expected, payload);
+
+ }
+
+ @Test
+ public void getNetworkListTest_notFoundResponse() {
+
+ final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.NOT_FOUND,
+ "{" +
+ " \"requestError\": {" +
+ " \"serviceException\": {" +
+ " \"messageId\": \"SVC3001\"," +
+ " \"text\": \"Some text\"," +
+ " \"variables\": []" +
+ " }" +
+ " }" +
+ "}",
+ "/my/mocked/url",
+ HttpMethod.PUT);
+
+ mockForPutRequest(aaiRestInterface, responseWithRequestInfo);
+
+ List<Network> networkList = aaiServiceWithoutMocks.getL3NetworksByCloudRegion("aaa", "bbb", "ccc");
+ assertThat(networkList, empty());
+ }
+
+ @Test(expectedExceptions = ExceptionWithRequestInfo.class, expectedExceptionsMessageRegExp = ".*errorCode.*500.*raw.*entity")
+ public void getNetworkListTest_errorResponse() {
+
+ final ResponseWithRequestInfo responseWithRequestInfo = mockedResponseWithRequestInfo(Response.Status.INTERNAL_SERVER_ERROR,
+ "entity",
+ "/my/mocked/url",
+ HttpMethod.PUT);
+
+ mockForPutRequest(aaiRestInterface, responseWithRequestInfo);
+
+ aaiServiceWithoutMocks.getL3NetworksByCloudRegion("aaa", "bbb", "ccc");
+ }
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AAIServiceTreeTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AAIServiceTreeTest.java
index e8a9e5e83..ada1f857e 100644
--- a/vid-app-common/src/test/java/org/onap/vid/services/AAIServiceTreeTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/services/AAIServiceTreeTest.java
@@ -20,31 +20,46 @@
package org.onap.vid.services;
+import static java.util.Collections.emptyList;
+import static java.util.Collections.emptyMap;
+import static java.util.stream.Collectors.toList;
+import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.onap.vid.services.AAITreeNodeBuilderTest.createExpectedVnfTreeNode;
+
+import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Streams;
+import com.google.common.util.concurrent.MoreExecutors;
+import java.io.IOException;
+import java.util.List;
+import java.util.concurrent.ExecutorService;
+import net.javacrumbs.jsonunit.core.Option;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.jetbrains.annotations.NotNull;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import org.onap.vid.aai.AaiClient;
+import org.onap.vid.aai.util.AAITreeConverter;
import org.onap.vid.asdc.parser.ServiceModelInflator;
import org.onap.vid.asdc.parser.ServiceModelInflator.Names;
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.testUtils.TestUtils;
+import org.onap.vid.utils.Unchecked;
+import org.springframework.http.HttpMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
-import java.util.List;
-
-import static java.util.Collections.emptyList;
-import static java.util.Collections.emptyMap;
-import static java.util.stream.Collectors.toList;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.when;
-
public class AAIServiceTreeTest {
@Mock
@@ -177,4 +192,30 @@ public class AAIServiceTreeTest {
return newNode;
}
-}
+ @Test
+ public void whenBuildTreeForOneResource_resultAsExpected() throws IOException {
+
+ AaiClient aaiClientMock = mock(AaiClient.class);
+ ExecutorService executorService = MoreExecutors.newDirectExecutorService();
+ AAIServiceTree aaiServiceTree = new AAIServiceTree(
+ aaiClientMock,
+ new AAITreeNodeBuilder(aaiClientMock),
+ new AAITreeConverter(),
+ null,
+ null,
+ executorService
+ );
+
+ String url = "anyUrl/vnf";
+
+ JsonNode mockedAaiGetVnfResponse = TestUtils.readJsonResourceFileAsObject("/getTopology/vnf.json", JsonNode.class);
+ when(aaiClientMock.typedAaiRest(Unchecked.toURI(url), JsonNode.class, null, HttpMethod.GET, false)).thenReturn(mockedAaiGetVnfResponse);
+
+ CloudConfiguration expectedCloudConfiguration = new CloudConfiguration("dyh3b", "c8035f5ee95d4c62bbc8074c044122b9", "irma-aic");
+ AAITreeNode expectedVnfNode = createExpectedVnfTreeNode(expectedCloudConfiguration);
+
+ List<AAITreeNode> aaiTreeNodes = aaiServiceTree.buildAAITreeForUniqueResource(url, NodeType.GENERIC_VNF);
+ assertEquals(1, aaiTreeNodes.size());
+ assertThat(aaiTreeNodes.get(0), jsonEquals(expectedVnfNode).when(Option.IGNORING_EXTRA_FIELDS).whenIgnoringPaths("relationshipList", "children[0].relationshipList"));
+ }
+} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AaiServiceTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AaiServiceTest.java
new file mode 100644
index 000000000..92a55f0b8
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/services/AaiServiceTest.java
@@ -0,0 +1,230 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * VID
+ * ================================================================================
+ * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.vid.services;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.arrayWithSize;
+import static org.hamcrest.Matchers.containsInAnyOrder;
+import static org.hamcrest.Matchers.equalTo;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
+
+import com.google.common.collect.ImmutableMap;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+import org.onap.vid.aai.AaiClientInterface;
+import org.onap.vid.aai.AaiGetVnfResponse;
+import org.onap.vid.aai.AaiResponse;
+import org.onap.vid.aai.model.AaiGetPnfResponse;
+import org.onap.vid.aai.model.AaiGetPnfs.Pnf;
+import org.onap.vid.aai.model.AaiGetTenatns.GetTenantsResponse;
+import org.onap.vid.aai.model.LogicalLinkResponse;
+import org.onap.vid.aai.model.Relationship;
+import org.onap.vid.aai.model.RelationshipData;
+import org.onap.vid.aai.model.RelationshipList;
+import org.onap.vid.aai.model.ServiceRelationships;
+import org.onap.vid.aai.model.VnfResult;
+import org.onap.vid.model.aaiTree.AAITreeNode;
+import org.onap.vid.roles.Role;
+import org.onap.vid.roles.RoleValidator;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+public class AaiServiceTest {
+
+ @InjectMocks
+ private AaiServiceImpl aaiService;
+
+ @Mock
+ private AaiClientInterface aaiClientInterface;
+
+ @BeforeMethod
+ public void initMocks(){
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @Test
+ public void testGetSpecificPnf(){
+ Pnf pnf = new Pnf("11111", null, null, null, null, null, null);
+ AaiResponse<Pnf> aaiResponse = new AaiResponse<>(pnf, "aaaa", 200);
+ Mockito.doReturn(aaiResponse).when(aaiClientInterface).getSpecificPnf(Mockito.anyString());
+ AaiResponse<Pnf> specificPnf = aaiService.getSpecificPnf("1345667");
+ assertNotNull(specificPnf);
+ pnf = specificPnf.getT();
+ assertNotNull(pnf);
+ assertEquals("11111",pnf.getPnfId());
+ assertEquals("aaaa",specificPnf.getErrorMessage());
+ assertEquals(200,specificPnf.getHttpCode());
+ }
+
+ @Test
+ public void testPnfByRegion(){
+ AaiGetPnfResponse aaiGetPnfResponse = new AaiGetPnfResponse();
+ AaiResponse<AaiGetPnfResponse> aaiResponse = new AaiResponse<>(aaiGetPnfResponse, "", 200);
+ Mockito.doReturn(aaiResponse).when(aaiClientInterface).getPNFData(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
+ AaiResponse<AaiGetPnfResponse> aaiGetPnfResponseWrapper = aaiService.getPNFData("1345667", "1345667", "1345667", "1345667", "1345667", "1345667", "1345667");
+ assertNotNull(aaiGetPnfResponseWrapper);
+ aaiGetPnfResponse = aaiGetPnfResponseWrapper.getT();
+ assertNotNull(aaiGetPnfResponse);
+ }
+
+ @Test
+ public void testGetAssociatedPnfs(){
+ ServiceRelationships serviceRelationships = createServiceRelationships();
+ AaiResponse<ServiceRelationships> aaiResponse = new AaiResponse<>(serviceRelationships, null, 200);
+ Mockito.doReturn(aaiResponse).when(aaiClientInterface).getServiceInstance(Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
+
+ LogicalLinkResponse logicalLinkResponse = createLogicalLinkResponse();
+ AaiResponse<LogicalLinkResponse> aaiResponse1 = new AaiResponse<>(logicalLinkResponse, null, 200);
+ Mockito.doReturn(aaiResponse1).when(aaiClientInterface).getLogicalLink("SANITY6758cce9%3ALAG1992%7CSANITY6785cce9%3ALAG1961");
+
+ List<String> pnfList = aaiService.getServiceInstanceAssociatedPnfs("123", "456", "789");
+ assertNotNull(pnfList);
+ assertEquals(1, pnfList.size());
+ assertEquals("SANITY6785cce9", pnfList.get(0));
+ }
+
+ private ServiceRelationships createServiceRelationships() {
+ ServiceRelationships serviceRelationships = new ServiceRelationships();
+ serviceRelationships.setServiceInstanceName("test service");
+
+ RelationshipData logicalLinksRelationshipData = new RelationshipData();
+ logicalLinksRelationshipData.setRelationshipKey("logical-link.link-name");
+ logicalLinksRelationshipData.setRelationshipValue("SANITY6758cce9:LAG1992|SANITY6785cce9:LAG1961");
+
+ Relationship logicalLinksRelationship = new Relationship();
+ logicalLinksRelationship.setRelatedTo("logical-link");
+ logicalLinksRelationship.setRelationDataList(Arrays.asList(logicalLinksRelationshipData));
+
+ RelationshipList logicalLinksRelationshipsList = new RelationshipList();
+ logicalLinksRelationshipsList.setRelationship(Arrays.asList(logicalLinksRelationship));
+
+ serviceRelationships.setRelationshipList(logicalLinksRelationshipsList);
+ return serviceRelationships;
+ }
+
+ private LogicalLinkResponse createLogicalLinkResponse() {
+ LogicalLinkResponse logicalLinkResponse = new LogicalLinkResponse();
+ logicalLinkResponse.setLinkName("SANITY6758cce9:LAG1992|SANITY6785cce9:LAG1961");
+
+ RelationshipData lagInterfaceRelationshipData = new RelationshipData();
+ lagInterfaceRelationshipData.setRelationshipKey("pnf.pnf-name");
+ lagInterfaceRelationshipData.setRelationshipValue("SANITY6785cce9");
+
+ Relationship lagInterfaceRelationship = new Relationship();
+ lagInterfaceRelationship.setRelatedTo("lag-interface");
+ lagInterfaceRelationship.setRelationDataList(Arrays.asList(lagInterfaceRelationshipData));
+
+ RelationshipList lagInterfaceRelationshipsList = new RelationshipList();
+ lagInterfaceRelationshipsList.setRelationship(Arrays.asList(lagInterfaceRelationship));
+
+ logicalLinkResponse.setRelationshipList(lagInterfaceRelationshipsList);
+
+ return logicalLinkResponse;
+ }
+
+ @DataProvider
+ public static Object[][] getTenantsData() {
+ return new Object[][] {
+ {"customer1", "serviceType1", "tenant1", "customer1", "serviceType1", "tenant1", "id-1", true},
+ {"customer1", "serviceType1", "TeNant1", "customer1", "serviceType1", "tenant1", "id-1", true},
+ {"customer1", "serviceType1", "TENANT1", "customer1", "serviceType1", "tenant1", "id-1", true},
+ {"customer1", "serviceType1", "tenant2", "customer1", "serviceType1", "tenant1", "tenant2", false},
+ {"customer1", "serviceType1", null, "customer1", "serviceType1", "tenant1", "tenant2", true},
+ {"customer2", "serviceType1", "tenant1", "customer1", "serviceType1", "tenant1", "id-1", false},
+ {"customer1", "serviceType2", "tenant1", "customer1", "serviceType1", "tenant1", "id-1", false},
+ {"customer2", "serviceType1", null, "customer1", "serviceType1", "tenant1", "id-1", false},
+ {"customer1", "serviceType2", null, "customer1", "serviceType1", "tenant1", "id-1", false},
+ };
+ }
+
+ @Test(dataProvider = "getTenantsData")
+ public void testGetTenants(String userGlobalCustomerId, String userServiceType, String userTenantName, String serviceGlobalCustomerId,
+ String serviceServiceType, String serviceTenantName, String serviceTenantId, boolean expectedIsPermitted) {
+ GetTenantsResponse[] getTenantsResponses = new GetTenantsResponse[] {new GetTenantsResponse(null, null, serviceTenantName, serviceTenantId, false)};
+ AaiResponse<GetTenantsResponse[]> aaiResponse = new AaiResponse<>(getTenantsResponses, null, 200);
+ Mockito.doReturn(aaiResponse).when(aaiClientInterface).getTenants(serviceGlobalCustomerId, serviceServiceType);
+ Role role = new Role(null, userGlobalCustomerId, userServiceType, userTenantName);
+ RoleValidator roleValidator = RoleValidator.by(Collections.singletonList(role), false);
+ AaiResponse<GetTenantsResponse[]> actualTenants = aaiService.getTenants(serviceGlobalCustomerId, serviceServiceType, roleValidator);
+
+ assertThat(actualTenants.getT(), arrayWithSize(1));
+ assertThat(actualTenants.getT()[0].tenantName, equalTo(serviceTenantName));
+ assertThat(actualTenants.getT()[0].isPermitted, equalTo(expectedIsPermitted));
+ }
+
+ @DataProvider
+ public static Object[][] instanceGroupsRoleAndType() {
+ return new Object[][]{
+ {"group role & type are same as requested", ImmutableMap.of("SERVICE-ACCESS", "LOAD-GROUP"), false},
+ {"1 group properties is same as requested, 1 is not same", ImmutableMap.of("SERVICE-ACCESS", "LOAD-GROUP",
+ "dummy", "dummy"), false},
+ {"only group type is same as requested", ImmutableMap.of("dummy", "LOAD-GROUP"), true},
+ {"only group role is same as requested", ImmutableMap.of("SERVICE-ACCESS", "dummy"), true},
+ {"group role & type are not same as requested", ImmutableMap.of("dummy", "dummy"), true},
+ {"vnf is not related to instance group", ImmutableMap.of(), true},
+ };
+ }
+
+ @Test(dataProvider = "instanceGroupsRoleAndType")
+ public void testFilterInstanceGroupByRoleAndType(String description, Map<String, String> instanceGroupsProperties, boolean expectedMatch) {
+ List<AAITreeNode> instanceGroups = new ArrayList<>();
+
+ for (Map.Entry<String, String> props: instanceGroupsProperties.entrySet()) {
+ AAITreeNode instanceGroup = new AAITreeNode();
+ Map<String, Object> additionalProperties = ImmutableMap.of(
+ "instance-group-role", props.getKey(),
+ "instance-group-type", props.getValue());
+ instanceGroup.setAdditionalProperties(additionalProperties);
+ instanceGroups.add(instanceGroup);
+ }
+
+ boolean anyMatch = aaiService.isInstanceGroupsNotMatchRoleAndType(instanceGroups, "SERVICE-ACCESS", "LOAD-GROUP");
+ assertThat(anyMatch, equalTo(expectedMatch));
+ }
+
+ @Test
+ public void testFilterChangeManagementVNFCandidatesResponse() {
+ AaiGetVnfResponse aaiGetVnfResponse = new AaiGetVnfResponse();
+ aaiGetVnfResponse.results = new ArrayList<>();
+ Stream.of("genEric-vNf", "l3-interface-ipv6-address-list", "vserver", "pserver", "serviCe-inStance").forEach(
+ nodeType->{
+ VnfResult vnfResult = new VnfResult();
+ vnfResult.nodeType=nodeType;
+ aaiGetVnfResponse.results.add(vnfResult);
+ }
+ );
+
+ AaiResponse<AaiGetVnfResponse> result = aaiService.filterChangeManagementVNFCandidatesResponse(new AaiResponse<>(aaiGetVnfResponse, "", 200));
+ assertEquals(2, result.getT().results.size());
+ assertThat(result.getT().results.stream().map(x->x.nodeType).collect(Collectors.toList()), containsInAnyOrder("genEric-vNf","serviCe-inStance"));
+ }
+}
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 4cab99816..69458aa86 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
@@ -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,16 +20,38 @@
package org.onap.vid.services;
+import static java.util.Collections.emptyList;
+import static java.util.Collections.emptyMap;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.when;
+import static org.onap.vid.model.VidNotions.InstantiationType;
+import static org.onap.vid.model.VidNotions.InstantiationUI;
+import static org.onap.vid.model.VidNotions.ModelCategory;
+
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
+import java.time.ZonedDateTime;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import javax.inject.Inject;
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.model.serviceInstantiation.InstanceGroup;
+import org.onap.vid.model.serviceInstantiation.Network;
+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.RestObject;
import org.onap.vid.mso.model.ModelInfo;
import org.onap.vid.mso.rest.AsyncRequestStatus;
@@ -40,22 +62,10 @@ import org.springframework.http.HttpMethod;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
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.*;
-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}";
public static final String SUBSCRIBER_NAME = "{some subscriber name}";
@@ -97,15 +107,19 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests
return generateMockServiceInstantiationPayload(isPause, vnfs, networks, vnfGroups, bulkSize, isUserProvidedNaming, projectName, rollbackOnFailure, true, testApi, Action.Create, null);
}
- public ServiceInstantiation generateMockALaCarteServiceDeletionPayload(boolean isPause, Map<String, Vnf> vnfs, Map<String, Network> networks, Map<String, InstanceGroup> vnfGroups, int bulkSize, boolean isUserProvidedNaming, String projectName, boolean rollbackOnFailure, String testApi, String instanceId) {
+ public ServiceInstantiation generateMockAlaCarteServiceDeletionPayload(boolean isPause, Map<String, Vnf> vnfs, Map<String, Network> networks, Map<String, InstanceGroup> vnfGroups, int bulkSize, boolean isUserProvidedNaming, String projectName, boolean rollbackOnFailure, String testApi, String instanceId) {
return generateMockServiceInstantiationPayload(isPause, vnfs, networks, vnfGroups, bulkSize, isUserProvidedNaming, projectName, rollbackOnFailure, true, testApi, Action.Delete, instanceId);
}
+
+ public ServiceInstantiation generateMockServiceDeletionPayload(boolean isPause, Map<String, Vnf> vnfs, Map<String, Network> networks, Map<String, InstanceGroup> vnfGroups, int bulkSize, boolean isUserProvidedNaming, String projectName, boolean rollbackOnFailure, String testApi, String instanceId) {
+ return generateMockServiceInstantiationPayload(isPause, vnfs, networks, vnfGroups, bulkSize, isUserProvidedNaming, projectName, rollbackOnFailure, false, testApi, Action.Delete, instanceId);
+ }
private ServiceInstantiation generateMockServiceInstantiationPayload(boolean isPause, Map<String, Vnf> vnfs, Map<String, Network> networks, Map<String, InstanceGroup> vnfGroups, int bulkSize, boolean isUserProvidedNaming, String projectName, boolean rollbackOnFailure, boolean isAlacarte, String testApi, Action action, String instanceId) {
ModelInfo modelInfo = createModelInfo();
List<Map<String,String>> instanceParams = createInstanceParams();
- return new ServiceInstantiation ( modelInfo,
+ return new ServiceInstantiation( modelInfo,
AsyncInstantiationBusinessLogicTest.OWNING_ENTITY_ID,
AsyncInstantiationBusinessLogicTest.JULIO_ERICKSON,
projectName,
@@ -164,6 +178,15 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests
instanceParams, supplementaryParams, false, false, null, UUID.randomUUID().toString(), null, null);
}
+ protected ModelInfo createVfModuleModelInfo(String modelName, String modelVersion, String modelVersionId, String modelInvariantId, String modelCustomizationId, String modelCustomizationName) {
+ return createModelInfo("vfModule", modelName, modelVersion, modelVersionId, modelInvariantId, modelCustomizationId, modelCustomizationName);
+ }
+
+ protected VfModule createVfModuleForReplace(ModelInfo vfModuleModelInfo, String instanceName, String lcpCloudRegionId, String tenantId) {
+ return new VfModule( vfModuleModelInfo, instanceName, null, Action.Replace.name(), lcpCloudRegionId, null, tenantId,
+ null, null, true, null, null, UUID.randomUUID().toString(), null, null);
+ }
+
protected ModelInfo createVnfModelInfo(boolean isAlacarte) {
ModelInfo vnfModelInfo = new ModelInfo();
vnfModelInfo.setModelType("vnf");
@@ -179,6 +202,10 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests
return vnfModelInfo;
}
+ protected ModelInfo createVnfModelInfo(String modelName, String modelVersion, String modelVersionId, String modelInvariantId, String modelCustomizationId, String modelCustomizationName) {
+ return createModelInfo("vnf", modelName, modelVersion, modelVersionId, modelInvariantId, modelCustomizationId, modelCustomizationName);
+ }
+
private ModelInfo createNetworkModelInfo(boolean isAlacarte, String modelCustomizationId)
{
ModelInfo modelInfo = new ModelInfo();
@@ -205,6 +232,18 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests
return modelInfo;
}
+ private ModelInfo createModelInfo(String modelType, String modelName, String modelVersion, String modelVersionId, String modelInvariantId, String modelCustomizationId, String modelCustomizationName ) {
+ ModelInfo modelInfo = new ModelInfo();
+ modelInfo.setModelType(modelType);
+ modelInfo.setModelVersionId(modelVersionId);
+ modelInfo.setModelVersion(modelVersion);
+ modelInfo.setModelInvariantId(modelInvariantId);
+ modelInfo.setModelName(modelName);
+ modelInfo.setModelCustomizationId(modelCustomizationId);
+ modelInfo.setModelCustomizationName(modelCustomizationName);
+ return modelInfo;
+ }
+
protected Map<String, Vnf> createVnfList(HashMap<String, String> vfModuleInstanceParamsMap, List vnfInstanceParams, boolean isUserProvidedNaming) {
return createVnfList(vfModuleInstanceParamsMap, vnfInstanceParams, isUserProvidedNaming, false);
}
@@ -234,6 +273,37 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests
return vnfs;
}
+ protected void mockAaiClientAaiStatusOK() {
+ when(aaiClient.isNodeTypeExistsByName(eq(AsyncInstantiationBusinessLogicImpl.NAME_FOR_CHECK_AAI_STATUS), any())).thenReturn(false);
+ }
+
+ 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 void enableAddCloudOwnerOnMsoRequest() {
+ enableAddCloudOwnerOnMsoRequest(true);
+ }
+
+ 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;
+ }
+
public static class NetworkDetails {
public NetworkDetails(String name, String modelCustomizationId) {
@@ -245,13 +315,12 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests
public String modelCustomizationId;
}
-
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));
+ 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));
}
@@ -280,6 +349,10 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests
return siModelInfo;
}
+ protected ModelInfo createServiceModelInfo(String modelName, String modelVersion, String modelVersionId, String modelInvariantId, String modelCustomizationId, String modelCustomizationName) {
+ return createModelInfo("service", modelName, modelVersion, modelVersionId, modelInvariantId, modelCustomizationId, modelCustomizationName);
+ }
+
protected void createInstanceParamsMaps() {
instanceParamsMapWithoutParams = new HashMap<>();
instanceParamsMapWithoutParams.put("availability_zone_0" , "mtpocdv-kvm-az01");
@@ -322,7 +395,7 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests
}
protected ServiceInstantiation generateALaCarteWithVnfsServiceInstantiationPayload() {
- Map<String, Vnf> vnfs = createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, Collections.singletonList(vnfInstanceParamsMapWithParamsToRemove) , true);
+ Map<String, Vnf> vnfs = createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, Collections.singletonList(vnfInstanceParamsMapWithParamsToRemove) , true, true);
ServiceInstantiation serviceInstantiation = generateMockALaCarteServiceInstantiationPayload(false, vnfs, emptyMap(), emptyMap(), 1, true, PROJECT_NAME, false, "VNF_API");
return serviceInstantiation;
}
@@ -347,37 +420,7 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests
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/AuditServiceIntegrativeTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AuditServiceIntegrativeTest.java
new file mode 100644
index 000000000..d60d8112c
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/services/AuditServiceIntegrativeTest.java
@@ -0,0 +1,288 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * VID
+ * ================================================================================
+ * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.vid.services;
+
+import static java.util.stream.Collectors.toList;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.contains;
+import static org.hamcrest.Matchers.containsInAnyOrder;
+import static org.hamcrest.Matchers.hasProperty;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.notNullValue;
+import static org.hamcrest.Matchers.nullValue;
+import static org.hamcrest.core.Every.everyItem;
+import static org.onap.vid.job.Job.JobStatus.COMPLETED;
+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.utils.DaoUtils.getPropsMap;
+import static org.testng.Assert.assertTrue;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Streams;
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+import java.util.Date;
+import java.util.List;
+import java.util.Objects;
+import java.util.UUID;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+import javax.inject.Inject;
+import org.apache.commons.lang3.tuple.Pair;
+import org.hibernate.SessionFactory;
+import org.mockito.MockitoAnnotations;
+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.JobCommandsConfigWithMockedMso;
+import org.onap.vid.config.MockedAaiClientAndFeatureManagerConfig;
+import org.onap.vid.job.Job;
+import org.onap.vid.job.Job.JobStatus;
+import org.onap.vid.job.impl.JobDaoImpl;
+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.mso.rest.AsyncRequestStatusList;
+import org.onap.vid.testUtils.TestUtils;
+import org.onap.vid.utils.DaoUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+@ContextConfiguration(classes = {DataSourceConfig.class, SystemProperties.class, MockedAaiClientAndFeatureManagerConfig.class, JobCommandsConfigWithMockedMso.class})
+public class AuditServiceIntegrativeTest extends AbstractTestNGSpringContextTests {
+
+ @Inject
+ private DataAccessService dataAccessService;
+
+ @Inject
+ private AuditService auditService;
+
+ @Autowired
+ private SessionFactory sessionFactory;
+
+ @BeforeClass
+ void setup() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @AfterMethod
+ void clearDb() {
+ dataAccessService.deleteDomainObjects(JobDaoImpl.class, "1=1", getPropsMap());
+ dataAccessService.deleteDomainObjects(ServiceInfo.class, "1=1", getPropsMap());
+ dataAccessService.deleteDomainObjects(JobAuditStatus.class, "1=1", getPropsMap());
+ dataAccessService.deleteDomainObjects(NameCounter.class, "1=1", getPropsMap());
+ }
+
+
+ @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());
+
+ assertThat(dates, containsInAnyOrder(notNullValue(), notNullValue(), nullValue()));
+ assertThat(statuses, containsInAnyOrder("COMPLETE", "COMPLETE", "IN_PROGRESS"));
+ }
+
+
+ @DataProvider
+ public static Object[][] resourceTypeFilter() {
+
+ return new Object[][]{
+ {JobAuditStatus.ResourceTypeFilter.SERVICE, "serviceInstanceId"},
+ {JobAuditStatus.ResourceTypeFilter.VNF,"vnfInstanceId"},
+ {JobAuditStatus.ResourceTypeFilter.VFMODULE,"vfModuleInstanceId"},
+ {JobAuditStatus.ResourceTypeFilter.NETWORK,"networkInstanceId"},
+ {JobAuditStatus.ResourceTypeFilter.VNFGROUP,"instanceGroupId"},
+ };
+
+ }
+
+
+ //In case any of ResourceTypeFilter are accidentally changed or removed
+ @Test(dataProvider = "resourceTypeFilter")
+ public void testAllInstanceTypesForAuditInfoExist(JobAuditStatus.ResourceTypeFilter resourceTypeFilter, String value){
+ assertThat("ResourceTypeFilter value changed! Check the relevant usage vs MSO before changing it.", resourceTypeFilter.getFilterBy().equals(value));
+ }
+
+ private static final String MSO_ARBITRARY_STATUS = "completed mso status";
+
+ @DataProvider
+ public static Object[][] auditStatuses(Method test) {
+ return new Object[][]{
+ {
+ SourceStatus.VID,
+ new String[]{ PENDING.toString(), IN_PROGRESS.toString(), COMPLETED.toString()}
+ },
+ { SourceStatus.MSO,
+ new String[]{ IN_PROGRESS.toString(), MSO_ARBITRARY_STATUS }
+ }
+ };
+
+ }
+
+ @Test(dataProvider = "auditStatuses")
+ public void givenSomeAuditStatuses_getStatusesOfSpecificSourceAndJobId_getSortedResultsMatchingToParameters(
+ SourceStatus expectedSource, String [] expectedSortedStatuses){
+ UUID jobUuid = UUID.randomUUID();
+
+ final Date nowMinus3 = toDate(LocalDateTime.now().minusHours(3));
+ final Date nowMinus2 = toDate(LocalDateTime.now().minusHours(2));
+ final Date nowMinus30 = toDate(LocalDateTime.now().minusHours(30));
+
+ List<JobAuditStatus> auditStatusList = com.google.common.collect.ImmutableList.of(
+ JobAuditStatus.createForTest(jobUuid, PENDING.toString(), SourceStatus.VID, nowMinus3, 0),
+ JobAuditStatus.createForTest(jobUuid, IN_PROGRESS.toString(), SourceStatus.VID, nowMinus3, 1),
+ JobAuditStatus.createForTest(jobUuid, IN_PROGRESS.toString(), SourceStatus.MSO, UUID.randomUUID(),"", nowMinus30),
+ JobAuditStatus.createForTest(jobUuid, COMPLETED.toString(), SourceStatus.VID, nowMinus2, 2),
+ JobAuditStatus.createForTest(jobUuid, MSO_ARBITRARY_STATUS, SourceStatus.MSO, UUID.randomUUID(),"", nowMinus3),
+
+ JobAuditStatus.createForTest(UUID.randomUUID(), PENDING.toString(), SourceStatus.VID, nowMinus3, 0)
+ );
+ auditStatusList.forEach((auditStatus) -> createNewAuditStatus(auditStatus));
+
+ List<JobAuditStatus> statuses = auditService.getAuditStatuses(jobUuid, expectedSource);
+ List<String> statusesList = statuses.stream().map(status -> status.getJobStatus()).collect(toList());
+
+ 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 + " is not ok", statusesList, contains(expectedSortedStatuses));
+ }
+
+ private static Date toDate(LocalDateTime localDateTime) {
+ return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
+ }
+
+ private void createNewAuditStatus(JobAuditStatus auditStatus)
+ {
+ Date createdDate= auditStatus.getCreated();
+ dataAccessService.saveDomainObject(auditStatus, getPropsMap());
+ setDateToStatus(auditStatus.getSource(), auditStatus.getJobStatus(), createdDate);
+ }
+
+ 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
+ public void addSomeVidStatuses_getThem_verifyGetIsWithoutDuplicates(){
+ final Stream<JobStatus> statusesToPush = Stream.of(PENDING, IN_PROGRESS, IN_PROGRESS, PAUSE, PAUSE, IN_PROGRESS, COMPLETED);
+ final Stream<JobStatus> statusesToExpect = Stream.of(PENDING, IN_PROGRESS, PAUSE, IN_PROGRESS, COMPLETED);
+ final UUID jobUuid = UUID.randomUUID();
+
+ // Set up
+ statusesToPush.forEach(status-> auditService.auditVidStatus(jobUuid, status));
+
+ // Given
+ List<JobAuditStatus> auditStatusesFromDB = auditService.getAuditStatuses(jobUuid, SourceStatus.VID);
+ List<Pair<String, Integer>> statusesAndOrdinalsFromDB =
+ auditStatusesFromDB.stream()
+ .map(status -> Pair.of(status.getJobStatus(), status.getOrdinal()))
+ .collect(toList());
+
+ // Assert that
+ List<Pair<String, Integer>> expectedStatusesAndOrdinals =
+ Streams.zip(
+ statusesToExpect.map(Objects::toString),
+ IntStream.range(0, 100).boxed(), // max=100 will be truncated
+ Pair::of
+ ).collect(toList());
+
+ assertThat(statusesAndOrdinalsFromDB, is(expectedStatusesAndOrdinals));
+ }
+
+ @Test
+ public void addSameStatusOfVidAndMso_verifyThatBothWereAdded(){
+ UUID jobUuid = UUID.randomUUID();
+ Job.JobStatus sameStatus = IN_PROGRESS;
+ auditService.auditMsoStatus(jobUuid, sameStatus.toString(),null,null);
+ auditService.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[][] 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 -> {
+ auditService.auditMsoStatus(status.getJobId(), status.getJobStatus(), status.getRequestId() != null ? status.getRequestId().toString() : null, status.getAdditionalInfo());
+ });
+ List<String> statusesFromDB = auditService.getAuditStatuses(jobUuid, SourceStatus.MSO).stream().map(auditStatus -> auditStatus.getJobStatus()).collect(
+ toList());
+ assertThat( assertionReason, statusesFromDB, is(expectedStatuses));
+ }
+} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/services/MsoRequestBuilderTest.java b/vid-app-common/src/test/java/org/onap/vid/services/MsoRequestBuilderTest.java
new file mode 100644
index 000000000..311eb04cc
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/services/MsoRequestBuilderTest.java
@@ -0,0 +1,620 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * VID
+ * ================================================================================
+ * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.vid.services;
+
+import static com.google.common.collect.Maps.newHashMap;
+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.core.IsEqual.equalTo;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
+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.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.stream.Collectors;
+import javax.inject.Inject;
+import org.apache.commons.io.IOUtils;
+import org.hibernate.SessionFactory;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+import org.onap.portalsdk.core.service.DataAccessService;
+import org.onap.portalsdk.core.util.SystemProperties;
+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.dal.AsyncInstantiationRepository;
+import org.onap.vid.job.JobAdapter;
+import org.onap.vid.job.JobsBrokerService;
+import org.onap.vid.job.command.MsoRequestBuilder;
+import org.onap.vid.model.Action;
+import org.onap.vid.model.serviceInstantiation.InstanceGroup;
+import org.onap.vid.model.serviceInstantiation.Network;
+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.AddOrRemoveInstanceGroupMemberRequestDetails;
+import org.onap.vid.mso.model.InstanceGroupInstantiationRequestDetails;
+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.properties.Features;
+import org.onap.vid.testUtils.TestUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.testng.Assert;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+@ContextConfiguration(classes = {DataSourceConfig.class, SystemProperties.class, MockedAaiClientAndFeatureManagerConfig.class})
+public class MsoRequestBuilderTest extends AsyncInstantiationBaseTest {
+
+ @Inject
+ private DataAccessService dataAccessService;
+
+ @Mock
+ private JobAdapter jobAdapterMock;
+
+ @Mock
+ private JobsBrokerService jobsBrokerServiceMock;
+
+ private AsyncInstantiationRepository asyncInstantiationRepository;
+
+ private AuditService auditService;
+
+ @Autowired
+ private SessionFactory sessionFactory;
+
+ private AsyncInstantiationBusinessLogicImpl asyncInstantiationBL;
+
+ private MsoRequestBuilder msoRequestBuilder;
+
+
+ @BeforeClass
+ void initServicesInfoService() {
+ MockitoAnnotations.initMocks(this);
+ 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();
+ }
+
+ @Test(dataProvider = "pauseAndInstanceParams", enabled = false) //Test is irrelevant with unique names feature
+ public void createMacroServiceInstantiationMsoRequest(Boolean isPause, HashMap<String, String> vfModuleInstanceParamsMap, List vnfInstanceParams) throws Exception {
+ ServiceInstantiation serviceInstantiationPayload = generateMacroMockServiceInstantiationPayload(isPause, createVnfList(vfModuleInstanceParamsMap, vnfInstanceParams, true));
+ final URL resource = this.getClass().getResource("/payload_jsons/bulk_macro_service_request.json");
+ RequestDetailsWrapper<ServiceInstantiationRequestDetails> result =
+ msoRequestBuilder.generateMacroServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016");
+ String expected = IOUtils.toString(resource, "UTF-8");
+ MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
+ }
+
+ @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 {
+
+ 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 =
+ msoRequestBuilder.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 =
+ msoRequestBuilder.generateALaCarteServiceInstantiationRequest(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 =
+ msoRequestBuilder.generateALaCarteServiceInstantiationRequest(serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016");
+
+ String serviceExpected = IOUtils.toString(this.getClass().getResource("/payload_jsons/bulk_alacarte_service_request.json"), "UTF-8");
+ MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(serviceExpected, result);
+ }
+
+ @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 =
+ msoRequestBuilder.generateALaCarteServiceInstantiationRequest(serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016");
+ String expected = IOUtils.toString(resource, "UTF-8");
+ MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
+ }
+
+ @Test
+ public void generateALaCarteServiceDeletionRequest_verifyRequestIsAsExpected() throws IOException {
+ String expected = generateServiceDeletionRequest(true, "VNF_API");
+
+ ServiceInstantiation serviceDeletionPayload = generateALaCarteServiceDeletionPayload();
+ RequestDetailsWrapper<ServiceDeletionRequestDetails> result =
+ msoRequestBuilder.generateServiceDeletionRequest(serviceDeletionPayload, "az2016");
+
+ MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
+ }
+
+ private ServiceInstantiation generateALaCarteServiceDeletionPayload() {
+ return generateMockAlaCarteServiceDeletionPayload(false, Collections.EMPTY_MAP, Collections.EMPTY_MAP, Collections.EMPTY_MAP, 1, true, PROJECT_NAME, false, "VNF_API", "1234567890");
+ }
+
+ @Test
+ public void generateServiceDeletionRequest_verifyRequestIsAsExpected() throws IOException {
+ String expected = generateServiceDeletionRequest(false, null);
+
+ ServiceInstantiation serviceDeletionPayload = generateServiceDeletionPayload();
+ RequestDetailsWrapper<ServiceDeletionRequestDetails> result =
+ msoRequestBuilder.generateServiceDeletionRequest(serviceDeletionPayload, "az2016");
+
+ MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
+ }
+
+ private String generateServiceDeletionRequest(boolean isAlaCarte, String testApi) {
+ String expected = TestUtils.readFileAsString("/payload_jsons/bulk_alacarte_service_deletion_request.json");
+ expected = expected.replace("[TEST_API]", String.valueOf(testApi));
+ expected = expected.replace("[IS_ALACARTE]", Boolean.toString(isAlaCarte));
+ return expected;
+ }
+
+ private ServiceInstantiation generateServiceDeletionPayload() {
+ return generateMockServiceDeletionPayload(false, Collections.EMPTY_MAP, Collections.EMPTY_MAP, Collections.EMPTY_MAP, 1, true, PROJECT_NAME, false, "VNF_API", "1234567890");
+ }
+
+ @DataProvider
+ public static Object[][] createVnfParameters() {
+ return new Object[][]{
+ {true, true, "/payload_jsons/vnf/bulk_vnf_request.json"},
+ {false, true, "/payload_jsons/vnf/bulk_vnf_request_without_cloud_owner.json"},
+ {true, false, "/payload_jsons/vnf/bulk_vnf_request_without_instance_name.json"},
+ };
+ }
+
+ @Test(dataProvider = "createVnfParameters")
+ public void createVnfRequestDetails_detailsAreAsExpected(boolean isFlagAddCloudOwnerActive, boolean isUserProvidedNaming, String expectedFile) throws IOException {
+ final List<Vnf> vnfList = new ArrayList<>(createVnfList(new HashMap<>(), null, isUserProvidedNaming, true).values());
+ createVnfPayloadAndAssert(vnfList.get(0), isFlagAddCloudOwnerActive, expectedFile);
+ }
+
+ @DataProvider
+ public static Object[][] inputVnfEndExpectedResult() {
+ return new Object[][]{
+ {"/payload_jsons/vnf/vnf_without_lob_user_input.json", "/payload_jsons/vnf/vnf_without_lob_expected.json"},
+ };
+ }
+
+ @Test(dataProvider = "inputVnfEndExpectedResult")
+ public void createVnfRequestFromJson_andCompre(String userInputFile, String expectedFile) throws IOException {
+ Vnf vnf = TestUtils.readJsonResourceFileAsObject(userInputFile, Vnf.class);
+ createVnfPayloadAndAssert(vnf, true, expectedFile);
+ }
+
+ private void createVnfPayloadAndAssert(Vnf vnf, boolean isFlagAddCloudOwnerActive, String expectedFile) throws IOException {
+ ModelInfo siModelInfo = createServiceModelInfo();
+ String serviceInstanceId = "aa3514e3-5a33-55df-13ab-12abad84e7aa";
+ Mockito.reset(aaiClient);
+ mockAaiClientAaiStatusOK();
+ enableAddCloudOwnerOnMsoRequest(isFlagAddCloudOwnerActive);
+ final RequestDetailsWrapper<VnfInstantiationRequestDetails> result = msoRequestBuilder.generateVnfInstantiationRequest(vnf, siModelInfo, serviceInstanceId, "pa0916", "VNF_API");
+ String expected = IOUtils.toString(this.getClass().getResource(expectedFile), "UTF-8");
+ assertThat(result, jsonEquals(expected).when(IGNORING_ARRAY_ORDER));
+ }
+
+ @DataProvider
+ public static Object[][] testBuildVnfInstanceParamsDataProvider(Method test) {
+ return new Object[][]{
+ {
+ Collections.EMPTY_LIST,
+ ImmutableList.of(
+ ImmutableList.of(ImmutableMap.of("k1", "v1", "k2", "v2")),
+ ImmutableList.of(ImmutableMap.of("k3", "v3", "k2", "v2"))
+ ),
+ 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)
+ ),
+ ImmutableList.of(ImmutableMap.of("k1", "v1", "k2", "v2", "k3", "v3", "j1", "w1"))
+ },
+ {
+ Collections.EMPTY_LIST,
+ Arrays.asList(null, null),
+ 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)
+ ),
+ Collections.EMPTY_LIST //mso is expect to empty list and not list with empty map
+ }
+ };
+ }
+
+ @Test(dataProvider = "testBuildVnfInstanceParamsDataProvider")
+ public void testBuildVnfInstanceParams(List<Map<String, String>> currentVnfInstanceParams,
+ List<List<Map<String, String>>> vfModulesInstanceParams,
+ List<Map<String, String>> expectedResult) {
+ List<VfModuleMacro> vfModules =
+ vfModulesInstanceParams.stream().map(params -> new VfModuleMacro(new ModelInfo(), null, null, params)).collect(Collectors.toList());
+ List<Map<String, String>> actual = msoRequestBuilder.buildVnfInstanceParams(currentVnfInstanceParams, vfModules);
+ assertThat(actual, equalTo(expectedResult));
+ }
+
+ @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 = msoRequestBuilder.generateVfModuleInstantiationRequest(
+ vfModule, siModelInfo, serviceInstanceId,
+ vnfModelInfo, vnfInstanceId, volumeGroupInstanceId, "pa0916", "VNF_API");
+ 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 = msoRequestBuilder.aggregateAllInstanceParams(instanceParams, suppParams);
+ assertThat("Aggregated params are not as expected", aggParams, equalTo(expected));
+ }
+
+ @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 =
+ msoRequestBuilder.generateVolumeGroupInstantiationRequest(vfModule,
+ createServiceModelInfo(),
+ "ff3514e3-5a33-55df-13ab-12abad84e7ff",
+ vnfModelInfo,
+ "vnfInstanceId",
+ "az2016",
+ "VNF_API");
+ String expected = IOUtils.toString(resource, "UTF-8");
+ MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
+ }
+
+ @DataProvider
+ public static Object[][] expectedNetworkRequestDetailsParameters() {
+ return new Object[][]{
+ {VNF_NAME, "/payload_jsons/network_instantiation_request.json"},
+ {null, "/payload_jsons/network_instantiation_request_without_instance_name.json"}
+ };
+ }
+
+ @Test(dataProvider = "expectedNetworkRequestDetailsParameters")
+ public void createNetworkRequestDetails_detailsAreAsExpected(String networkName, String filePath) throws IOException {
+
+ List<NetworkDetails> networkDetails = Collections.singletonList(new NetworkDetails(networkName, "ab153b6e-c364-44c0-bef6-1f2982117f04"));
+ final List<Network> networksList = new ArrayList<>(createNetworkList(null, networkDetails, true).values());
+ ModelInfo siModelInfo = createServiceModelInfo();
+ String serviceInstanceId = "aa3514e3-5a33-55df-13ab-12abad84e7aa";
+
+ Mockito.reset(aaiClient);
+ mockAaiClientAaiStatusOK();
+ enableAddCloudOwnerOnMsoRequest();
+
+ String expected = IOUtils.toString(this.getClass().getResource(filePath), "UTF-8");
+ final RequestDetailsWrapper<NetworkInstantiationRequestDetails> result = msoRequestBuilder.generateNetworkInstantiationRequest(networksList.get(0), siModelInfo, serviceInstanceId, "pa0916", "VNF_API");
+ 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();
+
+ String expected = IOUtils.toString(this.getClass().getResource("/payload_jsons/instance_group_instantiation_request.json"), "UTF-8");
+ final RequestDetailsWrapper<InstanceGroupInstantiationRequestDetails> result = msoRequestBuilder.generateInstanceGroupInstantiationRequest(instanceGroup, siModelInfo, serviceInstanceId, "az2018", "VNF_API");
+ MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
+ }
+
+ @Test
+ public void generateAddOrRemoveInstanceGroupMemberRequest_verifyResultAsExpected() throws IOException {
+ String expected = " {" +
+ " \"requestDetails\": {" +
+ " \"requestInfo\": {" +
+ " \"source\": \"VID\"," +
+ " \"requestorId\": \"az2018\"" +
+ " }," +
+ " \"relatedInstanceList\": [" +
+ " {" +
+ " \"relatedInstance\": {" +
+ " \"instanceId\": \"aa3514e3-5a33-55df-13ab-12abad84e7aa\"," +
+ " \"modelInfo\": {" +
+ " \"modelType\": \"vnf\"" +
+ " }" +
+ " }" +
+ " }" +
+ " ]" +
+ " }" +
+ " }";
+ RequestDetailsWrapper<AddOrRemoveInstanceGroupMemberRequestDetails> result =
+ msoRequestBuilder.generateInstanceGroupMemberRequest("aa3514e3-5a33-55df-13ab-12abad84e7aa", "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 =
+ msoRequestBuilder.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 = msoRequestBuilder.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 generateDeleteVnfRequest_verifyResultAsExpected() throws IOException {
+ String expected =
+ "{ " +
+ "\"requestDetails\" : {\n" +
+ " \"modelInfo\" : {\n" +
+ " \"modelCustomizationName\" : \"2016-73_MOW-AVPN-vPE-BV-L 0\",\n" +
+ " \"modelCustomizationId\" : \"ab153b6e-c364-44c0-bef6-1f2982117f04\",\n" +
+ " \"modelInvariantId\" : \"11111111-f63c-463e-ba94-286933b895f9\",\n" +
+ " \"modelVersionId\" : \"7f40c192-f63c-463e-ba94-286933b895f8\",\n" +
+ " \"modelName\" : \"2016-73_MOW-AVPN-vPE-BV-L\",\n" +
+ " \"modelType\" : \"vnf\",\n" +
+ " \"modelVersion\" : \"10.0\"\n" +
+ " },\n" +
+ " \"cloudConfiguration\" : {\n" +
+ " \"lcpCloudRegionId\" : \"AAIAIC25\",\n" +
+ " \"tenantId\" : \"092eb9e8e4b7412e8787dd091bc58e86\",\n" +
+ " \"cloudOwner\" : \"irma-aic\"\n" +
+ " },\n" +
+ " \"requestInfo\" : {\n" +
+ " \"source\" : \"VID\",\n" +
+ " \"requestorId\" : \"az2018\"\n" +
+ " }\n" +
+ " }" +
+ "}";
+ Vnf vnfDetails = new Vnf(createVnfModelInfo(true), "productFamily", "instanceName", Action.Delete.name(), "platform", "AAIAIC25", null,
+ "092eb9e8e4b7412e8787dd091bc58e86", null, null, false, "VNF_INSTANCE_ID", null, UUID.randomUUID().toString(), null, null);
+ RequestDetailsWrapper<VnfInstantiationRequestDetails> result =
+ msoRequestBuilder.generateDeleteVnfRequest(vnfDetails, "az2018");
+ MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
+ }
+
+ @Test
+ public void generateDeleteVfModuleRequest_verifyResultAsExpected() throws IOException {
+ String expected =
+ "{ " +
+ "\"requestDetails\" : {" +
+ " \"modelInfo\" : {" +
+ " \"modelCustomizationName\" : \"201673MowAvpnVpeBvL..AVPN_base_vPE_BV..module-0\"," +
+ " \"modelCustomizationId\" : \"a25e8e8c-58b8-4eec-810c-97dcc1f5cb7f\"," +
+ " \"modelVersionId\" : \"4c75f813-fa91-45a4-89d0-790ff5f1ae79\"," +
+ " \"modelInvariantId\" : \"22222222-f63c-463e-ba94-286933b895f9\"," +
+ " \"modelName\" : \"201673MowAvpnVpeBvL..AVPN_base_vPE_BV..module-0\"," +
+ " \"modelType\" : \"vfModule\"," +
+ " \"modelVersion\" : \"10.0\"" +
+ " }," +
+ " \"cloudConfiguration\" : {" +
+ " \"lcpCloudRegionId\" : \"mdt1\"," +
+ " \"tenantId\" : \"88a6ca3ee0394ade9403f075db23167e\"," +
+ " \"cloudOwner\" : \"irma-aic\"" +
+ " }," +
+ " \"requestInfo\" : {" +
+ " \"source\" : \"VID\"," +
+ " \"requestorId\" : \"az2018\"" +
+ " }" +
+ " }" +
+ "}";
+ VfModule vfModuleDetails = createVfModule("201673MowAvpnVpeBvL..AVPN_base_vPE_BV..module-0", VF_MODULE_0_MODEL_VERSION_ID, VF_MODULE_0_MODEL_CUSTOMIZATION_NAME, null, new HashMap<>(), "vmxnjr001_AVPN_base_vPE_BV_base", null, true);
+ RequestDetailsWrapper<VfModuleInstantiationRequestDetails> result =
+ msoRequestBuilder.generateDeleteVfModuleRequest(vfModuleDetails, "az2018");
+ MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
+ }
+
+ @Test(dataProvider = "cloudConfigurationPermutations")
+ public void createPre1806TransportServiceInstantiationMsoRequest(String tenantId, String lcpCloudRegionId, String jsonFile) throws IOException {
+ ServiceInstantiation serviceInstantiationPayload = generatePre1806MacroTransportServiceInstantiationPayload(tenantId, lcpCloudRegionId);
+
+ final URL resource = this.getClass().getResource(jsonFile);
+ RequestDetailsWrapper<ServiceInstantiationRequestDetails> result =
+ msoRequestBuilder.generateMacroServicePre1806InstantiationRequest(serviceInstantiationPayload, "az2016");
+ String expected = IOUtils.toString(resource, "UTF-8");
+ MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
+ }
+
+ @DataProvider
+ public static Object[][] cloudConfigurationPermutations() {
+ return new Object[][]{
+ {"88a6ca3ee0394ade9403f075db23167e", "mdt1", "/payload_jsons/pre_1806_macro_service_instantiation_request.json"},
+ {"", "mdt1", "/payload_jsons/pre_1806_macro_without_cloudConfiguration.json"},
+ {"88a6ca3ee0394ade9403f075db23167e", "", "/payload_jsons/pre_1806_macro_without_cloudConfiguration.json"},
+ {null, null, "/payload_jsons/pre_1806_macro_without_cloudConfiguration.json"}
+ };
+ }
+
+ @Test
+ public void createPre1806MacroWithVrfEntry() throws IOException {
+ ServiceInstantiation serviceInstantiationPayload = TestUtils.readJsonResourceFileAsObject(
+ "/payload_jsons/vrfEntry/service_with_vrf_entry_fe_input.json",
+ ServiceInstantiation.class);
+
+ when(featureManager.isActive(Features.FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST)).thenReturn(true);
+ when(aaiClient.getCloudOwnerByCloudRegionId("lcpCloudRegionId")).thenReturn("irma-aic");
+
+ RequestDetailsWrapper<ServiceInstantiationRequestDetails> result =
+ msoRequestBuilder.generateMacroServicePre1806InstantiationRequest(serviceInstantiationPayload, "az2016");
+
+ final URL url = this.getClass().getResource("/payload_jsons/vrfEntry/service_with_vrf_instantiation_request.json");
+ String expected = IOUtils.toString(url, "UTF-8");
+
+ assertThat(result, jsonEquals(expected).when(IGNORING_ARRAY_ORDER));
+ }
+
+ @Test
+ public void generateReplaceVfModuleRequest_verifyResultAsExpected() throws IOException {
+ String expected = TestUtils.readFileAsString("/payload_jsons/vfmodule/replace_vfmodule.json");
+ when(featureManager.isActive(Features.FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST)).thenReturn(true);
+ when(aaiClient.getCloudOwnerByCloudRegionId("regionOne")).thenReturn("irma-aic");
+
+ ModelInfo vfModuleModelInfo = createVfModuleModelInfo("VfZrdm5bpxmc02092017Vf..CORNELIUS_base..module-0", "1", "eb5de6fb-9ecf-4009-b922-fae3a9ae7d46",
+ "f7a867f2-596b-4f4a-a128-421e825a6190", "074c64d0-7e13-4bcc-8bdb-ea922331102d",null );
+
+ VfModule vfModuleDetails = createVfModuleForReplace(vfModuleModelInfo, "replace_module", "regionOne", "0422ffb57ba042c0800a29dc85ca70f8");
+
+ ModelInfo serviceModelInfo = createServiceModelInfo("Vf zolson5bpxmc02092017-Service", "1", "bad955c3-29b2-4a27-932e-28e942cc6480", "b16a9398-ffa3-4041-b78c-2956b8ad9c7b", null, null );
+
+ ModelInfo vnfModelInfo = createVnfModelInfo("Vf zolson5bpxmc02092017-VF", "1", "d326f424-2312-4dd6-b7fe-364fadbd1ef5", "23122c9b-dd7f-483f-bf0a-e069303db2f7", "96c23a4a-6887-4b2c-9cce-1e4ea35eaade", "Vf zolson5bpxmc02092017-VF 0" );
+
+ RequestDetailsWrapper<VfModuleInstantiationRequestDetails> result =
+ msoRequestBuilder.generateVfModuleInstantiationRequest(vfModuleDetails, serviceModelInfo, "e9993045-cc96-4f3f-bf9a-71b2a400a956", vnfModelInfo, "5c9c2896-1fe6-4055-b7ec-d0a01e5f9bf5", null,"az2016", "GR_API");
+
+ MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
+ }
+} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/services/VidServiceImplTest.java b/vid-app-common/src/test/java/org/onap/vid/services/VidServiceImplTest.java
index 4f7faab99..ff6b7f0b1 100644
--- a/vid-app-common/src/test/java/org/onap/vid/services/VidServiceImplTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/services/VidServiceImplTest.java
@@ -20,8 +20,23 @@
package org.onap.vid.services;
+import static java.util.stream.Collectors.toMap;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.Matchers.not;
+import static org.hamcrest.Matchers.nullValue;
+import static org.hamcrest.core.IsSame.sameInstance;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.any;
+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 com.google.common.collect.ImmutableMap;
import io.joshworks.restclient.http.HttpResponse;
+import java.util.Map;
+import java.util.UUID;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.mockito.Answers;
import org.mockito.Mock;
@@ -39,22 +54,6 @@ import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.togglz.core.manager.FeatureManager;
-import java.util.Map;
-import java.util.UUID;
-
-import static java.util.stream.Collectors.toMap;
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.Matchers.not;
-import static org.hamcrest.Matchers.nullValue;
-import static org.hamcrest.core.IsSame.sameInstance;
-import static org.junit.Assert.assertThat;
-import static org.mockito.Mockito.any;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
public class VidServiceImplTest {
@Mock(answer = Answers.RETURNS_MOCKS)
diff --git a/vid-app-common/src/test/resources/payload_jsons/bulk_alacarte_service_deletion_request.json b/vid-app-common/src/test/resources/payload_jsons/bulk_alacarte_service_deletion_request.json
index 55a57e195..c8d095949 100644
--- a/vid-app-common/src/test/resources/payload_jsons/bulk_alacarte_service_deletion_request.json
+++ b/vid-app-common/src/test/resources/payload_jsons/bulk_alacarte_service_deletion_request.json
@@ -12,8 +12,8 @@
"requestorId": "az2016"
},
"requestParameters": {
- "testApi": "VNF_API",
- "aLaCarte": true
+ "testApi": [TEST_API],
+ "aLaCarte": [IS_ALACARTE]
}
}
} \ No newline at end of file