aboutsummaryrefslogtreecommitdiffstats
path: root/vid-app-common/src/test/java
diff options
context:
space:
mode:
Diffstat (limited to 'vid-app-common/src/test/java')
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/aai/SubscriberFilteredResultsTest.java6
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/bl/AaiServiceTest.java177
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/config/JobCommandsConfigWithMockedMso.java36
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java14
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/controller/LoggerControllerTest.java8
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/controller/ServicePermissionsTest.java3
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/controller/VidControllerTest.java62
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/job/command/ResourceCommandTest.java14
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/job/command/VnfCommandTest.kt90
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/job/impl/AsyncInstantiationIntegrationTest.java59
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/model/ServiceInstanceSearchResultTest.java188
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/model/serviceInstantiation/InstantiationModelSerializationTest.java23
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/model/serviceInstantiation/VfModuleTest.java62
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/mso/MsoUtilTest.java23
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/mso/model/RequestParametersVfModuleTest.java49
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/properties/FeatureSetsManagerTest.kt101
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/roles/AlwaysValidRoleValidatorTest.java3
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/roles/RoleProviderTest.java41
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/roles/RoleValidatorByOwningEntityTest.java90
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/roles/RoleValidatorByRolesTest.java114
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/roles/RoleValidatorBySubscriberAndServiceTypeTest.java111
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/roles/RoleValidatorFactoryTest.java77
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/roles/RoleValidatorsComposerTest.java110
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/AAITreeNodeBuilderTest.java19
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/AaiServiceImplTest.java2
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/AaiServiceTest.java153
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBaseTest.java35
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBusinessLogicTest.java44
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/InstantiationTemplatesServiceTest.java68
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/MsoRequestBuilderTest.java118
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/services/UserParamsContainerTest.kt57
-rw-r--r--vid-app-common/src/test/java/org/onap/vid/testUtils/TestUtils.java38
32 files changed, 1359 insertions, 636 deletions
diff --git a/vid-app-common/src/test/java/org/onap/vid/aai/SubscriberFilteredResultsTest.java b/vid-app-common/src/test/java/org/onap/vid/aai/SubscriberFilteredResultsTest.java
index f9668c960..06ef5d586 100644
--- a/vid-app-common/src/test/java/org/onap/vid/aai/SubscriberFilteredResultsTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/aai/SubscriberFilteredResultsTest.java
@@ -33,8 +33,10 @@ import org.onap.vid.model.SubscriberList;
import org.onap.vid.roles.EcompRole;
import org.onap.vid.roles.Role;
import org.onap.vid.roles.RoleValidator;
+import org.onap.vid.roles.RoleValidatorFactory;
import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.mock;
public class SubscriberFilteredResultsTest {
@@ -89,9 +91,7 @@ public class SubscriberFilteredResultsTest {
}
private void prepareRoleValidator() {
- ArrayList<Role> list = new ArrayList<>();
- list.add(new Role(EcompRole.READ, "a", "a", "a"));
- roleValidator = RoleValidator.by(list);
+ roleValidator = mock(RoleValidator.class);
}
private void prepareSubscriberList() throws IOException {
diff --git a/vid-app-common/src/test/java/org/onap/vid/bl/AaiServiceTest.java b/vid-app-common/src/test/java/org/onap/vid/bl/AaiServiceTest.java
deleted file mode 100644
index 1d4556535..000000000
--- a/vid-app-common/src/test/java/org/onap/vid/bl/AaiServiceTest.java
+++ /dev/null
@@ -1,177 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * VID
- * ================================================================================
- * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.vid.bl;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.arrayWithSize;
-import static org.hamcrest.Matchers.equalTo;
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.assertNotNull;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-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.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.roles.Role;
-import org.onap.vid.roles.RoleValidator;
-import org.onap.vid.services.AaiServiceImpl;
-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 = Pnf.builder().withPnfId("11111").build();
- 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, expectedIsPermitted)};
- 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));
- 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));
- }
-}
diff --git a/vid-app-common/src/test/java/org/onap/vid/config/JobCommandsConfigWithMockedMso.java b/vid-app-common/src/test/java/org/onap/vid/config/JobCommandsConfigWithMockedMso.java
index c4f788689..3f2bf7318 100644
--- a/vid-app-common/src/test/java/org/onap/vid/config/JobCommandsConfigWithMockedMso.java
+++ b/vid-app-common/src/test/java/org/onap/vid/config/JobCommandsConfigWithMockedMso.java
@@ -31,12 +31,32 @@ import org.onap.vid.aai.util.SystemPropertyHelper;
import org.onap.vid.dal.AsyncInstantiationRepository;
import org.onap.vid.job.JobAdapter;
import org.onap.vid.job.JobsBrokerService;
-import org.onap.vid.job.command.*;
+import org.onap.vid.job.command.ALaCarteServiceCommand;
+import org.onap.vid.job.command.CommandUtils;
+import org.onap.vid.job.command.InProgressStatusService;
+import org.onap.vid.job.command.InstanceGroupCommand;
+import org.onap.vid.job.command.InstanceGroupMemberCommand;
+import org.onap.vid.job.command.JobCommandFactory;
+import org.onap.vid.job.command.MacroServiceCommand;
+import org.onap.vid.job.command.MsoRequestBuilder;
+import org.onap.vid.job.command.MsoResultHandlerService;
+import org.onap.vid.job.command.NetworkCommand;
+import org.onap.vid.job.command.VfmoduleCommand;
+import org.onap.vid.job.command.VnfCommand;
+import org.onap.vid.job.command.VolumeGroupCommand;
+import org.onap.vid.job.command.WatchChildrenJobsBL;
import org.onap.vid.job.impl.JobAdapterImpl;
import org.onap.vid.job.impl.JobWorker;
import org.onap.vid.job.impl.JobsBrokerServiceInDatabaseImpl;
+import org.onap.vid.model.ModelUtil;
import org.onap.vid.mso.RestMsoImplementation;
-import org.onap.vid.services.*;
+import org.onap.vid.services.AsyncInstantiationBusinessLogic;
+import org.onap.vid.services.AsyncInstantiationBusinessLogicImpl;
+import org.onap.vid.services.AuditService;
+import org.onap.vid.services.AuditServiceImpl;
+import org.onap.vid.services.CloudOwnerService;
+import org.onap.vid.services.InstantiationTemplatesService;
+import org.onap.vid.services.VersionService;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
@@ -130,6 +150,18 @@ public class JobCommandsConfigWithMockedMso {
return new AsyncInstantiationBusinessLogicImpl(jobAdapter, jobsBrokerService, sessionFactory, aaiClient, featureManager, cloudOwnerService, asyncInstantiationRepository, auditService);
}
+ @Bean
+ public ModelUtil modelUtil() {return new ModelUtil();}
+
+ @Bean
+ public InstantiationTemplatesService instantiationTemplatesService(
+ ModelUtil modelUtil,
+ AsyncInstantiationRepository asyncInstantiationRepository,
+ FeatureManager featureManager
+ ) {
+ return new InstantiationTemplatesService(modelUtil, asyncInstantiationRepository, featureManager);
+ };
+
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java
index 521102383..202263c41 100644
--- a/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/controller/AaiControllerTest.java
@@ -23,11 +23,13 @@ package org.onap.vid.controller;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
+import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
@@ -68,8 +70,11 @@ import org.onap.vid.aai.model.PortDetailsTranslator.PortDetailsOk;
import org.onap.vid.aai.util.AAIRestInterface;
import org.onap.vid.model.VersionByInvariantIdsRequest;
import org.onap.vid.properties.Features;
+import org.onap.vid.roles.AlwaysValidRoleValidator;
import org.onap.vid.roles.RoleProvider;
-import org.onap.vid.roles.RoleValidatorByRoles;
+import org.onap.vid.roles.RoleValidator;
+import org.onap.vid.roles.RoleValidatorBySubscriberAndServiceType;
+import org.onap.vid.roles.RoleValidatorFactory;
import org.onap.vid.services.AaiService;
import org.onap.vid.utils.SystemPropertiesWrapper;
import org.onap.vid.utils.Unchecked;
@@ -92,6 +97,8 @@ public class AaiControllerTest {
@Mock
private RoleProvider roleProvider;
@Mock
+ private RoleValidator roleValidator;
+ @Mock
private SystemPropertiesWrapper systemPropertiesWrapper;
@Mock
private FeatureManager featureManager;
@@ -103,6 +110,7 @@ public class AaiControllerTest {
public void setUp() {
aaiController = new AaiController(aaiService, aaiRestInterface, roleProvider, systemPropertiesWrapper,
featureManager);
+ when(roleProvider.getUserRolesValidator(any())).thenReturn(roleValidator);
mockMvc = MockMvcBuilders.standaloneSetup(aaiController).build();
}
@@ -408,7 +416,7 @@ public class AaiControllerTest {
String okResponseBody = "OK_RESPONSE";
AaiResponse<String> aaiResponse = new AaiResponse<>(okResponseBody, "", HttpStatus.OK.value());
given(featureManager.isActive(Features.FLAG_1906_AAI_SUB_DETAILS_REDUCE_DEPTH)).willReturn(isFeatureActive);
- given(aaiService.getSubscriberData(eq(subscriberId), isA(RoleValidatorByRoles.class),
+ given(aaiService.getSubscriberData(eq(subscriberId), isA(RoleValidator.class),
eq(isFeatureActive && omitServiceInstances)))
.willReturn(aaiResponse);
@@ -479,7 +487,7 @@ public class AaiControllerTest {
String okResponseBody = "OK_RESPONSE";
AaiResponse<String> aaiResponse = new AaiResponse<>(okResponseBody, "", HttpStatus.OK.value());
given(featureManager.isActive(Features.FLAG_1906_AAI_SUB_DETAILS_REDUCE_DEPTH)).willReturn(isFeatureActive);
- given(aaiService.getSubscriberData(eq(subscriberId), isA(RoleValidatorByRoles.class),
+ given(aaiService.getSubscriberData(eq(subscriberId), isA(RoleValidator.class),
eq(isFeatureActive && omitServiceInstances)))
.willReturn(aaiResponse);
diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/LoggerControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/LoggerControllerTest.java
index f0d840929..6f584ed3d 100644
--- a/vid-app-common/src/test/java/org/onap/vid/controller/LoggerControllerTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/controller/LoggerControllerTest.java
@@ -66,7 +66,7 @@ public class LoggerControllerTest {
@Test
public void shouldThrowNotAuthorizedException_whenUserIsNotAuthorizedToGetLogs() throws Exception {
- List<Role> list = ImmutableList.of(new Role(EcompRole.READ, "subName1", "servType1", "tenant1"));
+ List<Role> list = ImmutableList.of(new Role(EcompRole.READ, "subName1", "servType1", "tenant1", "owningEntityId"));
given(provider.getUserRoles(argThat(req -> req.getRequestedSessionId().equals("id1")))).willReturn(list);
given(provider.userPermissionIsReadLogs(list)).willReturn(false);
@@ -80,7 +80,7 @@ public class LoggerControllerTest {
@Test
public void shouldReturnLastAndOneBeforeLogLines_whenLimitIs2() throws Exception {
- List<Role> list = ImmutableList.of(new Role(EcompRole.READ, "subName1", "servType1", "tenant1"));
+ List<Role> list = ImmutableList.of(new Role(EcompRole.READ, "subName1", "servType1", "tenant1", "owningEntityId"));
given(provider.getUserRoles(argThat(req -> req.getRequestedSessionId().equals("id1")))).willReturn(list);
given(provider.userPermissionIsReadLogs(list)).willReturn(true);
@@ -96,7 +96,7 @@ public class LoggerControllerTest {
@Test
public void shouldReturnEmptyString_whenLogFileIsEmpty() throws Exception {
- List<Role> list = ImmutableList.of(new Role(EcompRole.READ, "subName1", "servType1", "tenant1"));
+ List<Role> list = ImmutableList.of(new Role(EcompRole.READ, "subName1", "servType1", "tenant1", "owningEntityId"));
given(provider.getUserRoles(argThat(req -> req.getRequestedSessionId().equals("id1")))).willReturn(list);
given(provider.userPermissionIsReadLogs(list)).willReturn(true);
@@ -111,7 +111,7 @@ public class LoggerControllerTest {
@Test
public void shouldReturnEmptyString_whenDebugLogFileIsEmpty() throws Exception {
- List<Role> list = ImmutableList.of(new Role(EcompRole.READ, "subName1", "servType1", "tenant1"));
+ List<Role> list = ImmutableList.of(new Role(EcompRole.READ, "subName1", "servType1", "tenant1", "owningEntityId"));
given(provider.getUserRoles(argThat(req -> req.getRequestedSessionId().equals("id1")))).willReturn(list);
given(provider.userPermissionIsReadLogs(list)).willReturn(true);
diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/ServicePermissionsTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/ServicePermissionsTest.java
index ac3da50ab..3b7dbfbb8 100644
--- a/vid-app-common/src/test/java/org/onap/vid/controller/ServicePermissionsTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/controller/ServicePermissionsTest.java
@@ -31,6 +31,7 @@ import static org.mockito.Mockito.when;
import org.jetbrains.annotations.NotNull;
import org.onap.vid.aai.model.Permissions;
+import org.onap.vid.roles.PermissionPropertiesSubscriberAndServiceType;
import org.onap.vid.roles.RoleProvider;
import org.onap.vid.roles.RoleValidator;
import org.springframework.mock.web.MockHttpServletRequest;
@@ -53,7 +54,7 @@ public class ServicePermissionsTest {
RoleProvider roleProvider = mock(RoleProvider.class);
RoleValidator roleValidator = mock(RoleValidator.class);
when(roleProvider.getUserRolesValidator(any())).thenReturn(roleValidator);
- when(roleValidator.isServicePermitted(subscriberId, serviceType)).thenReturn(expected);
+ when(roleValidator.isServicePermitted(new PermissionPropertiesSubscriberAndServiceType(subscriberId, serviceType))).thenReturn(expected);
AaiController2 aaiController2 = new AaiController2(null, roleProvider, null, null);
diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/VidControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/VidControllerTest.java
index 484f4a034..da91edb5f 100644
--- a/vid-app-common/src/test/java/org/onap/vid/controller/VidControllerTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/controller/VidControllerTest.java
@@ -21,9 +21,27 @@
package org.onap.vid.controller;
+import static java.util.stream.Collectors.toMap;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.CoreMatchers.nullValue;
+import static org.hamcrest.Matchers.not;
+import static org.mockito.BDDMockito.given;
+import static org.mockito.BDDMockito.then;
+import static org.mockito.Mockito.times;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.stream.IntStream;
+import javax.ws.rs.core.MediaType;
import org.apache.log4j.BasicConfigurator;
import org.junit.Assert;
import org.junit.Before;
@@ -35,35 +53,24 @@ import org.mockito.junit.MockitoJUnitRunner;
import org.onap.vid.asdc.AsdcCatalogException;
import org.onap.vid.asdc.beans.SecureServices;
import org.onap.vid.asdc.beans.Service;
-import org.onap.vid.model.*;
+import org.onap.vid.model.CR;
+import org.onap.vid.model.Network;
+import org.onap.vid.model.Node;
import org.onap.vid.model.PombaInstance.PombaRequest;
import org.onap.vid.model.PombaInstance.ServiceInstance;
+import org.onap.vid.model.ServiceModel;
+import org.onap.vid.model.ServiceProxy;
+import org.onap.vid.model.VNF;
+import org.onap.vid.model.VfModule;
+import org.onap.vid.model.VolumeGroup;
import org.onap.vid.roles.RoleProvider;
import org.onap.vid.services.AaiService;
+import org.onap.vid.services.InstantiationTemplatesService;
import org.onap.vid.services.PombaService;
import org.onap.vid.services.VidService;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
-import javax.ws.rs.core.MediaType;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-import java.util.stream.IntStream;
-
-import static java.util.stream.Collectors.toMap;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.hamcrest.Matchers.not;
-import static org.mockito.BDDMockito.given;
-import static org.mockito.BDDMockito.then;
-import static org.mockito.Mockito.times;
-import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
-import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
-import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
-import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
-
@RunWith(MockitoJUnitRunner.class)
public class VidControllerTest {
@@ -79,6 +86,8 @@ public class VidControllerTest {
private RoleProvider roleProvider;
@Mock
private PombaService pombaService;
+ @Mock
+ private InstantiationTemplatesService instantiationTemplatesService;
private VidController vidController;
private MockMvc mockMvc;
@@ -90,7 +99,7 @@ public class VidControllerTest {
@Before
public void setUp() {
- vidController = new VidController(vidService, aaiService, roleProvider, pombaService);
+ vidController = new VidController(vidService, aaiService, roleProvider, pombaService, instantiationTemplatesService);
BasicConfigurator.configure();
mockMvc = MockMvcBuilders.standaloneSetup(vidController).build();
objectMapper = new ObjectMapper();
@@ -102,12 +111,17 @@ public class VidControllerTest {
@Test
public void getServices_shouldReturnService_whenServiceExists() throws Exception {
- List<Service> services = ImmutableList.of(createService(uuid1, 1), createService(uuid2, 2), createService(uuid3, 3));
+ List<Service> services1 = ImmutableList.of(createService(uuid1, 1), createService(uuid2, 2), createService(uuid3, 3));
+ List<Service> services2 = ImmutableList.of(createService(uuid1, 4), createService(uuid2, 5), createService(uuid3, 6));
+
+ given(aaiService.getServicesByDistributionStatus())
+ .willReturn(services1);
- given(aaiService.getServicesByDistributionStatus()).willReturn(services);
+ given(instantiationTemplatesService.setOnEachServiceIsTemplateExists(services1))
+ .willReturn(services2);
SecureServices secureServices = new SecureServices();
- secureServices.setServices(services);
+ secureServices.setServices(services2);
secureServices.setReadOnly(false);
mockMvc.perform(get(REST_MODELS_SERVICES)
diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceCommandTest.java b/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceCommandTest.java
index db856d757..b916347d2 100644
--- a/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceCommandTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/job/command/ResourceCommandTest.java
@@ -279,7 +279,7 @@ public class ResourceCommandTest {
convertToMap(networks),
convertToMap(vnfGroups),
null,
- null, false, 1, false,false,null, null, null, null, null, null, null);
+ null, false, 1, false,false,null, null, null, null, null, null, null, null);
}
public static ServiceInstantiation createServiceWith2InstancesInEachLevel(Action action) {
@@ -298,11 +298,11 @@ public class ResourceCommandTest {
static InstanceGroup createGroup(List<InstanceGroupMember> groupMembers, Action action) {
return new InstanceGroup(mock(ModelInfo.class), null, action.name(), false, null, convertToMap(groupMembers), null, null, null,
- null);
+ null, null);
}
static InstanceGroupMember createMember(Action action) {
- return new InstanceGroupMember(null, action.toString(), null, null, null, null);
+ return new InstanceGroupMember(null, action.toString(), null, null, null, null, null);
}
static Vnf createVnf(List<VfModule> vfModules, Action action) {
@@ -310,22 +310,22 @@ public class ResourceCommandTest {
vfModulesMap.put("abc",convertToMap(vfModules));
return new Vnf(mock(ModelInfo.class), null, null, action.toString(), null, null, null, null, null, null, false, null, vfModulesMap, null, null, null,
- null);
+ null, null);
}
static Vnf createVnf(Action action) {
return new Vnf(mock(ModelInfo.class), null, null, action.toString(), null, null, null, null, null, null, false, null,null, null, null, null,
- null);
+ null, null);
}
static VfModule createVfModule(Action action) {
return new VfModule(mock(ModelInfo.class), null, null, action.toString(), null, null, null, null, null,
- false, false, null, null, null, null, null, null, null);
+ false, false, null, null, null, null, null, null, null, null);
}
static Network createNetwork(Action action) {
return new Network(mock(ModelInfo.class), null, null, action.toString(), null, null, null, null, null, null, false, null, null, null, null,
- null);
+ null, null);
}
}
diff --git a/vid-app-common/src/test/java/org/onap/vid/job/command/VnfCommandTest.kt b/vid-app-common/src/test/java/org/onap/vid/job/command/VnfCommandTest.kt
new file mode 100644
index 000000000..660abe4d2
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/job/command/VnfCommandTest.kt
@@ -0,0 +1,90 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * VID
+ * ================================================================================
+ * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.vid.job.command
+
+import net.javacrumbs.jsonunit.JsonMatchers.jsonPartEquals
+import org.hamcrest.MatcherAssert.assertThat
+import org.hamcrest.core.AllOf.allOf
+import org.mockito.Answers
+import org.mockito.InjectMocks
+import org.mockito.Mock
+import org.onap.vid.job.JobAdapter
+import org.onap.vid.job.JobsBrokerService
+import org.onap.vid.job.command.ResourceCommandTest.FakeResourceCreator
+import org.onap.vid.job.impl.JobSharedData
+import org.onap.vid.model.Action
+import org.onap.vid.mso.RestMsoImplementation
+import org.onap.vid.properties.Features
+import org.onap.vid.services.AsyncInstantiationBusinessLogic
+import org.onap.vid.testUtils.TestUtils
+import org.onap.vid.testUtils.TestUtils.initMockitoMocks
+import org.testng.annotations.BeforeMethod
+import org.testng.annotations.Test
+import org.togglz.core.manager.FeatureManager
+import org.mockito.Mockito.`when` as _when
+
+class VnfCommandTest {
+
+ @Mock lateinit var asyncInstantiationBL: AsyncInstantiationBusinessLogic
+ @Mock lateinit var restMso: RestMsoImplementation
+ @Mock lateinit var msoRequestBuilder: MsoRequestBuilder
+ @Mock lateinit var msoResultHandlerService: MsoResultHandlerService
+ @Mock lateinit var inProgressStatusService:InProgressStatusService
+ @Mock lateinit var watchChildrenJobsBL: WatchChildrenJobsBL
+ @Mock lateinit var jobsBrokerService: JobsBrokerService
+ @Mock lateinit var jobAdapter: JobAdapter
+ @Mock lateinit var featureManager: FeatureManager
+
+ @Mock lateinit var jobSharedData: JobSharedData
+ @Mock(answer = Answers.RETURNS_MOCKS) lateinit var vnfJobRequest: org.onap.vid.model.serviceInstantiation.Vnf
+
+ @InjectMocks lateinit var vnfCommand: VnfCommand;
+
+ @BeforeMethod
+ fun initMocks() {
+ initMockitoMocks(this)
+ }
+
+ @Test(dataProvider = "trueAndFalse", dataProviderClass = TestUtils::class)
+ fun `childVfModuleWithVnfRegionAndTenant -- given vfmodule -- tenant and region are copied from vnf`(featureToggleOn: Boolean) {
+
+ val vfModule = FakeResourceCreator.createVfModule(Action.Create)
+ .cloneWith("vfmodule-lcp-cloud-region-id", "vfmodule-tenant-id")
+
+ _when(featureManager.isActive(Features.FLAG_2006_VFMODULE_TAKES_TENANT_AND_REGION_FROM_VNF)).thenReturn(featureToggleOn)
+
+ _when(vnfJobRequest.lcpCloudRegionId).thenReturn("vnf-lcp-cloud-region-id")
+ _when(vnfJobRequest.tenantId).thenReturn("vnf-tenant-id")
+ _when(jobSharedData.request).thenReturn(vnfJobRequest)
+
+ vnfCommand.init(jobSharedData, mapOf())
+
+ val expectedSource = if (featureToggleOn) "vnf" else "vfmodule"
+
+ assertThat(vnfCommand.childVfModuleWithVnfRegionAndTenant(vfModule),
+ allOf(
+ jsonPartEquals("lcpCloudRegionId", "${expectedSource}-lcp-cloud-region-id"),
+ jsonPartEquals("tenantId", "${expectedSource}-tenant-id")
+ )
+ )
+ }
+
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/job/impl/AsyncInstantiationIntegrationTest.java b/vid-app-common/src/test/java/org/onap/vid/job/impl/AsyncInstantiationIntegrationTest.java
index cd4045b8d..642adb307 100644
--- a/vid-app-common/src/test/java/org/onap/vid/job/impl/AsyncInstantiationIntegrationTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/job/impl/AsyncInstantiationIntegrationTest.java
@@ -59,6 +59,7 @@ import static org.onap.vid.job.Job.JobStatus.STOPPED;
import static org.onap.vid.job.impl.JobSchedulerInitializer.WORKERS_TOPICS;
import static org.onap.vid.model.JobAuditStatus.SourceStatus.VID;
import static org.onap.vid.testUtils.TestUtils.readJsonResourceFileAsObject;
+import static org.testng.Assert.assertNull;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertTrue;
@@ -119,6 +120,7 @@ import org.onap.vid.properties.Features;
import org.onap.vid.services.AsyncInstantiationBaseTest;
import org.onap.vid.services.AsyncInstantiationBusinessLogic;
import org.onap.vid.services.AuditService;
+import org.onap.vid.services.InstantiationTemplatesService;
import org.onap.vid.services.VersionService;
import org.onap.vid.testUtils.TestUtils;
import org.onap.vid.utils.DaoUtils;
@@ -172,6 +174,9 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
@Inject
private CommandUtils commandUtils;
+ @Inject
+ private InstantiationTemplatesService instantiationTemplates;
+
@BeforeClass
void initServicesInfoService() {
createInstanceParamsMaps();
@@ -189,7 +194,12 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
void defineMocks() {
Mockito.reset(restMso);
Mockito.reset(aaiClient);
+ Mockito.reset(commandUtils);
mockAaiClientAnyNameFree();
+
+ when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(true);
+ when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VFMODULE)).thenReturn(true);
+ when(featureManager.isActive(Features.FLAG_2006_VFMODULE_TAKES_TENANT_AND_REGION_FROM_VNF)).thenReturn(true);
}
@Test
@@ -371,9 +381,7 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
* not looking on audit (yet)
*/
- reset(restMso);
- when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(true);
- when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VFMODULE)).thenReturn(false);
+ when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VFMODULE)).thenReturn(false); // this makes the test pass without mocking the vfModules
final String SERVICE_REQUEST_ID = UUID.randomUUID().toString();
final String SERVICE_INSTANCE_ID = UUID.randomUUID().toString();
final String VNF_REQUEST_ID = UUID.randomUUID().toString();
@@ -416,8 +424,6 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
String msoVnfStatus = COMPLETE_STR;
- when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VNF)).thenReturn(true);
- when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VFMODULE)).thenReturn(true);
final String SERVICE_REQUEST_ID = UUID.randomUUID().toString();
final String SERVICE_INSTANCE_ID = UUID.randomUUID().toString();
final String VNF_REQUEST_ID = UUID.randomUUID().toString();
@@ -431,7 +437,6 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
//push alacarte with 1 vnf, verify STATUS pending
UUID uuid = pushALaCarteWithVnf();
singleServicesAndAssertStatus(JobStatus.PENDING, uuid);
- reset(restMso);
/*---------- service -----------*/
@@ -514,8 +519,6 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
NetworkDetails networkDetails1 = new NetworkDetails("LukaDoncic", "1");
NetworkDetails networkDetails2 = new NetworkDetails("KevinDurant", "2");
- reset(restMso);
-
/*---------- service -----------*/
//mock mso to answer 200 of create service instance request, verify STATUS in progress
@@ -1014,8 +1017,6 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
JobStatus expectedJobStatus,
int getStatusCounter) throws IOException, AsdcCatalogException {
- when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VFMODULE)).thenReturn(true);
- reset(commandUtils);
when(commandUtils.isVfModuleBaseModule("6b528779-44a3-4472-bdff-9cd15ec93450", "f8360508-3f17-4414-a2ed-6bc71161e8db")).thenReturn(true);
when(commandUtils.isVfModuleBaseModule("6b528779-44a3-4472-bdff-9cd15ec93450", "25284168-24bb-4698-8cb4-3f509146eca5")).thenReturn(false);
@@ -1266,7 +1267,6 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
asyncRequestStatusResponseAsRestObject(IN_PROGRESS_STR),
asyncRequestStatusResponseAsRestObject(COMPLETE_STR));
- when(featureManager.isActive(Features.FLAG_ASYNC_ALACARTE_VFMODULE)).thenReturn(true);
enableAddCloudOwnerOnMsoRequest();
@@ -1309,4 +1309,41 @@ public class AsyncInstantiationIntegrationTest extends AsyncInstantiationBaseTes
return readJsonResourceFileAsObject("/payload_jsons/vfmodule/upgrade_vfmodule_e2e__fe_input_cypress.json", ServiceInstantiation.class);
}
+ @Test
+ public void deployService_failIt_retryDeploy_getRetryAsTemplate_makeSureFalsyIsFailedInTemplate() {
+
+ final String SERVICE_REQUEST_ID = UUID.randomUUID().toString();
+
+ //push alacarte with 1 vnf, verify STATUS pending
+ UUID uuid = pushALaCarteWithVnf();
+ singleServicesAndAssertStatus(JobStatus.PENDING, uuid);
+
+ //mock mso to answer 200 of create service instance request, verify STATUS in progress
+ when(restMso.restCall(eq(HttpMethod.POST), eq(RequestReferencesContainer.class), any(), endsWith("serviceInstances"), any())).thenReturn(
+ createResponse(200, SERVICE_INSTANCE_ID, SERVICE_REQUEST_ID));
+
+ //mock mso to answer FAILED for service instance create
+ final RestObject<AsyncRequestStatus> failedResponse = asyncRequestStatusResponseAsRestObject(FAILED_STR);
+ final String failureDescription = "Some deep failure";
+ failedResponse.get().request.requestStatus.setStatusMessage(failureDescription);
+ when(restMso.GetForObject(endsWith(SERVICE_REQUEST_ID), eq(AsyncRequestStatus.class))).
+ thenReturn(failedResponse);
+
+ //Wait till job failed
+ processJobsCountTimesAndAssertStatus(uuid, 3, FAILED);
+
+ //make sure retry request jas isFailed = true, and status message is with failureDescription
+ ServiceInstantiation retryRequest = asyncInstantiationBL.getBulkForRetry(uuid);
+ assertTrue(retryRequest.getIsFailed());
+ assertEquals(failureDescription, retryRequest.getStatusMessage());
+
+ //deploy retry job and it's template
+ UUID retryUuid = asyncInstantiationBL.pushBulkJob(retryRequest, USER_ID).get(0);
+ ServiceInstantiation templateOfRetry = instantiationTemplates.getJobRequestAsTemplate(retryUuid);
+
+ //make sure the template request has isFailed = false, and no status message
+ assertFalse(templateOfRetry.getIsFailed());
+ assertNull(templateOfRetry.getStatusMessage());
+ }
+
}
diff --git a/vid-app-common/src/test/java/org/onap/vid/model/ServiceInstanceSearchResultTest.java b/vid-app-common/src/test/java/org/onap/vid/model/ServiceInstanceSearchResultTest.java
index 5168a5c63..b777375ef 100644
--- a/vid-app-common/src/test/java/org/onap/vid/model/ServiceInstanceSearchResultTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/model/ServiceInstanceSearchResultTest.java
@@ -20,183 +20,47 @@
package org.onap.vid.model;
-import org.junit.Test;
+import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanConstructor;
+import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanEqualsFor;
+import static com.google.code.beanmatchers.BeanMatchers.hasValidBeanHashCodeFor;
+import static com.google.code.beanmatchers.BeanMatchers.hasValidGettersAndSetters;
+import static net.javacrumbs.jsonunit.JsonMatchers.jsonNodeAbsent;
+import static net.javacrumbs.jsonunit.JsonMatchers.jsonPartEquals;
+import static org.apache.commons.lang3.ArrayUtils.toArray;
+import static org.hamcrest.CoreMatchers.allOf;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import org.testng.annotations.Test;
public class ServiceInstanceSearchResultTest {
- private ServiceInstanceSearchResult createTestSubject() {
- return new ServiceInstanceSearchResult();
- }
-
- @Test
- public void testGetServiceInstanceId() throws Exception {
- ServiceInstanceSearchResult testSubject;
- String result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getServiceInstanceId();
- }
-
- @Test
- public void testSetServiceInstanceId() throws Exception {
- ServiceInstanceSearchResult testSubject;
- String serviceInstanceId = "";
-
- // default test
- testSubject = createTestSubject();
- testSubject.setServiceInstanceId(serviceInstanceId);
- }
-
- @Test
- public void testGetGlobalCustomerId() throws Exception {
- ServiceInstanceSearchResult testSubject;
- String result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getGlobalCustomerId();
- }
-
- @Test
- public void testSetGlobalCustomerId() throws Exception {
- ServiceInstanceSearchResult testSubject;
- String globalCustomerId = "";
-
- // default test
- testSubject = createTestSubject();
- testSubject.setGlobalCustomerId(globalCustomerId);
- }
-
- @Test
- public void testGetServiceType() throws Exception {
- ServiceInstanceSearchResult testSubject;
- String result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getServiceType();
- }
-
- @Test
- public void testSetServiceType() throws Exception {
- ServiceInstanceSearchResult testSubject;
- String serviceType = "";
-
- // default test
- testSubject = createTestSubject();
- testSubject.setServiceType(serviceType);
- }
-
- @Test
- public void testGetServiceInstanceName() throws Exception {
- ServiceInstanceSearchResult testSubject;
- String result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getServiceInstanceName();
- }
-
- @Test
- public void testSetServiceInstanceName() throws Exception {
- ServiceInstanceSearchResult testSubject;
- String serviceInstanceName = "";
-
- // default test
- testSubject = createTestSubject();
- testSubject.setServiceInstanceName(serviceInstanceName);
- }
-
- @Test
- public void testGetSubscriberName() throws Exception {
- ServiceInstanceSearchResult testSubject;
- String result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getSubscriberName();
- }
-
- @Test
- public void testSetSubscriberName() throws Exception {
- ServiceInstanceSearchResult testSubject;
- String subscriberName = "";
-
- // default test
- testSubject = createTestSubject();
- testSubject.setSubscriberName(subscriberName);
- }
-
@Test
- public void testGetAaiModelInvariantId() throws Exception {
- ServiceInstanceSearchResult testSubject;
- String result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getAaiModelInvariantId();
- }
-
- @Test
- public void testSetAaiModelInvariantId() throws Exception {
- ServiceInstanceSearchResult testSubject;
- String aaiModelInvariantId = "";
-
- // default test
- testSubject = createTestSubject();
- testSubject.setAaiModelInvariantId(aaiModelInvariantId);
- }
-
- @Test
- public void testGetAaiModelVersionId() throws Exception {
- ServiceInstanceSearchResult testSubject;
- String result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getAaiModelVersionId();
+ public void shouldHaveValidGettersAndSetters() {
+ assertThat(ServiceInstanceSearchResult.class, hasValidGettersAndSetters());
}
@Test
- public void testSetAaiModelVersionId() throws Exception {
- ServiceInstanceSearchResult testSubject;
- String aaiModelVersionId = "";
-
- // default test
- testSubject = createTestSubject();
- testSubject.setAaiModelVersionId(aaiModelVersionId);
- }
-
- @Test
- public void testGetIsPermitted() throws Exception {
- ServiceInstanceSearchResult testSubject;
- boolean result;
-
- // default test
- testSubject = createTestSubject();
- result = testSubject.getIsPermitted();
+ public void shouldHaveValidConstructor() {
+ assertThat(ServiceInstanceSearchResult.class, hasValidBeanConstructor());
}
@Test
- public void testSetIsPermitted() throws Exception {
- ServiceInstanceSearchResult testSubject;
- boolean isPermitted = false;
+ public void shouldHaveValidEqualsAndHashCode() {
+ String[] propertiesToEqualBy = toArray("serviceInstanceId");
- // default test
- testSubject = createTestSubject();
- testSubject.setIsPermitted(isPermitted);
+ assertThat(ServiceInstanceSearchResult.class, allOf(
+ hasValidBeanHashCodeFor(propertiesToEqualBy),
+ hasValidBeanEqualsFor(propertiesToEqualBy))
+ );
}
@Test
- public void testEquals() throws Exception {
- ServiceInstanceSearchResult testSubject;
- Object other = null;
- boolean result;
+ public void subscriberId_shouldBeSerializedAsGlobalCustomerId() {
+ ServiceInstanceSearchResult underTest = new ServiceInstanceSearchResult();
+ underTest.setSubscriberId("example");
- // default test
- testSubject = createTestSubject();
- result = testSubject.equals(other);
+ assertThat(underTest, jsonPartEquals("globalCustomerId", "example"));
+ assertThat(underTest, jsonNodeAbsent("subscriberId"));
}
}
diff --git a/vid-app-common/src/test/java/org/onap/vid/model/serviceInstantiation/InstantiationModelSerializationTest.java b/vid-app-common/src/test/java/org/onap/vid/model/serviceInstantiation/InstantiationModelSerializationTest.java
index b5d281622..f0c96b839 100644
--- a/vid-app-common/src/test/java/org/onap/vid/model/serviceInstantiation/InstantiationModelSerializationTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/model/serviceInstantiation/InstantiationModelSerializationTest.java
@@ -38,6 +38,7 @@ import static org.onap.vid.utils.KotlinUtilsKt.JACKSON_OBJECT_MAPPER;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import java.lang.reflect.InvocationTargetException;
+import java.util.List;
import java.util.Map;
import org.apache.commons.beanutils.PropertyUtils;
import org.onap.vid.model.VidNotions;
@@ -45,6 +46,7 @@ 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.mso.model.ModelInfo;
+import org.onap.vid.mso.model.ServiceInstantiationRequestDetails.UserParamNameAndValue;
import org.testng.annotations.Test;
public class InstantiationModelSerializationTest {
@@ -92,7 +94,8 @@ public class InstantiationModelSerializationTest {
new VidNotions(InstantiationUI.ANY_ALACARTE_WHICH_NOT_EXCLUDED,
ModelCategory.INFRASTRUCTURE_VPN,
InstantiationUI.INFRASTRUCTURE_VPN,
- InstantiationType.Macro)
+ InstantiationType.Macro),
+ "originalName"
);
verifySerializationAndDeserialization(serviceInstantiation);
@@ -117,7 +120,8 @@ public class InstantiationModelSerializationTest {
"trackById",
true,
"statusMessage",
- 5);
+ 5,
+ "originalName");
verifySerializationAndDeserialization(vnf);
}
@@ -125,10 +129,10 @@ public class InstantiationModelSerializationTest {
@Test
public void serializeAndDeserializeVfModule() throws Exception {
- ImmutableMap<String, String> supplementaryParams = ImmutableMap.of(
- "uno", "1",
- "dos", "2",
- "tres", "3"
+ List<UserParamNameAndValue> supplementaryParams = ImmutableList.of(
+ new UserParamNameAndValue("uno", "1"),
+ new UserParamNameAndValue("dos", "2"),
+ new UserParamNameAndValue("tres", "3")
);
VfModule vfModule = new VfModule(
@@ -149,7 +153,8 @@ public class InstantiationModelSerializationTest {
"statusMessage",
true,
true,
- 1);
+ 1,
+ "originalName");
verifySerializationAndDeserialization(vfModule);
}
@@ -162,7 +167,7 @@ public class InstantiationModelSerializationTest {
VfModule vfModule = new VfModule(newModelInfo(), null, null, null,
null, null, null, null, null, false,
/* HERE ====> */ USE_PRELOAD,
- null, null, null, null, null, null, null);
+ null, null, null, null, null, null, null, null);
assertThat(vfModule, jsonPartEquals("sdncPreLoad", USE_PRELOAD));
assertThat(vfModule, jsonNodeAbsent("usePreload"));
@@ -177,7 +182,7 @@ public class InstantiationModelSerializationTest {
/* HERE ====> */ VOLUME_GROUP_INSTANCE_NAME,
null, null, null, null, null, null,
false, null, null, null, null, null,
- null, null, null);
+ null, null, null, null);
assertThat(vfModule, jsonPartEquals("volumeGroupName", VOLUME_GROUP_INSTANCE_NAME));
assertThat(vfModule, jsonNodeAbsent("volumeGroupInstanceName"));
diff --git a/vid-app-common/src/test/java/org/onap/vid/model/serviceInstantiation/VfModuleTest.java b/vid-app-common/src/test/java/org/onap/vid/model/serviceInstantiation/VfModuleTest.java
new file mode 100644
index 000000000..a1c78c421
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/model/serviceInstantiation/VfModuleTest.java
@@ -0,0 +1,62 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * VID
+ * ================================================================================
+ * Copyright (C) 2020 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.model.serviceInstantiation;
+
+import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals;
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.beans.HasPropertyWithValue.hasProperty;
+import static org.hamcrest.core.AllOf.allOf;
+import static org.onap.vid.testUtils.TestUtils.setStringsInStringProperties;
+
+import org.onap.vid.mso.model.ModelInfo;
+import org.testng.annotations.Test;
+
+public class VfModuleTest {
+
+ @Test
+ public void cloneWithLcpCloudRegionIdAndTenantId() {
+ String targetLcpCloudRegionId = "dictated lcpCloudRegionId";
+ String targetTenantId = "dictated tenantId";
+
+ VfModule originVfModule = createVfModule();
+
+ assertThat(originVfModule.cloneWith(targetLcpCloudRegionId, targetTenantId), allOf(
+ hasProperty("lcpCloudRegionId", equalTo(targetLcpCloudRegionId)),
+ hasProperty("tenantId", equalTo(targetTenantId)),
+ jsonEquals(originVfModule).whenIgnoringPaths("lcpCloudRegionId", "tenantId")
+ ));
+
+ // verify vfModule did not mutate
+ assertThat(originVfModule, jsonEquals(createVfModule()));
+ }
+
+ private VfModule createVfModule() {
+ VfModule vfModule = new VfModule(
+ setStringsInStringProperties(new ModelInfo()),
+ null, null, null, null, null,
+ null, null, null, true, true,
+ null, null, true, null, true,
+ true, null, null);
+
+ return setStringsInStringProperties(vfModule);
+ }
+} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/MsoUtilTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/MsoUtilTest.java
index 10456bebf..cfde52a56 100644
--- a/vid-app-common/src/test/java/org/onap/vid/mso/MsoUtilTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/mso/MsoUtilTest.java
@@ -26,6 +26,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import io.joshworks.restclient.http.HttpResponse;
import org.onap.vid.testUtils.TestUtils;
+import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class MsoUtilTest {
@@ -67,4 +68,26 @@ public class MsoUtilTest {
assertThat(result.getStatus()).isEqualTo(SC_OK);
}
+ @DataProvider
+ public static Object[][] formatExceptionAdditionalInfo() {
+ return new Object[][]{
+ {"message", "Http Code:400, message"},
+
+ {null, "Http Code:400"},
+
+ {"{\"requestError\":{\"serviceException\":{\"messageId\":\"SVC0002\",\"text\":\"message\"}}}",
+ "Http Code:400, \"messageId\":\"SVC0002\",\"text\":\"message\""},
+
+ {"{\"validJson\": \"Error: message\"}", "Http Code:400, {\"validJson\": \"Error: message\"}"},
+
+ {"{\"serviceException\":{\"messageId\":\"SVC0002\",\"text\":\"Error: message\"}}",
+ "Http Code:400, \"messageId\":\"SVC0002\",\"text\":\"Error: message\""},
+ };
+ }
+
+ @Test(dataProvider = "formatExceptionAdditionalInfo")
+ public void formatExceptionAdditionalInfo_payloadWithError400_doNotReturnNull(String payload, String expected) {
+ assertThat(MsoUtil.formatExceptionAdditionalInfo(400, payload))
+ .isEqualTo(expected);
+ }
}
diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/model/RequestParametersVfModuleTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/model/RequestParametersVfModuleTest.java
new file mode 100644
index 000000000..e339af094
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/mso/model/RequestParametersVfModuleTest.java
@@ -0,0 +1,49 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * VID
+ * ================================================================================
+ * Copyright (C) 2020 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.mso.model;
+
+import static java.util.Collections.emptyList;
+import static net.javacrumbs.jsonunit.JsonMatchers.jsonPartEquals;
+import static org.hamcrest.MatcherAssert.assertThat;
+
+import org.testng.annotations.Test;
+
+public class RequestParametersVfModuleTest {
+
+ @Test
+ public void RequestParametersVfModuleOrVolumeGroupInstantiation_whenUsePreloadIsNull_thenLiteralFalseIsSerialized() {
+ Boolean usePreload = null;
+ assertThat(
+ new RequestParametersVfModuleOrVolumeGroupInstantiation(emptyList(), usePreload, ""),
+ jsonPartEquals("usePreload", false)
+ );
+ }
+
+ @Test
+ public void RequestParametersVfModuleUpgrade_whenUsePreloadIsNull_thenLiteralFalseIsSerialized() {
+ Boolean usePreload = null;
+ assertThat(
+ new RequestParametersVfModuleUpgrade(emptyList(), usePreload, "", false, false),
+ jsonPartEquals("usePreload", false)
+ );
+ }
+
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/properties/FeatureSetsManagerTest.kt b/vid-app-common/src/test/java/org/onap/vid/properties/FeatureSetsManagerTest.kt
new file mode 100644
index 000000000..9cf7aa662
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/properties/FeatureSetsManagerTest.kt
@@ -0,0 +1,101 @@
+package org.onap.vid.properties
+
+import org.hamcrest.CoreMatchers.*
+import org.hamcrest.MatcherAssert.assertThat
+import org.mockito.ArgumentMatchers.anyString
+import org.mockito.InjectMocks
+import org.mockito.Mock
+import org.mockito.Mockito.*
+import org.onap.vid.testUtils.TestUtils
+import org.springframework.web.context.request.RequestContextHolder
+import org.testng.annotations.BeforeMethod
+import org.testng.annotations.Test
+import org.togglz.core.manager.FeatureManager
+import javax.servlet.ServletContext
+import javax.servlet.http.Cookie
+import javax.servlet.http.HttpServletRequest
+import org.hamcrest.CoreMatchers.`is` as _is
+import org.mockito.Mockito.`when` as _when
+
+class FeatureSetsManagerTest {
+ @Mock
+ lateinit var defaultFeatureManager: FeatureManager
+ @Mock
+ lateinit var servletContext: ServletContext
+ @Mock
+ lateinit var alternativeFeatureSetNameProvider: AlternativeFeatureSetNameProvider
+ @InjectMocks
+ lateinit var featureSetsManager: FeatureSetsManager
+
+ private val alternativeFeatureSetNameFromCookie = AlternativeFeatureSetNameFromCookie()
+
+ @BeforeMethod
+ fun setUp() {
+ TestUtils.initMockitoMocks(this)
+ }
+
+ @Test
+ fun `isActive - without alternative features set name - delegates to default and no file loaded`() {
+ _when(defaultFeatureManager.isActive(Features.FLAG_1810_AAI_LOCAL_CACHE)).thenReturn(true)
+ _when(alternativeFeatureSetNameProvider.alternativeFeatureSetName).thenReturn(null)
+
+ assertThat(featureSetsManager.isActive(Features.FLAG_1810_AAI_LOCAL_CACHE), _is(true))
+
+ verifyZeroInteractions(servletContext) // implies no other file loaded
+ verify(defaultFeatureManager, times(1)).isActive(Features.FLAG_1810_AAI_LOCAL_CACHE)
+ }
+
+ @Test
+ fun `isActive - with alternative features set - brings flags from alternative`() {
+ _when(servletContext.getRealPath(anyString())).thenReturn(this.javaClass.getResource("/").path)
+ _when(alternativeFeatureSetNameProvider.alternativeFeatureSetName).thenReturn("example.features.properties")
+
+ assertThat(featureSetsManager.isActive(Features.FLAG_1810_AAI_LOCAL_CACHE), _is(true))
+ assertThat(featureSetsManager.isActive(Features.FLAG_1902_NEW_VIEW_EDIT), _is(false))
+ verifyZeroInteractions(defaultFeatureManager)
+ }
+
+ @Test
+ fun `isActive - with non-existing alternative features set - fallback is to all flags off`() {
+ _when(servletContext.getRealPath(anyString())).thenReturn(this.javaClass.getResource("/").path)
+ _when(alternativeFeatureSetNameProvider.alternativeFeatureSetName).thenReturn("non-existing")
+
+ assertThat(featureSetsManager, not(nullValue()))
+ assertThat(
+ featureSetsManager.features.map { featureSetsManager.isActive(it) },
+ not(hasItem(true))
+ )
+ }
+
+ @Test
+ fun `valueFromCookie - given no request - return null`() {
+ assertThat(alternativeFeatureSetNameFromCookie.valueFromCookie(null), _is(nullValue()))
+ }
+
+ @Test
+ fun `valueFromCookie - given request - return the correct cookie value`() {
+ val servletRequestMock = mock(HttpServletRequest::class.java)
+ _when(servletRequestMock.cookies).thenReturn(arrayOf(Cookie("features.set", "value")))
+
+ assertThat(alternativeFeatureSetNameFromCookie.valueFromCookie(servletRequestMock), _is("value"))
+ }
+
+ @Test
+ fun `valueFromCookie - given request without cookies - return null`() {
+ val servletRequestMock = mock(HttpServletRequest::class.java)
+ _when(servletRequestMock.cookies).thenReturn(emptyArray())
+
+ assertThat(alternativeFeatureSetNameFromCookie.valueFromCookie(servletRequestMock), _is(nullValue()))
+ }
+
+ @Test
+ fun `currentHttpRequest - when no current request - return null`() {
+ assertPrecondition()
+ assertThat(alternativeFeatureSetNameFromCookie.currentHttpRequest(), _is(nullValue()))
+ }
+
+ private fun assertPrecondition() {
+ assertThat("precondition for test not met: static RequestContextHolder.getRequestAttributes should be null",
+ RequestContextHolder.getRequestAttributes(), _is(nullValue()))
+ }
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/roles/AlwaysValidRoleValidatorTest.java b/vid-app-common/src/test/java/org/onap/vid/roles/AlwaysValidRoleValidatorTest.java
index 363c6ff76..6826b1e4a 100644
--- a/vid-app-common/src/test/java/org/onap/vid/roles/AlwaysValidRoleValidatorTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/roles/AlwaysValidRoleValidatorTest.java
@@ -33,7 +33,8 @@ public class AlwaysValidRoleValidatorTest {
@Test
public void testIsServicePermitted() {
- assertTrue(new AlwaysValidRoleValidator().isServicePermitted("any", "any"));
+ WithPermissionProperties emptyPermissionProperties = new WithPermissionProperties() {};
+ assertTrue(new AlwaysValidRoleValidator().isServicePermitted(emptyPermissionProperties));
}
@Test
diff --git a/vid-app-common/src/test/java/org/onap/vid/roles/RoleProviderTest.java b/vid-app-common/src/test/java/org/onap/vid/roles/RoleProviderTest.java
index c1033d2d0..8d81c929c 100644
--- a/vid-app-common/src/test/java/org/onap/vid/roles/RoleProviderTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/roles/RoleProviderTest.java
@@ -22,6 +22,7 @@ package org.onap.vid.roles;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
@@ -42,7 +43,7 @@ import org.testng.annotations.Test;
public class RoleProviderTest {
private static final String SAMPLE_SUBSCRIBER = "sampleSubscriber";
- private static final String SAMPLE_CUSTOMER_ID = "sampleCustomerId";
+ private static final String SAMPLE_SUBSCRIBER_ID = "subscriberId";
private static final String SERVICE_TYPE_LOGS = "LOGS";
private static final String TENANT_PERMITTED = "PERMITTED";
private static final String SAMPLE_SERVICE = "sampleService";
@@ -58,13 +59,16 @@ public class RoleProviderTest {
@Mock
private AaiResponse<SubscriberList> subscriberListResponse;
+ @Mock
+ private RoleValidatorFactory roleValidatorFactory;
+
private RoleProvider roleProvider;
@BeforeMethod
public void setUp() {
initMocks(this);
- roleProvider = new RoleProvider(aaiService, httpServletRequest -> 5, httpServletRequest -> createRoles());
+ roleProvider = new RoleProvider(aaiService, roleValidatorFactory, httpServletRequest -> 5, httpServletRequest -> createRoles());
}
@Test
@@ -83,7 +87,7 @@ public class RoleProviderTest {
Role role = roleProvider.createRoleFromStringArr(roleParts, SAMPLE_ROLE_PREFIX);
assertThat(role.getEcompRole()).isEqualTo(EcompRole.READ);
- assertThat(role.getSubscribeName()).isEqualTo(SAMPLE_CUSTOMER_ID);
+ assertThat(role.getSubscriberId()).isEqualTo(SAMPLE_SUBSCRIBER_ID);
assertThat(role.getTenant()).isEqualTo(SAMPLE_TENANT);
assertThat(role.getServiceType()).isEqualTo(SAMPLE_SERVICE);
}
@@ -97,7 +101,7 @@ public class RoleProviderTest {
Role role = roleProvider.createRoleFromStringArr(roleParts, SAMPLE_ROLE_PREFIX);
assertThat(role.getEcompRole()).isEqualTo(EcompRole.READ);
- assertThat(role.getSubscribeName()).isEqualTo(SAMPLE_CUSTOMER_ID);
+ assertThat(role.getSubscriberId()).isEqualTo(SAMPLE_SUBSCRIBER_ID);
assertThat(role.getServiceType()).isEqualTo(SAMPLE_SERVICE);
assertThat(role.getTenant()).isNullOrEmpty();
}
@@ -111,7 +115,7 @@ public class RoleProviderTest {
@Test
public void shouldProperlyRetrieveUserRolesWhenPermissionIsDifferentThanRead() {
- Role expectedRole = new Role(EcompRole.READ, SAMPLE_CUSTOMER_ID, SAMPLE_SERVICE, SAMPLE_TENANT);
+ Role expectedRole = new Role(EcompRole.READ, SAMPLE_SUBSCRIBER_ID, SAMPLE_SERVICE, SAMPLE_TENANT, owningEntityId());
setSubscribers();
List<Role> userRoles = roleProvider.getUserRoles(request);
@@ -121,7 +125,7 @@ public class RoleProviderTest {
Role actualRole = userRoles.get(0);
assertThat(actualRole.getTenant()).isEqualTo(expectedRole.getTenant());
- assertThat(actualRole.getSubscribeName()).isEqualTo(expectedRole.getSubscribeName());
+ assertThat(actualRole.getSubscriberId()).isEqualTo(expectedRole.getSubscriberId());
assertThat(actualRole.getServiceType()).isEqualTo(expectedRole.getServiceType());
}
@@ -132,21 +136,38 @@ public class RoleProviderTest {
@Test
public void shouldReturnNotReadOnlyPermissionWhenRolesArePresent() {
- assertThat(roleProvider.userPermissionIsReadOnly(Lists.list(new Role(EcompRole.READ, SAMPLE_SUBSCRIBER, SAMPLE_SERVICE, SAMPLE_TENANT)))).isFalse();
+ assertThat(roleProvider.userPermissionIsReadOnly(Lists.list(new Role(
+ EcompRole.READ, SAMPLE_SUBSCRIBER, SAMPLE_SERVICE, SAMPLE_TENANT, owningEntityId())))).isFalse();
}
@Test
public void userShouldHavePermissionToReadLogsWhenServiceAndTenantAreCorrect() {
- Role withoutPermission = new Role(EcompRole.READ, SAMPLE_SUBSCRIBER, SAMPLE_SERVICE, SAMPLE_TENANT);
- Role withPermission = new Role(EcompRole.READ, SAMPLE_SUBSCRIBER, SERVICE_TYPE_LOGS, TENANT_PERMITTED);
+ Role withoutPermission = new Role(EcompRole.READ, SAMPLE_SUBSCRIBER, SAMPLE_SERVICE, SAMPLE_TENANT, owningEntityId());
+ Role withPermission = new Role(EcompRole.READ, SAMPLE_SUBSCRIBER, SERVICE_TYPE_LOGS, TENANT_PERMITTED, owningEntityId());
assertThat(roleProvider.userPermissionIsReadLogs(Lists.list(withoutPermission, withPermission))).isTrue();
}
+ @Test
+ public void getUserRolesValidator_shouldReturnValidatorFromFactory() {
+ RoleValidator expectedRoleValidator = new AlwaysValidRoleValidator();
+ when(roleValidatorFactory.by(any())).thenReturn(expectedRoleValidator);
+
+ RoleValidator result = roleProvider.getUserRolesValidator(request);
+
+ assertThat(result).isEqualTo(expectedRoleValidator);
+ }
+
+ private String owningEntityId() {
+ // while translateOwningEntityNameToOwningEntityId does nothing, no translation happens.
+ // this will be changed later.
+ return SAMPLE_SUBSCRIBER;
+ }
+
private void setSubscribers() {
Subscriber subscriber = new Subscriber();
subscriber.subscriberName = SAMPLE_SUBSCRIBER;
- subscriber.globalCustomerId = SAMPLE_CUSTOMER_ID;
+ subscriber.globalCustomerId = SAMPLE_SUBSCRIBER_ID;
SubscriberList subscriberList = new SubscriberList(Lists.list(subscriber));
when(aaiService.getFullSubscriberList()).thenReturn(subscriberListResponse);
when(subscriberListResponse.getT()).thenReturn(subscriberList);
diff --git a/vid-app-common/src/test/java/org/onap/vid/roles/RoleValidatorByOwningEntityTest.java b/vid-app-common/src/test/java/org/onap/vid/roles/RoleValidatorByOwningEntityTest.java
new file mode 100644
index 000000000..d84ac6edd
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/roles/RoleValidatorByOwningEntityTest.java
@@ -0,0 +1,90 @@
+/*-
+ * ============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.roles;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.withSettings;
+import static org.testng.Assert.assertFalse;
+
+import com.google.common.collect.ImmutableList;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+public class RoleValidatorByOwningEntityTest {
+
+ private static final String OWNING_ENTITY_ID = "owningEntityId";
+ private static final String SUBSCRIBER_NAME = "subscriber_name";
+ private static final String NOT_MATCHING_OWNING_ENTITY_ID = "notMatchingOwningEntityId";
+
+ private static final String SERVICE_TYPE = "serviceType";
+ private static final String GLOBAL_CUSTOMER_ID = "globalCustomerId";
+ private static final String TENANT_NAME = "tenantName";
+
+
+ private RoleValidatorByOwningEntity roleValidatorByOwningEntity;
+
+ @BeforeMethod
+ public void setup() {
+ final Role SAMPLE_ROLE = new Role(EcompRole.READ, "", "", "", OWNING_ENTITY_ID);
+ roleValidatorByOwningEntity = new RoleValidatorByOwningEntity(ImmutableList.of(SAMPLE_ROLE));
+ }
+
+ @Test
+ public void testIsSubscriberPermitted() {
+ assertFalse(roleValidatorByOwningEntity.isSubscriberPermitted(SUBSCRIBER_NAME));
+ }
+
+ @Test
+ public void isServicePermitted_owningEntityMatch_returnTrue() {
+ PermissionPropertiesOwningEntity permittedOwningEntity =
+ new PermissionPropertiesOwningEntity(OWNING_ENTITY_ID);
+
+ assertThat(roleValidatorByOwningEntity.isServicePermitted(permittedOwningEntity), is(true));
+ }
+
+ @DataProvider
+ public static Object[][] nonMatchingPermissionProperties() {
+ return new Object[][]{
+ {new PermissionPropertiesOwningEntity(NOT_MATCHING_OWNING_ENTITY_ID)},
+ {new PermissionPropertiesOwningEntity("")},
+ {new WithPermissionProperties() {}},
+ {mock(PermissionPropertiesOwningEntity.class,
+ withSettings().name("PermissionPropertiesOwningEntity with null owningEntityId"))},
+ {new PermissionPropertiesSubscriberAndServiceType(OWNING_ENTITY_ID, OWNING_ENTITY_ID)},
+ };
+ }
+
+ @Test(dataProvider = "nonMatchingPermissionProperties")
+ public void isServicePermitted_nonMatchingPermissionProperties_returnFalse(WithPermissionProperties permissionProperties) {
+ assertThat(permissionProperties.toString(), roleValidatorByOwningEntity.isServicePermitted(
+ permissionProperties
+ ), is(false));
+ }
+
+ @Test
+ public void testIsTenantPermitted() {
+ assertFalse(roleValidatorByOwningEntity.isTenantPermitted(GLOBAL_CUSTOMER_ID, SERVICE_TYPE, TENANT_NAME));
+ }
+
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/roles/RoleValidatorByRolesTest.java b/vid-app-common/src/test/java/org/onap/vid/roles/RoleValidatorByRolesTest.java
deleted file mode 100644
index 9362ec9d7..000000000
--- a/vid-app-common/src/test/java/org/onap/vid/roles/RoleValidatorByRolesTest.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * VID
- * ================================================================================
- * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.onap.vid.roles;
-
-
-import static org.assertj.core.api.Assertions.assertThat;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import java.util.List;
-import java.util.Map;
-import org.onap.vid.mso.rest.RequestDetails;
-import org.testng.annotations.BeforeMethod;
-import org.testng.annotations.Test;
-
-public class RoleValidatorByRolesTest {
-
- private static final String SAMPLE_SUBSCRIBER = "sampleSubscriber";
- private static final String NOT_MATCHING_SUBSCRIBER = "notMatchingSubscriber";
- private static final String SAMPLE_SERVICE_TYPE = "sampleServiceType";
- private static final String NOT_MATCHING_TENANT = "notMatchingTenant";
- private static final String SAMPLE_TENANT = "sampleTenant";
-
- private static final Role SAMPLE_ROLE = new Role(EcompRole.READ, SAMPLE_SUBSCRIBER, SAMPLE_SERVICE_TYPE, SAMPLE_TENANT);
-
- private List<Role> roles = ImmutableList.of(SAMPLE_ROLE);
- private Map<String, Object> subscriberInfo = ImmutableMap.of("globalSubscriberId", SAMPLE_SUBSCRIBER);
- private Map<String, Object> requestParameters = ImmutableMap.of("subscriptionServiceType", SAMPLE_SERVICE_TYPE);
- private Map<String, Object> requestDetailsProperties = ImmutableMap.of("subscriberInfo", subscriberInfo, "requestParameters", requestParameters);
- private RequestDetails requestDetails;
- private RoleValidatorByRoles roleValidator;
-
- @BeforeMethod
- public void setUp() {
- roleValidator = new RoleValidatorByRoles(roles);
- requestDetails = new RequestDetails();
- }
-
- @Test
- public void shouldPermitSubscriberWhenNameMatchesAndRolesAreEnabled() {
- assertThat(roleValidator.isSubscriberPermitted(SAMPLE_SUBSCRIBER)).isTrue();
- }
-
- @Test
- public void shouldNotPermitSubscriberWhenNameNotMatches() {
- assertThat(roleValidator.isSubscriberPermitted(NOT_MATCHING_SUBSCRIBER)).isFalse();
- }
-
- @Test
- public void shouldPermitServiceWhenNamesMatches() {
- assertThat(roleValidator.isServicePermitted(SAMPLE_SUBSCRIBER, SAMPLE_SERVICE_TYPE)).isTrue();
- }
-
-
- @Test
- public void shouldNotPermitServiceWhenSubscriberNameNotMatches() {
- assertThat(roleValidator.isServicePermitted(NOT_MATCHING_SUBSCRIBER, SAMPLE_SERVICE_TYPE)).isFalse();
- }
-
- @Test
- public void shouldNotPermitServiceWhenServiceTypeNotMatches() {
- assertThat(roleValidator.isServicePermitted(SAMPLE_SUBSCRIBER, NOT_MATCHING_SUBSCRIBER)).isFalse();
- }
-
- @Test
- public void shouldPermitTenantWhenNameMatches() {
- assertThat(roleValidator.isTenantPermitted(SAMPLE_SUBSCRIBER, SAMPLE_SERVICE_TYPE, SAMPLE_TENANT)).isTrue();
- }
-
-
- @Test
- public void shouldNotPermitTenantWhenNameNotMatches() {
- assertThat(roleValidator.isTenantPermitted(SAMPLE_SUBSCRIBER, SAMPLE_SERVICE_TYPE, NOT_MATCHING_TENANT)).isFalse();
- }
-
- @Test
- public void shouldValidateProperlySORequest() {
- requestDetails.setAdditionalProperty("requestDetails", requestDetailsProperties);
-
- assertThat(roleValidator.isMsoRequestValid(requestDetails)).isTrue();
- }
-
- @Test
- public void shouldValidateUnknownSORequest() {
- assertThat(roleValidator.isMsoRequestValid(new RequestDetails())).isTrue();
- }
-
- @Test
- public void shouldRejectSORequestWhenSubscriberNotMatches() {
- Map<String, Object> subscriberInfo = ImmutableMap.of("globalSubscriberId", "sample");
- Map<String, Object> requestDetailsProperties = ImmutableMap.of("subscriberInfo", subscriberInfo, "requestParameters", requestParameters);
- requestDetails.setAdditionalProperty("requestDetails", requestDetailsProperties);
-
- assertThat(roleValidator.isMsoRequestValid(requestDetails)).isFalse();
- }
-}
diff --git a/vid-app-common/src/test/java/org/onap/vid/roles/RoleValidatorBySubscriberAndServiceTypeTest.java b/vid-app-common/src/test/java/org/onap/vid/roles/RoleValidatorBySubscriberAndServiceTypeTest.java
new file mode 100644
index 000000000..b6958cd67
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/roles/RoleValidatorBySubscriberAndServiceTypeTest.java
@@ -0,0 +1,111 @@
+/*-
+ * ============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.roles;
+
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.google.common.collect.ImmutableList;
+import java.util.List;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class RoleValidatorBySubscriberAndServiceTypeTest {
+
+ private static final String SAMPLE_SUBSCRIBER = "sampleSubscriber";
+ private static final String NOT_MATCHING_SUBSCRIBER = "notMatchingSubscriber";
+ private static final String SAMPLE_SERVICE_TYPE = "sampleServiceType";
+ private static final String NOT_MATCHING_TENANT = "notMatchingTenant";
+ private static final String SAMPLE_TENANT = "sampleTenant";
+ private static final String SOME_OWNING_ENTITY_ID = "someOwningEntityId";
+
+ private static final Role SAMPLE_ROLE = new Role(
+ EcompRole.READ, SAMPLE_SUBSCRIBER, SAMPLE_SERVICE_TYPE, SAMPLE_TENANT, SOME_OWNING_ENTITY_ID);
+
+ private List<Role> roles = ImmutableList.of(SAMPLE_ROLE);
+ private RoleValidatorBySubscriberAndServiceType roleValidatorBySubscriberAndServiceType;
+
+ @BeforeMethod
+ public void setUp() {
+ roleValidatorBySubscriberAndServiceType = new RoleValidatorBySubscriberAndServiceType(roles);
+ }
+
+ @Test
+ public void shouldPermitSubscriberWhenNameMatchesAndRolesAreEnabled() {
+ assertThat(roleValidatorBySubscriberAndServiceType.isSubscriberPermitted(SAMPLE_SUBSCRIBER)).isTrue();
+ }
+
+ @Test
+ public void shouldNotPermitSubscriberWhenNameNotMatches() {
+ assertThat(roleValidatorBySubscriberAndServiceType.isSubscriberPermitted(NOT_MATCHING_SUBSCRIBER)).isFalse();
+ }
+
+ @Test
+ public void shouldPermitServiceWhenNamesMatches() {
+ assertThat(roleValidatorBySubscriberAndServiceType.isServicePermitted(
+ new PermissionPropertiesSubscriberAndServiceType(SAMPLE_SUBSCRIBER, SAMPLE_SERVICE_TYPE))).isTrue();
+ }
+
+ @Test
+ public void isServicePermitted_serviceWithAllPermissionProperties_isPermitted() {
+ assertThat(roleValidatorBySubscriberAndServiceType.isServicePermitted(
+ new AllPermissionProperties(SAMPLE_SUBSCRIBER, SAMPLE_SERVICE_TYPE, SOME_OWNING_ENTITY_ID))).isTrue();
+ }
+
+ @Test
+ public void shouldNotPermitServiceWhenSubscriberNameNotMatches() {
+ assertThat(
+ roleValidatorBySubscriberAndServiceType.isServicePermitted(
+ new PermissionPropertiesSubscriberAndServiceType(NOT_MATCHING_SUBSCRIBER, SAMPLE_SERVICE_TYPE))).isFalse();
+ }
+
+ @Test
+ public void shouldNotPermitServiceWhenServiceTypeNotMatches() {
+ assertThat(roleValidatorBySubscriberAndServiceType.isServicePermitted(
+ new PermissionPropertiesSubscriberAndServiceType(SAMPLE_SUBSCRIBER, NOT_MATCHING_SUBSCRIBER))).isFalse();
+ }
+
+ @Test
+ public void isServicePermitted_owningEntityPermissionProperties_isNotPermitted() {
+ assertThat(roleValidatorBySubscriberAndServiceType.isServicePermitted(
+ new PermissionPropertiesOwningEntity(SAMPLE_SUBSCRIBER))).isFalse();
+ }
+
+ @Test
+ public void shouldPermitTenantWhenNameMatches() {
+ assertThat(roleValidatorBySubscriberAndServiceType
+ .isTenantPermitted(SAMPLE_SUBSCRIBER, SAMPLE_SERVICE_TYPE, SAMPLE_TENANT)).isTrue();
+ }
+
+ @Test
+ public void shouldPermitTenantWhenNameMatchesCaseInsensitive() {
+ assertThat(roleValidatorBySubscriberAndServiceType
+ .isTenantPermitted(SAMPLE_SUBSCRIBER, SAMPLE_SERVICE_TYPE, SAMPLE_TENANT.toUpperCase())).isTrue();
+ }
+
+
+ @Test
+ public void shouldNotPermitTenantWhenNameNotMatches() {
+ assertThat(roleValidatorBySubscriberAndServiceType
+ .isTenantPermitted(SAMPLE_SUBSCRIBER, SAMPLE_SERVICE_TYPE, NOT_MATCHING_TENANT)).isFalse();
+ }
+
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/roles/RoleValidatorFactoryTest.java b/vid-app-common/src/test/java/org/onap/vid/roles/RoleValidatorFactoryTest.java
new file mode 100644
index 000000000..b3c71c547
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/roles/RoleValidatorFactoryTest.java
@@ -0,0 +1,77 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * VID
+ * ================================================================================
+ * Copyright (C) 2017 - 2020 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.roles;
+
+import static java.util.Collections.emptyList;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.instanceOf;
+import static org.mockito.Mockito.when;
+
+import java.util.Collections;
+import java.util.List;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+import org.onap.vid.properties.Features;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+import org.togglz.core.manager.FeatureManager;
+
+public class RoleValidatorFactoryTest {
+
+ @InjectMocks
+ private RoleValidatorFactory roleValidatorFactory;
+
+ @Mock
+ private FeatureManager featureManager;
+
+ @BeforeClass
+ public void initMocks() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @AfterMethod
+ public void reset() {
+ Mockito.reset(featureManager);
+ }
+
+ @Test (dataProvider = "presetRoleValidatorClass")
+ public void returnRoleValidatorByGivenClass_And_RoleManagementActivated_And_FeatureFlag(Class expectedClass,boolean isDisabledRoles, boolean flagActive ) {
+
+ when(featureManager.isActive(Features.FLAG_2006_USER_PERMISSIONS_BY_OWNING_ENTITY)).thenReturn(flagActive);
+ RoleValidator roleValidator = roleValidatorFactory.by(emptyList(), isDisabledRoles);
+ assertThat(roleValidator, instanceOf(expectedClass));
+ }
+
+ @DataProvider
+ public static Object[][] presetRoleValidatorClass() {
+ return new Object[][] {
+ {RoleValidatorsComposer.class, false, true},
+ {AlwaysValidRoleValidator.class, true, true},
+ {RoleValidatorBySubscriberAndServiceType.class, false, false},
+ {AlwaysValidRoleValidator.class, true, false}
+ };
+ }
+
+} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/roles/RoleValidatorsComposerTest.java b/vid-app-common/src/test/java/org/onap/vid/roles/RoleValidatorsComposerTest.java
new file mode 100644
index 000000000..c0892dafb
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/roles/RoleValidatorsComposerTest.java
@@ -0,0 +1,110 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * VID
+ * ================================================================================
+ * Copyright (C) 2017 - 2020 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.roles;
+
+import static java.util.stream.Collectors.toList;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyZeroInteractions;
+import static org.mockito.Mockito.withSettings;
+
+import com.google.common.collect.ImmutableSet;
+import java.util.function.Function;
+import java.util.stream.Stream;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+public class RoleValidatorsComposerTest {
+
+ private RoleValidator alwaysTrueRoles;
+ private RoleValidator alwaysFalseRoles;
+
+ @DataProvider
+ public static Object[][] allInterfaceFunctions() {
+ return Stream.<Function<RoleValidator, Boolean>>of(
+ (RoleValidator o) -> o.isSubscriberPermitted("subscriberId"),
+ (RoleValidator o) -> o.isServicePermitted(new WithPermissionProperties() {}),
+ (RoleValidator o) -> o.isTenantPermitted("subscriberId", "serviceType", "tenantName")
+ ).map(it -> new Object[]{it}).collect(toList()).toArray(new Object[][]{});
+ }
+
+ @BeforeMethod
+ public void setUp() {
+ alwaysTrueRoles = mock(RoleValidator.class, withSettings().defaultAnswer(o -> true));
+ alwaysFalseRoles = mock(RoleValidator.class);
+ }
+
+ @Test(dataProvider = "allInterfaceFunctions")
+ public void emptyComposite_returnsFalse(Function<RoleValidator, Boolean> interfaceFunction) {
+ RoleValidatorsComposer underTest = new RoleValidatorsComposer();
+
+ assertThat(
+ interfaceFunction.apply(underTest),
+ is(false)
+ );
+
+ }
+
+ @Test(dataProvider = "allInterfaceFunctions")
+ public void falseAndTrueComposite_returnsTrue(Function<RoleValidator, Boolean> interfaceFunction) {
+ RoleValidatorsComposer underTest =
+ new RoleValidatorsComposer(alwaysFalseRoles, alwaysFalseRoles, alwaysTrueRoles);
+
+ assertThat(
+ interfaceFunction.apply(underTest),
+ is(true)
+ );
+ }
+
+ @Test(dataProvider = "allInterfaceFunctions")
+ public void trueAndFalseComposite_returnsTrueAndShortCircuits(Function<RoleValidator, Boolean> interfaceFunction) {
+ RoleValidatorsComposer underTest = new RoleValidatorsComposer(alwaysTrueRoles, alwaysFalseRoles);
+
+ assertThat(
+ interfaceFunction.apply(underTest),
+ is(true)
+ );
+
+ verifyZeroInteractions(alwaysFalseRoles);
+ }
+
+ @Test(dataProvider = "allInterfaceFunctions")
+ public void falseAndFalseComposite_returnsFalse(Function<RoleValidator, Boolean> interfaceFunction) {
+ RoleValidatorsComposer underTest = new RoleValidatorsComposer(alwaysFalseRoles, alwaysFalseRoles);
+
+ assertThat(
+ interfaceFunction.apply(underTest),
+ is(false)
+ );
+ }
+
+ @Test
+ public void secondaryConstructor_givenSetIfValidators_returnsTrue() {
+ RoleValidatorsComposer underTest = new RoleValidatorsComposer(
+ ImmutableSet.of(alwaysTrueRoles)
+ );
+
+ assertThat(underTest.isSubscriberPermitted("anything"), is(true));
+ }
+
+}
diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AAITreeNodeBuilderTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AAITreeNodeBuilderTest.java
index 29041839a..67d3d4a9a 100644
--- a/vid-app-common/src/test/java/org/onap/vid/services/AAITreeNodeBuilderTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/services/AAITreeNodeBuilderTest.java
@@ -50,7 +50,10 @@ import java.util.Optional;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
+import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.lang3.tuple.Pair;
+import org.apache.log4j.LogManager;
+import org.apache.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.mockito.Mock;
import org.mockito.stubbing.Answer;
@@ -79,6 +82,7 @@ public class AAITreeNodeBuilderTest {
private ExecutorService executorService;
private Logging logging = new Logging();
+ private static final Logger logger = LogManager.getLogger(AAITreeNodeBuilderTest.class);
private static final ObjectMapper mapper = new ObjectMapper();
@@ -92,7 +96,9 @@ public class AAITreeNodeBuilderTest {
private void buildNodeAndAssert(JsonNode inputNode, AAITreeNode expectedNode, NodeType nodeType){
ConcurrentSkipListSet<AAITreeNode> nodesAccumulator = new ConcurrentSkipListSet<>(comparing(AAITreeNode::getUniqueNodeKey));
when(aaiClientMock.typedAaiRest(Unchecked.toURI("anyUrl"), JsonNode.class, null, HttpMethod.GET, false)).thenReturn(inputNode);
- AAITreeNode actualNode = aaiTreeNodeBuilder.buildNode(
+ AAITreeNode actualNode;
+ try {
+ actualNode = aaiTreeNodeBuilder.buildNode(
nodeType,
"anyUrl",
null,
@@ -100,7 +106,16 @@ public class AAITreeNodeBuilderTest {
nodesAccumulator,
executorService,
AAI_TREE_PATHS.getSubTree(new AAIServiceTree.AaiRelationship(nodeType))
- ).get(0);
+ ).get(0);
+ } catch (Throwable e) {
+ //print stack traces for more information in case of failure
+ System.out.println("Failed to build node by aaiTreeNodeBuilder");
+ ExceptionUtils.getThrowableList(e)
+ .stream()
+ .peek(it ->System.err.println(it.getLocalizedMessage()))
+ .forEach(Throwable::printStackTrace);
+ throw e;
+ }
assertThat(actualNode, jsonEquals(expectedNode).when(IGNORING_ARRAY_ORDER, IGNORING_EXTRA_FIELDS).whenIgnoringPaths("relationshipList","children[0].relationshipList"));
}
diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AaiServiceImplTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AaiServiceImplTest.java
index d3b2a48b1..a37482624 100644
--- a/vid-app-common/src/test/java/org/onap/vid/services/AaiServiceImplTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/services/AaiServiceImplTest.java
@@ -183,7 +183,7 @@ public class AaiServiceImplTest {
AaiResponse<Services> aaiResponseServices = new AaiResponse<>(services, null, HttpStatus.SC_OK);
when(aaiClient.getSubscriberData(SUBSCRIBER_ID, false)).thenReturn(aaiResponseServices);
- when(roleValidator.isServicePermitted(eq(GLOBAL_CUSTOMER_ID), anyString())).thenReturn(Boolean.TRUE);
+ when(roleValidator.isServicePermitted(any())).thenReturn(Boolean.TRUE);
AaiResponse actualResponse = aaiService.getSubscriberData(SUBSCRIBER_ID, roleValidator, false);
List<ServiceSubscription> actualServiceSubscriptions = ((AaiResponse<Services>) actualResponse)
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
index 6aa67051e..4d6566f5b 100644
--- 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
@@ -20,35 +20,53 @@
package org.onap.vid.services;
+import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals;
+import static net.javacrumbs.jsonunit.core.Option.IGNORING_ARRAY_ORDER;
+import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.arrayWithSize;
import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.nullValue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.collect.ImmutableList;
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 org.jetbrains.annotations.NotNull;
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.AaiResponse;
+import org.onap.vid.aai.ServiceInstance;
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.OwningEntityResponse;
+import org.onap.vid.aai.model.ProjectResponse;
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.model.ServiceInstanceSearchResult;
import org.onap.vid.model.aaiTree.AAITreeNode;
-import org.onap.vid.roles.Role;
import org.onap.vid.roles.RoleValidator;
+import org.onap.vid.roles.RoleValidatorFactory;
+import org.onap.vid.roles.WithPermissionProperties;
+import org.onap.vid.testUtils.TestUtils;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
@@ -61,6 +79,9 @@ public class AaiServiceTest {
@Mock
private AaiClientInterface aaiClientInterface;
+ @Mock
+ private RoleValidatorFactory roleValidatorFactory;
+
@BeforeMethod
public void initMocks(){
MockitoAnnotations.initMocks(this);
@@ -68,7 +89,7 @@ public class AaiServiceTest {
@Test
public void testGetSpecificPnf(){
- Pnf pnf = new Pnf("11111", null, null, null, null, null, null);
+ Pnf pnf = Pnf.builder().withPnfId("11111").build();
AaiResponse<Pnf> aaiResponse = new AaiResponse<>(pnf, "aaaa", 200);
Mockito.doReturn(aaiResponse).when(aaiClientInterface).getSpecificPnf(Mockito.anyString());
AaiResponse<Pnf> specificPnf = aaiService.getSpecificPnf("1345667");
@@ -150,8 +171,6 @@ public class AaiServiceTest {
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},
@@ -162,14 +181,20 @@ public class AaiServiceTest {
}
@Test(dataProvider = "getTenantsData")
- public void testGetTenants(String userGlobalCustomerId, String userServiceType, String userTenantName, String serviceGlobalCustomerId,
- String serviceServiceType, String serviceTenantName, String serviceTenantId, boolean expectedIsPermitted) {
+ 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);
+
+ RoleValidator roleValidatorMock = mock(RoleValidator.class);
+ when(roleValidatorMock.isTenantPermitted(
+ eq(userGlobalCustomerId), eq(userServiceType),
+ (userTenantName == null) ? anyString() : eq(userTenantName))
+ ).thenReturn(true);
+
+ AaiResponse<GetTenantsResponse[]> actualTenants = aaiService.getTenants(serviceGlobalCustomerId, serviceServiceType, roleValidatorMock);
assertThat(actualTenants.getT(), arrayWithSize(1));
assertThat(actualTenants.getT()[0].tenantName, equalTo(serviceTenantName));
@@ -206,4 +231,112 @@ public class AaiServiceTest {
assertThat(anyMatch, equalTo(expectedMatch));
}
+ @DataProvider
+ public static Object[][] dataToDestroy() {
+ return new Object[][]{
+ {"nothing"}, {"relationship-list"}, {"relationship"}, {"relationship-data"} ,{"owning-entity-id"}
+ };
+ }
+
+
+ @Test(dataProvider = "dataToDestroy")
+ public void relatedOwningEntityId_givenInstanceAndOptionalError_extractCorrectlyOrReturnNull(String dataToDestroy) throws JsonProcessingException {
+ ServiceInstance serviceInstance = new ObjectMapper().readValue((""
+ + "{ "
+ + " \"service-instance-id\": \"5d521981-33be-4bb5-bb20-5616a9c52a5a\", "
+ + " \"service-instance-name\": \"dfgh\", "
+ + " \"service-type\": \"\", "
+ + " \"service-role\": \"\", "
+ + " \"environment-context\": \"null\", "
+ + " \"workload-context\": \"null\", "
+ + " \"model-invariant-id\": \"331a194d-9248-4533-88bc-62c812ccb5c1\", "
+ + " \"model-version-id\": \"171b3887-e73e-479d-8ef8-2690bf74f2aa\", "
+ + " \"resource-version\": \"1508832105498\", "
+ + " \"orchestration-status\": \"Active\", "
+ + " \"relationship-list\": { "
+ + " \"relationship\": [ "
+ + " { "
+ + " \"related-to\": \"project\", "
+ + " \"related-link\": \"/aai/v11/business/projects/project/Kennedy\", "
+ + " \"relationship-data\": [ "
+ + " { "
+ + " \"relationship-key\": \"project.project-name\", "
+ + " \"relationship-value\": \"Kennedy\" "
+ + " } "
+ + " ] "
+ + " }, "
+ + " { "
+ + " \"related-to\": \"owning-entity\", "
+ + " \"related-link\": \"/aai/v11/business/owning-entities/owning-entity/4d4ecf59-41f1-40d4-818d-885234680a42\", "
+ + " \"relationship-data\": [ "
+ + " { "
+ + " \"relationship-key\": \"owning-entity.owning-entity-id\", "
+ + " \"relationship-value\": \"4d4ecf59-41f1-40d4-818d-885234680a42\" "
+ + " } "
+ + " ] "
+ + " } "
+ + " ] "
+ + " } "
+ + "}").replace(dataToDestroy, "omitted"), ServiceInstance.class);
+
+ if (dataToDestroy.equals("nothing")) {
+ assertThat(aaiService.relatedOwningEntityId(serviceInstance), is("4d4ecf59-41f1-40d4-818d-885234680a42"));
+ } else {
+ assertThat(aaiService.relatedOwningEntityId(serviceInstance), is(nullValue()));
+ }
+ }
+
+ @Test
+ public void testGetServicesByOwningEntityId() {
+
+ //given
+ List<String> owningEntityIds = ImmutableList.of("43b8a85a-0421-4265-9069-117dd6526b8a", "26dcc4aa-725a-447d-8346-aa26dfaa4eb7");
+ OwningEntityResponse owningEntityResponse = TestUtils.readJsonResourceFileAsObject("/responses/aai/listServicesByOwningEntity.json", OwningEntityResponse.class);
+ when(aaiClientInterface.getServicesByOwningEntityId(owningEntityIds)).thenReturn(new AaiResponse<>(owningEntityResponse, "", 200));
+ RoleValidator roleValidator = createAlwaysTrueRoleValidator();
+
+ //when
+ List<ServiceInstanceSearchResult> result = aaiService.getServicesByOwningEntityId(owningEntityIds, roleValidator);
+
+ //then
+ ServiceInstanceSearchResult expected1 = new ServiceInstanceSearchResult(
+ "af9d52f9-13b2-4657-a198-463677f82dc0", "256cddb4-3aa1-43cc-a08f-315bb50b275e", "MSO-dev-service-type", "xbghrftgr_shani", null, null, null, "43b8a85a-0421-4265-9069-117dd6526b8a", true);
+ ServiceInstanceSearchResult expected2 = new ServiceInstanceSearchResult(
+ "49769492-5def-4c89-8e73-b236f958fa40", "e02fd6f2-7fc2-434b-a92d-15abdb24b68d", "JUST-another-service-type", "fghghfhgf", null, null, null, "43b8a85a-0421-4265-9069-117dd6526b8a", true);
+ ServiceInstanceSearchResult expected3 = new ServiceInstanceSearchResult(
+ "1d8fd482-2f53-4d62-a7bd-20e4bab14c45", "256cddb4-3aa1-43cc-a08f-315bb50b275e", "MSO-dev-service-type", "Bryant", null, null, null, "26dcc4aa-725a-447d-8346-aa26dfaa4eb7", true);
+
+ assertThat(result, jsonEquals(ImmutableList.of(expected1, expected2, expected3)).when(IGNORING_ARRAY_ORDER).whenIgnoringPaths("[*].subscriberName")); //ignore in array
+ }
+
+ @NotNull
+ private RoleValidator createAlwaysTrueRoleValidator() {
+ RoleValidator roleValidator = mock(RoleValidator.class);
+ when(roleValidator.isServicePermitted(any(WithPermissionProperties.class))).thenReturn(true);
+ return roleValidator;
+ }
+
+ @Test
+ public void testGetServicesByProjectNames() {
+
+ //given
+ List<String> projectNames = ImmutableList.of("x1", "y2");
+ ProjectResponse projectResponse = TestUtils.readJsonResourceFileAsObject("/responses/aai/listServicesByProject.json", ProjectResponse.class);
+ when(aaiClientInterface.getServicesByProjectNames(projectNames)).thenReturn(new AaiResponse<>(projectResponse, "", 200));
+ RoleValidator roleValidator = createAlwaysTrueRoleValidator();
+
+ //when
+ List<ServiceInstanceSearchResult> result = aaiService.getServicesByProjectNames(projectNames, roleValidator);
+
+ //then
+ ServiceInstanceSearchResult expected1 = new ServiceInstanceSearchResult(
+ "3f826016-3ac9-4928-9561-beee75fd91d5", "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", "Emanuel", "Lital_SRIOV2_001", null, null, null, null, true);
+ ServiceInstanceSearchResult expected2 = new ServiceInstanceSearchResult(
+ "7e4f8130-5dee-47c4-8770-1abc5f5ded83", "3d15d7ea-4174-49b6-89ec-e569381f7231", "vMOG", "justAname", null, null, null, null, true);
+ ServiceInstanceSearchResult expected3 = new ServiceInstanceSearchResult(
+ "ff2d9326-1ef5-4760-aba0-0eaf372ae675", "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", "Yoda", "anotherName", null, null, null, null, true);
+
+ assertThat(result, jsonEquals(ImmutableList.of(expected1, expected2, expected3)).when(IGNORING_ARRAY_ORDER).whenIgnoringPaths("[*].subscriberName")); //ignore in array
+ }
+
}
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 b9535000a..f61131770 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
@@ -22,7 +22,6 @@ package org.onap.vid.services;
import static java.util.Collections.emptyList;
import static java.util.Collections.emptyMap;
-import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
@@ -65,6 +64,7 @@ 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.model.ServiceInstantiationRequestDetails.UserParamNameAndValue;
import org.onap.vid.mso.rest.AsyncRequestStatus;
import org.onap.vid.mso.rest.RequestStatus;
import org.onap.vid.properties.Features;
@@ -237,7 +237,7 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests
testApi,
instanceId,
action.name(),
- UUID.randomUUID().toString(), null, null, null);
+ UUID.randomUUID().toString(), null, null, null, null);
}
private List<Map<String,String>> createInstanceParams() {
@@ -249,8 +249,10 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests
return instanceParams;
}
- protected VfModule createVfModule(String modelName, String modelVersionId, String modelCustomizationId,
- List<Map<String, String>> instanceParams, Map<String, String> supplementaryParams, String instanceName, String volumeGroupInstanceName, boolean isAlacarte) {
+ protected VfModule createVfModule(
+ String modelName, String modelVersionId, String modelCustomizationId,
+ List<Map<String, String>> instanceParams, List<UserParamNameAndValue> supplementaryParams, String instanceName,
+ String volumeGroupInstanceName, boolean isAlacarte, Boolean usePreload) {
ModelInfo vfModuleInfo = new ModelInfo();
vfModuleInfo.setModelType("vfModule");
vfModuleInfo.setModelName(modelName);
@@ -262,13 +264,14 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests
vfModuleInfo.setModelInvariantId("22222222-f63c-463e-ba94-286933b895f9");
vfModuleInfo.setModelVersion("10.0");
return new VfModule(vfModuleInfo, instanceName, volumeGroupInstanceName, Action.Create.name(), "mdt1", null,
- "88a6ca3ee0394ade9403f075db23167e", instanceParams, supplementaryParams, false, true, null, UUID.randomUUID().toString(), null, null,
- null, null, null);
+ "88a6ca3ee0394ade9403f075db23167e", instanceParams, supplementaryParams, false,
+ usePreload, null, UUID.randomUUID().toString(), null, null,
+ null, null, null, "originalName");
}
return new VfModule(vfModuleInfo, instanceName, volumeGroupInstanceName, Action.Create.name(), null, null, null,
instanceParams, supplementaryParams, false, false, null, UUID.randomUUID().toString(), null,
- null, null, null, null);
+ null, null, null, null, "originalName");
}
protected ModelInfo createVfModuleModelInfo(String modelName, String modelVersion, String modelVersionId, String modelInvariantId, String modelCustomizationId, String modelCustomizationName) {
@@ -276,9 +279,9 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests
}
protected VfModule createVfModuleForReplace(ModelInfo vfModuleModelInfo, String instanceName,
- String lcpCloudRegionId, String tenantId, Boolean retainAssignments, Boolean retainVolumeGroups, Map<String, String> supplementaryParams) {
+ String lcpCloudRegionId, String tenantId, Boolean retainAssignments, Boolean retainVolumeGroups, List<UserParamNameAndValue> supplementaryParams) {
return new VfModule( vfModuleModelInfo, instanceName, null, Action.Upgrade.name(), lcpCloudRegionId, null, tenantId,
- null, supplementaryParams, true, null, null, UUID.randomUUID().toString(), null, null, retainAssignments, retainVolumeGroups, null);
+ null, supplementaryParams, true, null, null, UUID.randomUUID().toString(), null, null, retainAssignments, retainVolumeGroups, null, "originalName");
}
protected ModelInfo createVnfModelInfo(boolean isAlacarte) {
@@ -349,9 +352,11 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests
Map<String, Map<String, VfModule>> vfModules = new HashMap<>();
List<Map<String, String>> instanceParams1 = ImmutableList.of((ImmutableMap.of("vmx_int_net_len", "24")));
- VfModule vfModule1 = createVfModule("201673MowAvpnVpeBvL..AVPN_base_vPE_BV..module-0", VF_MODULE_0_MODEL_VERSION_ID, VF_MODULE_0_MODEL_CUSTOMIZATION_NAME, instanceParams1, new HashMap<>(), (isUserProvidedNaming ? "vmxnjr001_AVPN_base_vPE_BV_base" : null), null, isAlacarte);
+ VfModule vfModule1 = createVfModule("201673MowAvpnVpeBvL..AVPN_base_vPE_BV..module-0", VF_MODULE_0_MODEL_VERSION_ID, VF_MODULE_0_MODEL_CUSTOMIZATION_NAME,
+ instanceParams1, emptyList(), (isUserProvidedNaming ? "vmxnjr001_AVPN_base_vPE_BV_base" : null), null, isAlacarte, true);
List<Map<String, String>> instanceParams2 = ImmutableList.of(vfModuleInstanceParamsMap);
- VfModule vfModule2 = createVfModule("201673MowAvpnVpeBvL..AVPN_vRE_BV..module-1", VF_MODULE_1_MODEL_VERSION_ID, VF_MODULE_1_MODEL_CUSTOMIZATION_NAME, instanceParams2, new HashMap<>(), (isUserProvidedNaming ? "vmxnjr001_AVPN_base_vRE_BV_expansion": null), (isUserProvidedNaming ? "myVgName" : null), isAlacarte);
+ VfModule vfModule2 = createVfModule("201673MowAvpnVpeBvL..AVPN_vRE_BV..module-1", VF_MODULE_1_MODEL_VERSION_ID, VF_MODULE_1_MODEL_CUSTOMIZATION_NAME,
+ instanceParams2, emptyList(), (isUserProvidedNaming ? "vmxnjr001_AVPN_base_vRE_BV_expansion": null), (isUserProvidedNaming ? "myVgName" : null), isAlacarte, true);
String vfModuleModelName = vfModule1.getModelInfo().getModelName();
vfModules.put(vfModuleModelName, new LinkedHashMap<>());
@@ -361,7 +366,7 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests
Vnf vnf = new Vnf(vnfModelInfo, "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", (isUserProvidedNaming ? VNF_NAME : null), Action.Create.name(),
"platformName", "mdt1", null, "88a6ca3ee0394ade9403f075db23167e", vnfInstanceParams,"lineOfBusinessName" , false, null, vfModules,
- UUID.randomUUID().toString(), null, null, null);
+ UUID.randomUUID().toString(), null, null, null, "originalName");
vnfs.put(vnf.getModelInfo().getModelName(), vnf);
return vnfs;
@@ -393,7 +398,7 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests
"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)
+ new VidNotions(InstantiationUI.TRANSPORT_SERVICE, ModelCategory.Transport, InstantiationUI.TRANSPORT_SERVICE, InstantiationType.Macro), "originalName"
);
return serviceInstantiation;
}
@@ -414,7 +419,7 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests
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, null));
+ false, null, UUID.randomUUID().toString(), null, null, null, "originalName"));
// 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));
}
@@ -430,7 +435,7 @@ public class AsyncInstantiationBaseTest extends AbstractTestNGSpringContextTests
modelInfo.setModelVersion("10.0");
return new InstanceGroup(modelInfo, (isUserProvidedNaming ? VNF_GROUP_NAME : null), action.name(), false, null, emptyMap(), UUID.randomUUID().toString(), null, null,
- null);
+ null, "originalName");
}
protected ModelInfo createServiceModelInfo() {
diff --git a/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBusinessLogicTest.java b/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBusinessLogicTest.java
index 7a6b94a1a..284efce45 100644
--- a/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBusinessLogicTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/services/AsyncInstantiationBusinessLogicTest.java
@@ -23,8 +23,10 @@ package org.onap.vid.services;
import static net.javacrumbs.jsonunit.JsonAssert.assertJsonEquals;
import static net.javacrumbs.jsonunit.JsonAssert.whenIgnoringPaths;
import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals;
+import static net.javacrumbs.jsonunit.JsonMatchers.jsonPartEquals;
import static net.javacrumbs.jsonunit.core.Option.IGNORING_ARRAY_ORDER;
import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.hasItem;
@@ -59,12 +61,14 @@ import static org.onap.vid.job.Job.JobStatus.PAUSE;
import static org.onap.vid.job.Job.JobStatus.PENDING;
import static org.onap.vid.job.Job.JobStatus.STOPPED;
import static org.onap.vid.testUtils.TestUtils.generateRandomAlphaNumeric;
+import static org.onap.vid.utils.KotlinUtilsKt.JACKSON_OBJECT_MAPPER;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
+import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
@@ -150,8 +154,6 @@ import org.testng.annotations.Test;
@ContextConfiguration(classes = {DataSourceConfig.class, SystemProperties.class, MockedAaiClientAndFeatureManagerConfig.class})
public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseTest {
-
-
@Mock
private JobAdapter jobAdapterMock;
@@ -1054,7 +1056,7 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT
public void whenLcpRegionNotEmpty_thenCloudRegionIdOfResourceIsLegacy() {
String legacyCloudRegion = "legacyCloudRegion";
Vnf vnf = new Vnf(new ModelInfo(), null, null, Action.Create.name(), null, "anyCloudRegion", legacyCloudRegion,
- null, null, null, false, null, null, UUID.randomUUID().toString(), null, null, null);
+ null, null, null, false, null, null, UUID.randomUUID().toString(), null, null, null, "originalName");
assertThat(vnf.getLcpCloudRegionId(), equalTo(legacyCloudRegion));
}
@@ -1063,7 +1065,7 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT
String legacyCloudRegion = "legacyCloudRegion";
ServiceInstantiation service = new ServiceInstantiation(new ModelInfo(), null, null, null, null, null, null,
null, null, "anyCloudRegion", legacyCloudRegion, null, null, null, null, null, null, null, null, null,
- false, 1,false, false, null, null, Action.Create.name(), UUID.randomUUID().toString(), null, null, null);
+ false, 1,false, false, null, null, Action.Create.name(), UUID.randomUUID().toString(), null, null, null, "originalName");
assertThat(service.getLcpCloudRegionId(), equalTo(legacyCloudRegion));
}
@@ -1087,7 +1089,7 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT
return new ServiceInstantiation(new ModelInfo(), null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null, null,
false, 1, false, isALaCarte, null, null, action.name(),
- UUID.randomUUID().toString(), null, null, null);
+ UUID.randomUUID().toString(), null, null, null, "originalName");
}
@DataProvider
@@ -1221,7 +1223,8 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT
String message = "Failed to create service instance";
return new Object[][]{
{500, message},
- {199, "{\"serviceException\":{\"messageId\":\"SVC2000\",\"text\":\"Error: " + message + "\"}}"}
+ {400, "{\"requestError\":{\"serviceException\":{\"messageId\":\"SVC0002\",\"text\":\"" + message + "\"}}}"},
+ {199, "{\"serviceException\":{\"messageId\":\"SVC2000\",\"text\":\"Error: " + message + "\"}}"},
};
}
@@ -1391,7 +1394,36 @@ public class AsyncInstantiationBusinessLogicTest extends AsyncInstantiationBaseT
{
String path = asyncInstantiationBL.getVfModuleReplacePath("myService", "myVNF", "myVFModule");
assertThat(path, equalTo("/serviceInstantiation/v7/serviceInstances/myService/vnfs/myVNF/vfModules/myVFModule/replace"));
+ }
+ @Test
+ public void whenCallClearStatusFromRequest_isFailedAndStatusAreRemoved() throws JsonProcessingException {
+ ServiceInstantiation serviceInstantiation = JACKSON_OBJECT_MAPPER.readValue(
+ "{"
+ + " \"modelInfo\": {"
+ + " \"modelType\": \"service\""
+ + " },"
+ + " \"isFailed\": true,"
+ + " \"statusMessage\": \"some status\","
+ + " \"vnfs\": {"
+ + " \"vProbe_NC_VNF\": {"
+ + " \"modelInfo\": {"
+ + " \"modelType\": \"vnf\""
+ + " },"
+ + " \"isFailed\": true,"
+ + " \"statusMessage\": \"other status\""
+ + " }"
+ + " }"
+ + "}",
+ ServiceInstantiation.class);
+ asyncInstantiationBL.clearStatusFromRequest(serviceInstantiation);
+ assertThat(serviceInstantiation, allOf(
+ jsonPartEquals("isFailed", false),
+ jsonPartEquals("statusMessage", null),
+ jsonPartEquals("vnfs.vProbe_NC_VNF.isFailed", false),
+ jsonPartEquals("vnfs.vProbe_NC_VNF.statusMessage", null)
+ ));
}
+
}
diff --git a/vid-app-common/src/test/java/org/onap/vid/services/InstantiationTemplatesServiceTest.java b/vid-app-common/src/test/java/org/onap/vid/services/InstantiationTemplatesServiceTest.java
index f09ea313c..de9fc2bcb 100644
--- a/vid-app-common/src/test/java/org/onap/vid/services/InstantiationTemplatesServiceTest.java
+++ b/vid-app-common/src/test/java/org/onap/vid/services/InstantiationTemplatesServiceTest.java
@@ -20,30 +20,45 @@
package org.onap.vid.services;
+import static java.lang.Boolean.FALSE;
+import static java.lang.Boolean.TRUE;
import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals;
+import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.anEmptyMap;
+import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasProperty;
+import static org.hamcrest.Matchers.nullValue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
+import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import java.util.Collection;
import java.util.Map;
import java.util.UUID;
import org.mockito.InjectMocks;
import org.mockito.Mock;
+import org.onap.vid.asdc.beans.Service;
import org.onap.vid.dal.AsyncInstantiationRepository;
import org.onap.vid.model.ModelUtil;
import org.onap.vid.model.serviceInstantiation.ServiceInstantiation;
import org.onap.vid.model.serviceInstantiation.ServiceInstantiationTemplate;
import org.onap.vid.model.serviceInstantiation.Vnf;
+import org.onap.vid.properties.Features;
import org.onap.vid.testUtils.TestUtils;
+import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
+import org.togglz.core.manager.FeatureManager;
public class InstantiationTemplatesServiceTest {
@@ -53,6 +68,9 @@ public class InstantiationTemplatesServiceTest {
@Mock
private ModelUtil modelUtil;
+ @Mock
+ private FeatureManager featureManager;
+
@InjectMocks
private InstantiationTemplatesService instantiationTemplatesService;
@@ -61,6 +79,11 @@ public class InstantiationTemplatesServiceTest {
TestUtils.initMockitoMocks(this);
}
+ @AfterMethod
+ public void resetMocks() {
+ reset(featureManager);
+ }
+
@Test
public void getJobRequestAsTemplate_whenIsCalled_asyncInstantiationRepositoryGetJobRequestIsInvoked() {
UUID jobId = UUID.randomUUID();
@@ -99,4 +122,49 @@ public class InstantiationTemplatesServiceTest {
assertThat(result, hasProperty("existingVRFCounterMap", anEmptyMap()));
}
+ @DataProvider
+ public static Object[][] isTemplatesExistsByGivenServiceUuid() {
+ return new Object[][]{{"1",TRUE},
+ {"3",FALSE}};
+ }
+
+ @Test(dataProvider = "isTemplatesExistsByGivenServiceUuid")
+ public void setInServicesTemplateValue_givenServiceWithServiceModelId_thenIsTemplateExistsIsEatherTrueOrFalse(String givenUuid, Boolean expectedTemplatesExist){
+
+ Service service = new Service();
+ service.setUuid(givenUuid);
+
+ Service newService = instantiationTemplatesService.setTemplateExistForService(service, ImmutableSet.of("1", "2"));
+ assertThat(newService.getIsInstantiationTemplateExists(), is(expectedTemplatesExist));
+ }
+
+ @Test
+ public void setTemplatesExistance_givenCollection__flagIsActive_thenSameCollectionReturnedWithTemplateExistsProperty(){
+ when(featureManager.isActive(Features.FLAG_2004_CREATE_ANOTHER_INSTANCE_FROM_TEMPLATE)).thenReturn(true);
+ when(asyncInstantiationRepository.getAllTemplatesServiceModelIds()).thenReturn(ImmutableSet.of("1", "2"));
+ Collection<Service> actualCollection = instantiationTemplatesService.setOnEachServiceIsTemplateExists(createGivenCollection());
+ assertThat(actualCollection, containsInAnyOrder(
+ allOf(hasProperty("uuid", is("1")), hasProperty("isInstantiationTemplateExists", is(true))),
+ allOf(hasProperty("uuid", is("3")), hasProperty("isInstantiationTemplateExists", is(false)))
+ ));
+ }
+
+ @Test
+ public void setTemplatesExistance_givenCollection_flagIsNotActive_thenTemplatesExistNotAdded(){
+ when(featureManager.isActive(Features.FLAG_2004_CREATE_ANOTHER_INSTANCE_FROM_TEMPLATE)).thenReturn(false);
+ Collection<Service> actualCollection = instantiationTemplatesService.setOnEachServiceIsTemplateExists(createGivenCollection());
+ assertThat("was " + actualCollection, actualCollection, containsInAnyOrder(
+ allOf(hasProperty("uuid", is("1")), hasProperty("isInstantiationTemplateExists", is(false))),
+ allOf(hasProperty("uuid", is("3")), hasProperty("isInstantiationTemplateExists", is(false)))
+ ));
+ }
+
+ private Collection<Service> createGivenCollection(){
+ Service service1 = new Service();
+ Service service2 = new Service();
+ service1.setUuid("1");
+ service2.setUuid("3");
+ return ImmutableList.of(service1, service2);
+ }
+
}
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
index efd9e2b27..71d38b3f8 100644
--- 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
@@ -21,6 +21,10 @@
package org.onap.vid.services;
import static com.google.common.collect.Maps.newHashMap;
+import static java.util.Collections.EMPTY_LIST;
+import static java.util.Collections.EMPTY_MAP;
+import static java.util.Collections.emptyList;
+import static java.util.Collections.singletonList;
import static net.javacrumbs.jsonunit.JsonMatchers.jsonEquals;
import static net.javacrumbs.jsonunit.JsonMatchers.jsonNodeAbsent;
import static net.javacrumbs.jsonunit.JsonMatchers.jsonPartEquals;
@@ -41,7 +45,6 @@ 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;
@@ -78,7 +81,7 @@ 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.UserParamMap;
+import org.onap.vid.mso.model.ServiceInstantiationRequestDetails.UserParamNameAndValue;
import org.onap.vid.mso.model.VfModuleMacro;
import org.onap.vid.mso.model.VfModuleOrVolumeGroupRequestDetails;
import org.onap.vid.mso.model.VnfInstantiationRequestDetails;
@@ -163,7 +166,7 @@ public class MsoRequestBuilderTest extends AsyncInstantiationBaseTest {
private void createMacroServiceInfo_WithUserProvidedNamingFalse_ServiceInfoIsAsExpected(boolean withVfmodules, boolean disabledHoming) throws IOException {
ServiceInstantiation serviceInstantiationPayload = generateMockMacroServiceInstantiationPayload(true,
- createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, Collections.EMPTY_LIST, false),
+ createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, EMPTY_LIST, false),
1,
false, PROJECT_NAME, true);
URL resource;
@@ -181,7 +184,7 @@ public class MsoRequestBuilderTest extends AsyncInstantiationBaseTest {
msoRequestBuilder.generateMacroServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016");
String expected = IOUtils.toString(resource, "UTF-8");
- MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
+ assertThat(result, jsonEquals(expected));
}
@Test
@@ -233,7 +236,7 @@ public class MsoRequestBuilderTest extends AsyncInstantiationBaseTest {
}
private ServiceInstantiation generateALaCarteServiceDeletionPayload() {
- return generateMockAlaCarteServiceDeletionPayload(false, Collections.EMPTY_MAP, Collections.EMPTY_MAP, Collections.EMPTY_MAP, 1, true, PROJECT_NAME, false, "VNF_API", "1234567890");
+ return generateMockAlaCarteServiceDeletionPayload(false, EMPTY_MAP, EMPTY_MAP, EMPTY_MAP, 1, true, PROJECT_NAME, false, "VNF_API", "1234567890");
}
@Test
@@ -255,7 +258,7 @@ public class MsoRequestBuilderTest extends AsyncInstantiationBaseTest {
}
private ServiceInstantiation generateServiceDeletionPayload() {
- return generateMockServiceDeletionPayload(false, Collections.EMPTY_MAP, Collections.EMPTY_MAP, Collections.EMPTY_MAP, 1, true, PROJECT_NAME, false, "VNF_API", "1234567890");
+ return generateMockServiceDeletionPayload(false, EMPTY_MAP, EMPTY_MAP, EMPTY_MAP, 1, true, PROJECT_NAME, false, "VNF_API", "1234567890");
}
@DataProvider
@@ -301,7 +304,7 @@ public class MsoRequestBuilderTest extends AsyncInstantiationBaseTest {
public static Object[][] testBuildVnfInstanceParamsDataProvider(Method test) {
return new Object[][]{
{
- Collections.EMPTY_LIST,
+ EMPTY_LIST,
ImmutableList.of(
ImmutableList.of(ImmutableMap.of("k1", "v1", "k2", "v2")),
ImmutableList.of(ImmutableMap.of("k3", "v3", "k2", "v2"))
@@ -313,23 +316,23 @@ public class MsoRequestBuilderTest extends AsyncInstantiationBaseTest {
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(EMPTY_MAP),
+ singletonList(null)
),
ImmutableList.of(ImmutableMap.of("k1", "v1", "k2", "v2", "k3", "v3", "j1", "w1"))
},
{
- Collections.EMPTY_LIST,
+ EMPTY_LIST,
Arrays.asList(null, null),
- Collections.EMPTY_LIST //mso is expect to empty list and not list with empty map
+ EMPTY_LIST //mso is expect to empty list and not list with empty map
},
{
- ImmutableList.of(Collections.EMPTY_MAP),
+ ImmutableList.of(EMPTY_MAP),
ImmutableList.of(
- ImmutableList.of(Collections.EMPTY_MAP),
- ImmutableList.of(Collections.EMPTY_MAP)
+ ImmutableList.of(EMPTY_MAP),
+ ImmutableList.of(EMPTY_MAP)
),
- Collections.EMPTY_LIST //mso is expect to empty list and not list with empty map
+ EMPTY_LIST //mso is expect to empty list and not list with empty map
}
};
}
@@ -347,24 +350,27 @@ public class MsoRequestBuilderTest extends AsyncInstantiationBaseTest {
@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"}
+ {"cc3514e3-5a33-55df-13ab-12abad84e7cc", true, false, "/payload_jsons/vfmodule_instantiation_request.json"},
+ {null, true, null, "/payload_jsons/vfmodule_instantiation_request_without_volume_group.json"},
+ {null, false, true, "/payload_jsons/vfmodule_instantiation_request_without_instance_name.json"}
};
}
@Test(dataProvider = "vfModuleRequestDetails")
- public void createVfModuleRequestDetails_detailsAreAsExpected(String volumeGroupInstanceId, boolean isUserProvidedNaming, String fileName) throws IOException {
+ public void createVfModuleRequestDetails_detailsAreAsExpected(String volumeGroupInstanceId, boolean isUserProvidedNaming, Boolean usePreload, 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");
+ List<UserParamNameAndValue> supplementaryParams = ImmutableList.of(
+ new UserParamNameAndValue("vre_a_volume_size_0", "100"),
+ new UserParamNameAndValue("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);
+ (isUserProvidedNaming ? "vmxnjr001_AVPN_base_vRE_BV_expansion" : null), "myVgName", true, usePreload);
String serviceInstanceId = "aa3514e3-5a33-55df-13ab-12abad84e7aa";
String vnfInstanceId = "bb3514e3-5a33-55df-13ab-12abad84e7bb";
@@ -378,26 +384,7 @@ public class MsoRequestBuilderTest extends AsyncInstantiationBaseTest {
final RequestDetailsWrapper<VfModuleOrVolumeGroupRequestDetails> 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<UserParamMap<String, String>> expected) {
- List<UserParamMap<String, String>> aggParams = msoRequestBuilder.aggregateAllInstanceParams(instanceParams, suppParams);
- assertThat("Aggregated params are not as expected", aggParams, equalTo(expected));
+ assertThat(result, jsonEquals(expected).when(IGNORING_ARRAY_ORDER));
}
@Test
@@ -406,10 +393,11 @@ public class MsoRequestBuilderTest extends AsyncInstantiationBaseTest {
VfModule vfModule = createVfModule("201673MowAvpnVpeBvL..AVPN_vRE_BV..module-1",
"56e2b103-637c-4d1a-adc8-3a7f4a6c3240",
"72d9d1cd-f46d-447a-abdb-451d6fb05fa8",
- Collections.emptyList(),
- Collections.emptyMap(),
+ emptyList(),
+ emptyList(),
"vmxnjr001_AVPN_base_vRE_BV_expansion",
"myVgName",
+ true,
true);
vfModule.getModelInfo().setModelInvariantId("ff5256d2-5a33-55df-13ab-12abad84e7ff");
vfModule.getModelInfo().setModelVersion("1");
@@ -437,7 +425,7 @@ public class MsoRequestBuilderTest extends AsyncInstantiationBaseTest {
@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"));
+ List<NetworkDetails> networkDetails = 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";
@@ -495,7 +483,7 @@ public class MsoRequestBuilderTest extends AsyncInstantiationBaseTest {
@Test
public void checkIfNullProjectNameSentToMso() {
ServiceInstantiation serviceInstantiationPayload = generateMockMacroServiceInstantiationPayload(true,
- createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, Collections.EMPTY_LIST, false),
+ createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, EMPTY_LIST, false),
1,
false, null, false);
RequestDetailsWrapper<ServiceInstantiationRequestDetails> result =
@@ -503,7 +491,7 @@ public class MsoRequestBuilderTest extends AsyncInstantiationBaseTest {
JsonNode jsonNode = new ObjectMapper().valueToTree(result.requestDetails);
Assert.assertTrue(jsonNode.get("project").isNull());
serviceInstantiationPayload = generateMockMacroServiceInstantiationPayload(true,
- createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, Collections.EMPTY_LIST, false),
+ createVnfList(vfModuleInstanceParamsMapWithParamsToRemove, EMPTY_LIST, false),
1,
false, "not null", false);
result = msoRequestBuilder.generateMacroServiceInstantiationRequest(null, serviceInstantiationPayload, serviceInstantiationPayload.getInstanceName(), "az2016");
@@ -538,7 +526,7 @@ public class MsoRequestBuilderTest extends AsyncInstantiationBaseTest {
"}";
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,
- null);
+ null, "originalName");
RequestDetailsWrapper<VnfInstantiationRequestDetails> result =
msoRequestBuilder.generateDeleteVnfRequest(vnfDetails, "az2018");
MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
@@ -569,7 +557,8 @@ public class MsoRequestBuilderTest extends AsyncInstantiationBaseTest {
" }" +
" }" +
"}";
- 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);
+ VfModule vfModuleDetails = createVfModule("201673MowAvpnVpeBvL..AVPN_base_vPE_BV..module-0", VF_MODULE_0_MODEL_VERSION_ID, VF_MODULE_0_MODEL_CUSTOMIZATION_NAME,
+ null, emptyList(), "vmxnjr001_AVPN_base_vPE_BV_base", null, true, true);
RequestDetailsWrapper<VfModuleOrVolumeGroupRequestDetails> result =
msoRequestBuilder.generateDeleteVfModuleRequest(vfModuleDetails, "az2018");
MsoOperationalEnvironmentTest.assertThatExpectationIsLikeObject(expected, result);
@@ -636,16 +625,25 @@ public class MsoRequestBuilderTest extends AsyncInstantiationBaseTest {
@Test
public void generateReplaceVfModuleRequest_whenThereAreSupplementaryParams_thenTheyAreAddToUserParams() {
- String expectedParams = "[{"
- + " \"vre_a_volume_size_0\" : \"100\","
- + " \"vmx_int_net_len\" : \"24\","
- + " \"availability_zone_0\": \"abc\""
- + " }]";
-
- Map<String, String> supplementaryParams = ImmutableMap.of(
- "vre_a_volume_size_0", "100",
- "vmx_int_net_len", "24",
- "availability_zone_0", "abc"
+ String expectedParams = "["
+ + " {"
+ + " \"name\": \"vre_a_volume_size_0\","
+ + " \"value\": \"100\""
+ + " },"
+ + " {"
+ + " \"name\": \"vmx_int_net_len\","
+ + " \"value\": \"24\""
+ + " },"
+ + " {"
+ + " \"name\": \"availability_zone_0\","
+ + " \"value\": \"abc\""
+ + " }"
+ + " ]";
+
+ List<UserParamNameAndValue> supplementaryParams = ImmutableList.of(
+ new UserParamNameAndValue( "vre_a_volume_size_0", "100"),
+ new UserParamNameAndValue("vmx_int_net_len", "24"),
+ new UserParamNameAndValue("availability_zone_0", "abc")
);
assertThat(generatedVfModuleReplaceRequest(null, null, supplementaryParams),
@@ -662,7 +660,7 @@ public class MsoRequestBuilderTest extends AsyncInstantiationBaseTest {
}
private RequestDetailsWrapper<VfModuleOrVolumeGroupRequestDetails> generatedVfModuleReplaceRequest(
- Boolean retainAssignments, Boolean retainVolumeGroups, Map<String, String> supplementaryParams) {
+ Boolean retainAssignments, Boolean retainVolumeGroups, List<UserParamNameAndValue> supplementaryParams) {
when(featureManager.isActive(Features.FLAG_1810_CR_ADD_CLOUD_OWNER_TO_MSO_REQUEST)).thenReturn(true);
when(aaiClient.getCloudOwnerByCloudRegionId("regionOne")).thenReturn("irma-aic");
diff --git a/vid-app-common/src/test/java/org/onap/vid/services/UserParamsContainerTest.kt b/vid-app-common/src/test/java/org/onap/vid/services/UserParamsContainerTest.kt
new file mode 100644
index 000000000..511c4e5cb
--- /dev/null
+++ b/vid-app-common/src/test/java/org/onap/vid/services/UserParamsContainerTest.kt
@@ -0,0 +1,57 @@
+package org.onap.vid.services
+
+import org.hamcrest.CoreMatchers.equalTo
+import org.hamcrest.MatcherAssert
+import org.onap.vid.mso.model.ServiceInstantiationRequestDetails.UserParamNameAndValue
+import org.testng.annotations.DataProvider
+import org.testng.annotations.Test
+
+class UserParamsContainerTest {
+
+ @DataProvider
+ fun userParamsDataProvider(): Array<Array<Any?>>? {
+ return arrayOf(
+ arrayOf<Any?>(
+ mapOf("a" to "b", "c" to "d"),
+ listOf(UserParamNameAndValue("e", "f"), UserParamNameAndValue("g", "h")),
+ mapOf("c" to "d", "a" to "b", "e" to "f", "g" to "h")
+ ),
+ arrayOf<Any?>(
+ mapOf("a" to "b", "c" to "g"),
+ listOf(UserParamNameAndValue("c", "d") , UserParamNameAndValue("e", "f")),
+ mapOf("c" to "d", "a" to "b", "e" to "f")
+ ),
+ arrayOf<Any?>(
+ emptyMap<String,String>(),
+ listOf(UserParamNameAndValue("c", "d"), UserParamNameAndValue("e", "f")),
+ mapOf("c" to "d", "e" to "f")
+ ),
+ arrayOf<Any?>(
+ mapOf("a" to "b", "c" to "d"),
+ emptyList<UserParamNameAndValue>(),
+ mapOf("a" to "b", "c" to "d")
+ ),
+ arrayOf<Any?>(
+ emptyMap<String,String>(),
+ emptyList<UserParamNameAndValue>(),
+ emptyMap<String,String>()
+ ),
+ arrayOf(
+ null,
+ emptyList<UserParamNameAndValue>(),
+ emptyMap<String,String>()
+ ),
+ arrayOf<Any?>(
+ emptyMap<String,String>(),
+ null,
+ emptyMap<String,String>()
+ )
+ )
+ }
+
+ @Test(dataProvider = "userParamsDataProvider")
+ fun testUserParamsConvertorCtor(instanceParams: Map<String, String>?, suppParams: List<UserParamNameAndValue>?, expected: Map<String, String>) {
+ val aggParams: Map<String, String> = UserParamsContainer(instanceParams, suppParams).params
+ MatcherAssert.assertThat("Aggregated params are not as expected", aggParams, equalTo(expected))
+ }
+} \ No newline at end of file
diff --git a/vid-app-common/src/test/java/org/onap/vid/testUtils/TestUtils.java b/vid-app-common/src/test/java/org/onap/vid/testUtils/TestUtils.java
index 862b8db8f..71f7ee015 100644
--- a/vid-app-common/src/test/java/org/onap/vid/testUtils/TestUtils.java
+++ b/vid-app-common/src/test/java/org/onap/vid/testUtils/TestUtils.java
@@ -21,9 +21,7 @@
package org.onap.vid.testUtils;
import static com.fasterxml.jackson.module.kotlin.ExtensionsKt.jacksonObjectMapper;
-import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
-import static java.util.stream.Collectors.toMap;
import static org.apache.commons.beanutils.PropertyUtils.getPropertyDescriptors;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.apache.commons.text.CharacterPredicates.DIGITS;
@@ -52,7 +50,9 @@ import java.lang.reflect.Field;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
+import java.util.Collections;
import java.util.Iterator;
+import java.util.LinkedList;
import java.util.List;
import java.util.function.Predicate;
import javax.ws.rs.client.Client;
@@ -61,7 +61,6 @@ import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
@@ -174,15 +173,27 @@ public class TestUtils {
}
public static String[] allPropertiesOf(Class<?> aClass) {
- return Arrays.stream(getPropertyDescriptors(aClass))
+ return getPropertyDescriptorsRecursively(aClass).stream()
.map(PropertyDescriptor::getDisplayName)
+ .distinct()
.toArray(String[]::new);
}
+ private static List<PropertyDescriptor> getPropertyDescriptorsRecursively(Class<?> aClass) {
+ List<PropertyDescriptor> result = new LinkedList<>();
+
+ for (Class<?> i = aClass; i != null && i != Object.class; i = i.getSuperclass()) {
+ Collections.addAll(result, getPropertyDescriptors(i));
+ }
+
+ return result;
+ }
+
private static <T> List<String> allStringPropertiesOf(T object) {
- return Arrays.stream(getPropertyDescriptors(object.getClass()))
+ return getPropertyDescriptorsRecursively(object.getClass()).stream()
.filter(descriptor -> descriptor.getPropertyType().isAssignableFrom(String.class))
.map(PropertyDescriptor::getDisplayName)
+ .distinct()
.collect(toList());
}
@@ -221,16 +232,15 @@ public class TestUtils {
* @return The modified object
*/
public static <T> T setStringsInStringProperties(T object) {
- try {
- final List<String> stringFields = allStringPropertiesOf(object);
-
- BeanUtils.populate(object, stringFields.stream()
- .collect(toMap(identity(), identity())));
+ allStringPropertiesOf(object).forEach(it -> {
+ try {
+ FieldUtils.writeField(object, it, it, true);
+ } catch (IllegalAccessException e) {
+ // YOLO
+ }
+ });
- return object;
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
+ return object;
}
public static void registerCloudConfigurationValueGenerator() {